made a multi threaded version of ht2crack2search since the file lookups should benefi...
[RRG-proxmark3.git] / armsrc / lfops.c
blob1748522d407e757efddaedfac72aa2265a2233c8
1 //-----------------------------------------------------------------------------
2 // Copyright (C) Jonathan Westhues, 2005
3 // Copyright (C) Proxmark3 contributors. See AUTHORS.md for details.
4 //
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.
9 //
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 //-----------------------------------------------------------------------------
22 #include "lfops.h"
24 #include "proxmark3_arm.h"
25 #include "cmd.h"
26 #include "BigBuf.h"
27 #include "fpgaloader.h"
28 #include "ticks.h"
29 #include "dbprint.h"
30 #include "util.h"
31 #include "commonutil.h"
33 #include "crc16.h"
34 #include "string.h"
35 #include "printf.h"
36 #include "lfdemod.h"
37 #include "lfsampling.h"
38 #include "protocols.h"
39 #include "pmflash.h"
40 #include "flashmem.h" // persistence on flash
41 #include "appmain.h" // print stack
44 Notes about EM4xxx timings.
46 The timing values differs between cards, we got EM410x, EM43x5, EM445x etc.
47 We are trying to unify and enable the Proxmark3 to easily detect and select correct timings automatic.
48 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
49 still benefit from this repo. This is why its configurable and we use to set these dynamic settings in device external flash memory.
52 // VALUES TAKEN FROM EM4x function: SendForward
53 // START_GAP = 440; (55*8) cycles at 125kHz (8us = 1cycle)
54 // WRITE_GAP = 128; (16*8)
55 // WRITE_1 = 256 32*8; (32*8)
57 // These timings work for 4469/4269/4305 (with the 55*8 above)
58 // WRITE_0 = 23*8 , 9*8
60 Not about ARM TIMERS
61 Short note about timers on Proxmark device ARM. They are a bit differently implemented and gives decent correctness.
63 SAM7S has several timers, we will use the source TIMER_CLOCK1 (aka AT91C_TC_CLKS_TIMER_DIV1_CLOCK)
64 TIMER_CLOCK1 = MCK/2, MCK is running at 48 MHz, Timer is running at 48/2 = 24 MHz
66 New timer implementation in ticks.c, which is used in LFOPS.c
67 1 μs = 1.5 ticks
68 1 fc = 8 μs = 12 ticks
70 Terms you find in different datasheets and how they match.
71 1 Cycle = 8 microseconds (μs) == 1 field clock (fc)
73 Note about HITAG timing
74 Hitag units (T0) have duration of 8 microseconds (us), which is 1/125000 per second (carrier)
75 T0 = TIMER_CLOCK1 / 125000 = 192
78 ==========================================================================================================
79 T55x7 Timing
80 ==========================================================================================================
82 ATA5577 Downlink Protocol Timings.
83 Note: All absolute times assume TC = 1 / fC = 8 μs (fC = 125 kHz)
85 Note: These timings are from the datasheet and doesn't map the best to the features of the RVD4 LF antenna.
86 RDV4 LF antenna has high voltage and the drop of power when turning off the rf field takes about 1-2 TC longer.
88 -----------------------------------------------------------------------
89 Fixed-bit-length Protocol | Normal Downlink | Fast Downlink |
90 ------------------------------+-----------------------------------+-----------------------------------+------
91 | Parameter | Remark | Symbol | Min. | Typ. | Max. | Min. | Typ. | Max. | Unit |
92 |------------+--------+--------+-----------+-----------+-----------+-----------+-----------+-----------+------|
93 | Start gap | | Sgap | 8 | 15 | 50 | 8 | 15 | 50 | Tc |
94 | Write gap | | Wgap | 8 | 10 | 20 | 8 | 10 | 20 | Tc |
95 |------------+--------+--------+-----------+-----------+-----------+-----------+-----------+-----------+------|
96 | coding | 0 data | d0 | 16 | 24 | 32 | 8 | 12 | 16 | Tc |
97 | | 1 data | d1 | 48 | 56 | 64 | 24 | 28 | 32 | Tc |
98 -------------------------------------------------------------------------------------------------------------
100 -----------------------------------------------------------------------
101 Long Leading Reference | Normal Downlink | Fast Downlink |
102 ------------------------------+-----------------------------------+-----------------------------------+------
103 | Parameter | Remark | Symbol | Min. | Typ. | Max. | Min. | Typ. | Max. | Unit |
104 |-----------+--------+---------+-----------+-----------+-----------+-----------+-----------+-----------+------|
105 | Start gap | | Sgap | 8 | 10 | 50 | 8 | 10 | 50 | Tc |
106 | Write gap | | Wgap | 8 | 10 | 20 | 8 | 10 | 20 | Tc |
107 |-----------+--------+---------+-----------+-----------+-----------+-----------+-----------+-----------+------|
108 | Write | Ref | | 152 | 160 | 168 | 140 | 144 | 148 | Tc |
109 | data | Pulse | dref | 136 clocks + 0 data bit | 132 clocks + 0 data bit | Tc |
110 | coding |--------+---------+-----------------------------------+-----------------------------------+------|
111 | | 0 data | d0 |dref – 143 |dref – 136 |dref – 128 |dref – 135 |dref – 132 |dref – 124 | Tc |
112 | | 1 data | d1 |dref – 111 |dref – 104 |dref – 96 |dref – 119 |dref – 116 |dref – 112 | Tc |
113 -------------------------------------------------------------------------------------------------------------
115 -----------------------------------------------------------------------
116 Leading-zero Reference | Normal Downlink | Fast Downlink |
117 ------------------------------+-----------------------------------+-----------------------------------+------
118 | Parameter | Remark | Symbol | Min. | Typ. | Max. | Min. | Typ. | Max. | Unit |
119 |-----------+--------+---------+-----------+-----------+-----------+-----------+-----------+-----------+------|
120 | Start gap | | Sgap | 8 | 10 | 50 | 8 | 10 | 50 | Tc |
121 | Write gap | | Wgap | 8 | 10 | 20 | 8 | 10 | 20 | Tc |
122 |-----------+--------+---------+-----------+-----------+-----------+-----------+-----------+-----------+------|
123 | Write | Ref | dref | 12 | – | 72 | 8 | – | 68 | Tc |
124 | data | 0 data | d0 | dref – 7 | dref | dref + 8 | dref – 3 | dref | dref + 4 | Tc |
125 | coding | 1 data | d1 | dref + 9 | dref + 16 | dref + 24 | dref + 5 | dref + 8 | dref + 12 | Tc |
126 -------------------------------------------------------------------------------------------------------------
128 -----------------------------------------------------------------------
129 1-of-4 Coding | Normal Downlink | Fast Downlink |
130 ------------------------------+-----------------------------------+-----------------------------------+------
131 | Parameter | Remark | Symbol | Min. | Typ. | Max. | Min. | Typ. | Max. | Unit |
132 |-----------+--------+---------+-----------+-----------+-----------+-----------+-----------+-----------+------|
133 | Start gap | | Sgap | 8 | 10 | 50 | 8 | 10 | 50 | Tc |
134 | Write gap | | Wgap | 8 | 10 | 20 | 8 | 10 | 20 | Tc |
135 |-----------+--------+---------+-----------+-----------+-----------+-----------+-----------+-----------+------|
136 | Write | Ref 00 | dref | 8 | – | 68 | 12 | – | 72 | Tc |
137 | data |00 data | d00 | dref – 7 | dref | dref + 8 | dref – 3 | dref | dref+ 4 | Tc |
138 | coding |01 data | d01 | dref + 9 | dref + 16 | dref + 24 | dref + 5 | dref + 8 | dref + 12 | Tc |
139 | |10 data | d10 | dref + 25 | dref + 32 | dref + 40 | dref + 13 | dref + 16 | dref + 20 | Tc |
140 | |11 data | d11 | dref + 41 | dref + 48 | dref + 56 | dref + 21 | dref + 24 | dref + 28 | Tc |
141 -------------------------------------------------------------------------------------------------------------
143 Initial values if not in flash
145 SG = Start gap
146 WG = Write gap
147 RG = Read gap
149 Explanations for array T55xx_Timing below
151 0 1 2 3
152 SG WG Bit 00 Bit 01 Bit 10 Bit 11 RG
153 --------------------------------------------------------------------
154 { 29 , 17 , 15 , 47 , 0 , 0 , 15 }, // Default Fixed
155 { 29 , 17 , 15 , 50 , 0 , 0 , 15 }, // Long Leading Ref.
156 { 29 , 17 , 15 , 40 , 0 , 0 , 15 }, // Leading 0
157 { 29 , 17 , 15 , 31 , 47 , 63 , 15 } // 1 of 4
159 static t55xx_configurations_t T55xx_Timing = {
161 #ifdef WITH_FLASH
162 // PM3RDV4
163 { 29 * 8, 17 * 8, 15 * 8, 47 * 8, 15 * 8, 0, 0 }, // Default Fixed
164 { 29 * 8, 17 * 8, 15 * 8, 47 * 8, 15 * 8, 0, 0 }, // Long Leading Ref.
165 { 29 * 8, 17 * 8, 15 * 8, 40 * 8, 15 * 8, 0, 0 }, // Leading 0
166 { 29 * 8, 17 * 8, 15 * 8, 31 * 8, 15 * 8, 47 * 8, 63 * 8 } // 1 of 4
167 #else
168 // PM3GENERIC or like official repo
169 { 31 * 8, 20 * 8, 18 * 8, 50 * 8, 15 * 8, 0, 0 }, // Default Fixed
170 { 31 * 8, 20 * 8, 18 * 8, 50 * 8, 15 * 8, 0, 0 }, // Long Leading Ref.
171 { 31 * 8, 20 * 8, 18 * 8, 40 * 8, 15 * 8, 0, 0 }, // Leading 0
172 { 31 * 8, 20 * 8, 18 * 8, 34 * 8, 15 * 8, 50 * 8, 66 * 8 } // 1 of 4
173 #endif
178 // Some defines for readability
179 #define T55XX_DLMODE_FIXED 0 // Default Mode
180 #define T55XX_DLMODE_LLR 1 // Long Leading Reference
181 #define T55XX_DLMODE_LEADING_ZERO 2 // Leading Zero
182 #define T55XX_DLMODE_1OF4 3 // 1 of 4
183 #define T55XX_LONGLEADINGREFERENCE 4 // Value to tell Write Bit to send long reference
185 // ATA55xx shared presets & routines
186 static uint32_t GetT55xxClockBit(uint8_t clock) {
187 switch (clock) {
188 case 128:
189 return T55x7_BITRATE_RF_128;
190 case 100:
191 return T55x7_BITRATE_RF_100;
192 case 64:
193 return T55x7_BITRATE_RF_64;
194 case 50:
195 return T55x7_BITRATE_RF_50;
196 case 40:
197 return T55x7_BITRATE_RF_40;
198 case 32:
199 return T55x7_BITRATE_RF_32;
200 case 16:
201 return T55x7_BITRATE_RF_16;
202 case 8:
203 return T55x7_BITRATE_RF_8;
204 default :
205 return 0;
209 void printT55xxConfig(void) {
211 #define PRN_NA sprintf(s + strlen(s), _RED_("n/a") " | ");
213 DbpString(_CYAN_("LF T55XX config"));
214 Dbprintf(" [r] [a] [b] [c] [d] [e] [f] [g]");
215 Dbprintf(" mode |start|write|write|write| read|write|write");
216 Dbprintf(" | gap | gap | 0 | 1 | gap | 2 | 3");
217 Dbprintf("---------------------------+-----+-----+-----+-----+-----+-----+------");
219 for (uint8_t i = 0; i < 4; i++) {
221 char s[160];
222 memset(s, 0, sizeof(s));
224 switch (i) {
225 case T55XX_DLMODE_FIXED :
226 sprintf(s, _YELLOW_("fixed bit length") _GREEN_(" (default)") " |");
227 break;
228 case T55XX_DLMODE_LLR :
229 sprintf(s, _YELLOW_(" long leading reference") " |");
230 break;
231 case T55XX_DLMODE_LEADING_ZERO :
232 sprintf(s, _YELLOW_(" leading zero") " |");
233 break;
234 case T55XX_DLMODE_1OF4 :
235 sprintf(s, _YELLOW_(" 1 of 4 coding reference") " |");
236 break;
237 default:
238 break;
241 if (T55xx_Timing.m[i].start_gap != 0xFFFF) {
242 sprintf(s + strlen(s), " %3d | ", T55xx_Timing.m[i].start_gap / 8);
243 } else {
244 PRN_NA;
247 if (T55xx_Timing.m[i].write_gap != 0xFFFF) {
248 sprintf(s + strlen(s), "%3d | ", T55xx_Timing.m[i].write_gap / 8);
249 } else {
250 PRN_NA;
253 if (T55xx_Timing.m[i].write_0 != 0xFFFF) {
254 sprintf(s + strlen(s), "%3d | ", T55xx_Timing.m[i].write_0 / 8);
255 } else {
256 PRN_NA;
259 if (T55xx_Timing.m[i].write_1 != 0xFFFF) {
260 sprintf(s + strlen(s), "%3d | ", T55xx_Timing.m[i].write_1 / 8);
261 } else {
262 PRN_NA;
265 if (T55xx_Timing.m[i].read_gap != 0xFFFF) {
266 sprintf(s + strlen(s), "%3d | ", T55xx_Timing.m[i].read_gap / 8);
267 } else {
268 PRN_NA;
271 if (T55xx_Timing.m[i].write_2 != 0xFFFF && i == T55XX_DLMODE_1OF4) {
272 sprintf(s + strlen(s), "%3d | ", T55xx_Timing.m[i].write_2 / 8);
273 } else {
274 PRN_NA
277 if (T55xx_Timing.m[i].write_3 != 0xFFFF && i == T55XX_DLMODE_1OF4) {
278 sprintf(s + strlen(s), "%3d | ", T55xx_Timing.m[i].write_3 / 8);
279 } else {
280 PRN_NA;
283 // remove last space
284 s[strlen(s)] = 0;
285 DbpStringEx(FLAG_LOG, s, sizeof(s));
287 DbpString("");
290 void setT55xxConfig(uint8_t arg0, const t55xx_configurations_t *c) {
291 for (uint8_t i = 0; i < 4; i++) {
292 if (c->m[i].start_gap != 0)
293 T55xx_Timing.m[i].start_gap = c->m[i].start_gap;
295 if (c->m[i].write_gap != 0)
296 T55xx_Timing.m[i].write_gap = c->m[i].write_gap;
298 if (c->m[i].write_0 != 0)
299 T55xx_Timing.m[i].write_0 = c->m[i].write_0;
301 if (c->m[i].write_1 != 0)
302 T55xx_Timing.m[i].write_1 = c->m[i].write_1;
304 if (i == T55XX_DLMODE_1OF4) {
305 if (c->m[i].write_2 != 0)
306 T55xx_Timing.m[i].write_2 = c->m[i].write_2;
308 if (c->m[i].write_3 != 0)
309 T55xx_Timing.m[i].write_3 = c->m[i].write_3;
311 } else {
312 T55xx_Timing.m[i].write_2 = 0x00;
313 T55xx_Timing.m[i].write_3 = 0x00;
315 if (c->m[i].read_gap != 0)
316 T55xx_Timing.m[i].read_gap = c->m[i].read_gap;
319 printT55xxConfig();
321 #ifdef WITH_FLASH
322 // shall persist to flashmem
323 if (arg0 == 0) {
324 BigBuf_free();
325 return;
328 if (!FlashInit()) {
329 BigBuf_free();
330 return;
333 uint8_t *buf = BigBuf_malloc(T55XX_CONFIG_LEN);
334 Flash_CheckBusy(BUSY_TIMEOUT);
335 uint16_t res = Flash_ReadDataCont(T55XX_CONFIG_OFFSET, buf, T55XX_CONFIG_LEN);
336 if (res == 0) {
337 FlashStop();
338 BigBuf_free();
339 return;
342 memcpy(buf, &T55xx_Timing, T55XX_CONFIG_LEN);
344 // delete old configuration
345 Flash_CheckBusy(BUSY_TIMEOUT);
346 Flash_WriteEnable();
347 Flash_Erase4k(3, 0xD);
349 // write new
350 res = Flash_Write(T55XX_CONFIG_OFFSET, buf, T55XX_CONFIG_LEN);
352 if (res == T55XX_CONFIG_LEN && g_dbglevel > 1) {
353 DbpString("T55XX Config save " _GREEN_("success"));
356 BigBuf_free();
357 #endif
360 t55xx_configurations_t *getT55xxConfig(void) {
361 return &T55xx_Timing;//_FixedBit;
364 void loadT55xxConfig(void) {
365 #ifdef WITH_FLASH
367 if (!FlashInit()) {
368 return;
371 uint8_t *buf = BigBuf_malloc(T55XX_CONFIG_LEN);
373 Flash_CheckBusy(BUSY_TIMEOUT);
374 uint16_t isok = Flash_ReadDataCont(T55XX_CONFIG_OFFSET, buf, T55XX_CONFIG_LEN);
375 FlashStop();
377 // verify read mem is actual data.
378 uint8_t cntA = T55XX_CONFIG_LEN, cntB = T55XX_CONFIG_LEN;
379 for (int i = 0; i < T55XX_CONFIG_LEN; i++) {
380 if (buf[i] == 0xFF) cntA--;
381 if (buf[i] == 0x00) cntB--;
383 if (!cntA || !cntB) {
384 BigBuf_free();
385 return;
388 if (buf[0] != 0xFF) // if not set for clear
389 memcpy((uint8_t *)&T55xx_Timing, buf, T55XX_CONFIG_LEN);
391 if (isok == T55XX_CONFIG_LEN) {
392 if (g_dbglevel > 1) DbpString("T55XX Config load success");
395 BigBuf_free();
396 #endif
399 static bool prev_keep = false;
402 * Function to do a modulation and then get samples.
403 * @param delay_off
404 * @param period_0
405 * @param period_1
406 * @param command (in binary char array)
408 void ModThenAcquireRawAdcSamples125k(uint32_t delay_off, uint16_t period_0, uint16_t period_1,
409 const uint8_t *symbol_extra, uint16_t *period_extra, uint8_t *command,
410 bool verbose, bool keep_field_on, uint32_t samples, bool ledcontrol) {
412 if (!prev_keep) {
413 FpgaDownloadAndGo(FPGA_BITSTREAM_LF);
415 // use lf config settings
416 sample_config *sc = getSamplingConfig();
417 LFSetupFPGAForADC(sc->divisor, true);
418 // this causes the field to turn on for uncontrolled amount of time, so we'll turn it off
420 if (!prev_keep) {
422 // Make sure the tag is reset
423 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
426 // start timer
427 StartTicks();
429 if (!prev_keep) {
430 WaitMS(100);
433 // clear read buffer
434 BigBuf_Clear_keep_EM();
436 // if delay_off = 0 then just bitbang 1 = antenna on 0 = off for respective periods.
437 bool bitbang = (delay_off == 0);
438 // now modulate the reader field
440 // Some tags need to be interrogated very soon after activation else they enter their emulation mode
441 // Therefore it's up to the caller to add an initial symbol of adequate duration, except for bitbang mode.
442 if (bitbang) {
443 turn_read_lf_on(20000);
444 // HACK it appears the loop and if statements take up about 7us so adjust waits accordingly...
445 uint8_t hack_cnt = 7;
446 if (period_0 < hack_cnt || period_1 < hack_cnt) {
447 DbpString("[!] Warning periods cannot be less than 7us in bit bang mode");
448 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
449 if (ledcontrol) LED_D_OFF();
450 reply_ng(CMD_LF_MOD_THEN_ACQ_RAW_ADC, PM3_EINVARG, NULL, 0);
451 return;
454 // hack2 needed--- it appears to take about 8-16us to turn the antenna back on
455 // leading to ~ 1 to 2 125kHz samples extra in every off period
456 // so we should test for last 0 before next 1 and reduce period_0 by this extra amount...
457 // but is this time different for every antenna or other hw builds??? more testing needed
459 // prime cmd_len to save time comparing strings while modulating
460 int cmd_len = 0;
461 while (command[cmd_len] != '\0' && command[cmd_len] != ' ')
462 cmd_len++;
464 int counter = 0;
465 bool off = false;
466 for (counter = 0; counter < cmd_len; counter++) {
467 // if cmd = 0 then turn field off
468 if (command[counter] == '0') {
469 // if field already off leave alone (affects timing otherwise)
470 if (off == false) {
471 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
472 if (ledcontrol) LED_D_OFF();
473 off = true;
475 // note we appear to take about 7us to switch over (or run the if statements/loop...)
476 WaitUS(period_0 - hack_cnt);
477 // else if cmd = 1 then turn field on
478 } else {
479 // if field already on leave alone (affects timing otherwise)
480 if (off) {
481 FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_READER | FPGA_LF_ADC_READER_FIELD);
482 if (ledcontrol) LED_D_ON();
483 off = false;
485 // note we appear to take about 7us to switch over (or run the if statements/loop...)
486 WaitUS(period_1 - hack_cnt);
489 } else { // old mode of cmd read using delay as off period
490 while (*command != '\0' && *command != ' ') {
491 if (ledcontrol) LED_D_ON();
492 if (*command == '0') {
493 turn_read_lf_on(period_0);
494 } else if (*command == '1') {
495 turn_read_lf_on(period_1);
496 } else {
497 for (uint8_t i = 0; i < LF_CMDREAD_MAX_EXTRA_SYMBOLS; i++) {
498 if (*command == symbol_extra[i]) {
499 turn_read_lf_on(period_extra[i]);
500 break;
504 command++;
505 if (ledcontrol) LED_D_OFF();
506 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
507 WaitUS(delay_off);
510 FpgaSendCommand(FPGA_CMD_SET_DIVISOR, sc->divisor);
513 FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_READER | FPGA_LF_ADC_READER_FIELD);
515 // now do the read
516 DoAcquisition_config(verbose, samples, ledcontrol);
518 // Turn off antenna
519 if (!keep_field_on) {
520 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
522 prev_keep = keep_field_on;
523 // tell client we are done
524 reply_ng(CMD_LF_MOD_THEN_ACQ_RAW_ADC, PM3_SUCCESS, NULL, 0);
527 /* blank r/w tag data stream
528 ...0000000000000000 01111111
529 1010101010101010101010101010101010101010101010101010101010101010
530 0011010010100001
531 01111111
532 101010101010101[0]000...
534 [5555fe852c5555555555555555fe0000]
536 void ReadTItag(bool ledcontrol) {
537 StartTicks();
538 // some hardcoded initial params
539 // when we read a TI tag we sample the zerocross line at 2MHz
540 // TI tags modulate a 1 as 16 cycles of 123.2kHz
541 // TI tags modulate a 0 as 16 cycles of 134.2kHz
542 #define FSAMPLE 2000000
543 #define FREQLO 123200
544 #define FREQHI 134200
546 signed char *dest = (signed char *)BigBuf_get_addr();
547 uint16_t n = BigBuf_max_traceLen();
548 // 128 bit shift register [shift3:shift2:shift1:shift0]
549 uint32_t shift3 = 0, shift2 = 0, shift1 = 0, shift0 = 0;
551 int i, cycles = 0, samples = 0;
552 // how many sample points fit in 16 cycles of each frequency
553 uint32_t sampleslo = (FSAMPLE << 4) / FREQLO, sampleshi = (FSAMPLE << 4) / FREQHI;
554 // when to tell if we're close enough to one freq or another
555 uint32_t threshold = (sampleslo - sampleshi + 1) >> 1;
557 // TI tags charge at 134.2kHz
558 FpgaDownloadAndGo(FPGA_BITSTREAM_LF);
559 FpgaSendCommand(FPGA_CMD_SET_DIVISOR, LF_DIVISOR_134); //~134kHz
561 // Place FPGA in passthrough mode, in this mode the CROSS_LO line
562 // connects to SSP_DIN and the SSP_DOUT logic level controls
563 // whether we're modulating the antenna (high)
564 // or listening to the antenna (low)
565 FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_PASSTHRU);
567 // get TI tag data into the buffer
568 AcquireTiType(ledcontrol);
570 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
572 for (i = 0; i < n - 1; i++) {
573 // count cycles by looking for lo to hi zero crossings
574 if ((dest[i] < 0) && (dest[i + 1] > 0)) {
575 cycles++;
576 // after 16 cycles, measure the frequency
577 if (cycles > 15) {
578 cycles = 0;
579 samples = i - samples; // number of samples in these 16 cycles
581 // TI bits are coming to us lsb first so shift them
582 // right through our 128 bit right shift register
583 shift0 = (shift0 >> 1) | (shift1 << 31);
584 shift1 = (shift1 >> 1) | (shift2 << 31);
585 shift2 = (shift2 >> 1) | (shift3 << 31);
586 shift3 >>= 1;
588 // check if the cycles fall close to the number
589 // expected for either the low or high frequency
590 if ((samples > (sampleslo - threshold)) && (samples < (sampleslo + threshold))) {
591 // low frequency represents a 1
592 shift3 |= (1u << 31);
593 } else if ((samples > (sampleshi - threshold)) && (samples < (sampleshi + threshold))) {
594 // high frequency represents a 0
595 } else {
596 // probably detected a gay waveform or noise
597 // use this as gaydar or discard shift register and start again
598 shift3 = shift2 = shift1 = shift0 = 0;
600 samples = i;
602 // for each bit we receive, test if we've detected a valid tag
604 // if we see 17 zeroes followed by 6 ones, we might have a tag
605 // remember the bits are backwards
606 if (((shift0 & 0x7fffff) == 0x7e0000)) {
607 // if start and end bytes match, we have a tag so break out of the loop
608 if (((shift0 >> 16) & 0xff) == ((shift3 >> 8) & 0xff)) {
609 cycles = 0xF0B; //use this as a flag (ugly but whatever)
610 break;
617 // if flag is set we have a tag
618 if (cycles != 0xF0B) {
619 DbpString("Info: No valid tag detected.");
620 } else {
621 // put 64 bit data into shift1 and shift0
622 shift0 = (shift0 >> 24) | (shift1 << 8);
623 shift1 = (shift1 >> 24) | (shift2 << 8);
625 // align 16 bit crc into lower half of shift2
626 shift2 = ((shift2 >> 24) | (shift3 << 8)) & 0x0ffff;
628 // if r/w tag, check ident match
629 if (shift3 & (1 << 15)) {
630 DbpString("Info: TI tag is rewriteable");
631 // only 15 bits compare, last bit of ident is not valid
632 if (((shift3 >> 16) ^ shift0) & 0x7fff) {
633 DbpString("Error: Ident mismatch!");
634 } else {
635 DbpString("Info: TI tag ident is valid");
637 } else {
638 DbpString("Info: TI tag is readonly");
641 // WARNING the order of the bytes in which we calc crc below needs checking
642 // i'm 99% sure the crc algorithm is correct, but it may need to eat the
643 // bytes in reverse or something
644 // calculate CRC
645 uint32_t crc = 0;
647 crc = update_crc16(crc, (shift0) & 0xff);
648 crc = update_crc16(crc, (shift0 >> 8) & 0xff);
649 crc = update_crc16(crc, (shift0 >> 16) & 0xff);
650 crc = update_crc16(crc, (shift0 >> 24) & 0xff);
651 crc = update_crc16(crc, (shift1) & 0xff);
652 crc = update_crc16(crc, (shift1 >> 8) & 0xff);
653 crc = update_crc16(crc, (shift1 >> 16) & 0xff);
654 crc = update_crc16(crc, (shift1 >> 24) & 0xff);
656 Dbprintf("Info: Tag data: %x%08x, crc=%x", (unsigned int)shift1, (unsigned int)shift0, (unsigned int)shift2 & 0xFFFF);
657 if (crc != (shift2 & 0xffff)) {
658 Dbprintf("Error: CRC mismatch, expected %x", (unsigned int)crc);
659 } else {
660 DbpString("Info: CRC is good");
663 StopTicks();
666 static void WriteTIbyte(uint8_t b) {
667 int i = 0;
669 // modulate 8 bits out to the antenna
670 for (i = 0; i < 8; i++) {
671 if (b & (1 << i)) {
672 // stop modulating antenna 1ms
673 LOW(GPIO_SSC_DOUT);
674 WaitUS(1000);
675 // modulate antenna 1ms
676 HIGH(GPIO_SSC_DOUT);
677 WaitUS(1000);
678 } else {
679 // stop modulating antenna 0.3ms
680 LOW(GPIO_SSC_DOUT);
681 WaitUS(300);
682 // modulate antenna 1.7ms
683 HIGH(GPIO_SSC_DOUT);
684 WaitUS(1700);
689 void AcquireTiType(bool ledcontrol) {
690 int i, j, n;
691 // tag transmission is <20ms, sampling at 2M gives us 40K samples max
692 // each sample is 1 bit stuffed into a uint32_t so we need 1250 uint32_t
693 #define TIBUFLEN 1250
695 // clear buffer
696 uint32_t *buf = (uint32_t *)BigBuf_get_addr();
698 //clear buffer now so it does not interfere with timing later
699 BigBuf_Clear_ext(false);
701 // Set up the synchronous serial port
702 AT91C_BASE_PIOA->PIO_PDR = GPIO_SSC_DIN;
703 AT91C_BASE_PIOA->PIO_ASR = GPIO_SSC_DIN;
705 // steal this pin from the SSP and use it to control the modulation
706 AT91C_BASE_PIOA->PIO_PER = GPIO_SSC_DOUT;
707 AT91C_BASE_PIOA->PIO_OER = GPIO_SSC_DOUT;
709 AT91C_BASE_SSC->SSC_CR = AT91C_SSC_SWRST;
710 AT91C_BASE_SSC->SSC_CR = AT91C_SSC_RXEN | AT91C_SSC_TXEN;
712 // Sample at 2 Mbit/s, so TI tags are 16.2 vs. 14.9 clocks long
713 // 48/2 = 24 MHz clock must be divided by 12
714 AT91C_BASE_SSC->SSC_CMR = 12;
716 AT91C_BASE_SSC->SSC_RCMR = SSC_CLOCK_MODE_SELECT(0);
717 AT91C_BASE_SSC->SSC_RFMR = SSC_FRAME_MODE_BITS_IN_WORD(32) | AT91C_SSC_MSBF;
718 // Transmit Clock Mode Register
719 AT91C_BASE_SSC->SSC_TCMR = 0;
720 // Transmit Frame Mode Register
721 AT91C_BASE_SSC->SSC_TFMR = 0;
722 // iceman, FpgaSetupSsc(FPGA_MAJOR_MODE_LF_READER) ?? the code above? can it be replaced?
723 if (ledcontrol) LED_D_ON();
725 // modulate antenna
726 HIGH(GPIO_SSC_DOUT);
728 // Charge TI tag for 50ms.
729 WaitMS(50);
731 // stop modulating antenna and listen
732 LOW(GPIO_SSC_DOUT);
734 if (ledcontrol) LED_D_OFF();
736 i = 0;
737 for (;;) {
738 if (AT91C_BASE_SSC->SSC_SR & AT91C_SSC_RXRDY) {
739 buf[i] = AT91C_BASE_SSC->SSC_RHR; // store 32 bit values in buffer
740 i++;
741 if (i >= TIBUFLEN) break;
743 WDT_HIT();
746 // return stolen pin to SSP
747 AT91C_BASE_PIOA->PIO_PDR = GPIO_SSC_DOUT;
748 AT91C_BASE_PIOA->PIO_ASR = GPIO_SSC_DIN | GPIO_SSC_DOUT;
750 char *dest = (char *)BigBuf_get_addr();
751 n = TIBUFLEN * 32;
753 // unpack buffer
754 for (i = TIBUFLEN - 1; i >= 0; i--) {
755 for (j = 0; j < 32; j++) {
756 if (buf[i] & (1u << j)) {
757 dest[--n] = 1;
758 } else {
759 dest[--n] = -1;
764 // reset SSC
765 FpgaSetupSsc(FPGA_MAJOR_MODE_LF_READER);
768 // arguments: 64bit data split into 32bit idhi:idlo and optional 16bit crc
769 // if crc provided, it will be written with the data verbatim (even if bogus)
770 // if not provided a valid crc will be computed from the data and written.
771 void WriteTItag(uint32_t idhi, uint32_t idlo, uint16_t crc, bool ledcontrol) {
772 FpgaDownloadAndGo(FPGA_BITSTREAM_LF);
773 if (crc == 0) {
774 crc = update_crc16(crc, (idlo) & 0xff);
775 crc = update_crc16(crc, (idlo >> 8) & 0xff);
776 crc = update_crc16(crc, (idlo >> 16) & 0xff);
777 crc = update_crc16(crc, (idlo >> 24) & 0xff);
778 crc = update_crc16(crc, (idhi) & 0xff);
779 crc = update_crc16(crc, (idhi >> 8) & 0xff);
780 crc = update_crc16(crc, (idhi >> 16) & 0xff);
781 crc = update_crc16(crc, (idhi >> 24) & 0xff);
783 Dbprintf("Writing to tag: %x%08x, crc=%x", idhi, idlo, crc);
785 // TI tags charge at 134.2kHz
786 FpgaSendCommand(FPGA_CMD_SET_DIVISOR, LF_DIVISOR_134); //~134kHz
787 // Place FPGA in passthrough mode, in this mode the CROSS_LO line
788 // connects to SSP_DIN and the SSP_DOUT logic level controls
789 // whether we're modulating the antenna (high)
790 // or listening to the antenna (low)
791 FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_PASSTHRU);
792 StartTicks();
794 if (ledcontrol) LED_A_ON();
796 // steal this pin from the SSP and use it to control the modulation
797 AT91C_BASE_PIOA->PIO_PER = GPIO_SSC_DOUT;
798 AT91C_BASE_PIOA->PIO_OER = GPIO_SSC_DOUT;
800 // writing algorithm:
801 // a high bit consists of a field off for 1ms and field on for 1ms
802 // a low bit consists of a field off for 0.3ms and field on for 1.7ms
803 // initiate a charge time of 50ms (field on) then immediately start writing bits
804 // start by writing 0xBB (keyword) and 0xEB (password)
805 // then write 80 bits of data (or 64 bit data + 16 bit crc if you prefer)
806 // finally end with 0x0300 (write frame)
807 // all data is sent lsb first
808 // finish with 50ms programming time
810 // modulate antenna
811 HIGH(GPIO_SSC_DOUT);
812 WaitMS(50); // charge time
814 WriteTIbyte(0xbb); // keyword
815 WriteTIbyte(0xeb); // password
816 WriteTIbyte((idlo) & 0xff);
817 WriteTIbyte((idlo >> 8) & 0xff);
818 WriteTIbyte((idlo >> 16) & 0xff);
819 WriteTIbyte((idlo >> 24) & 0xff);
820 WriteTIbyte((idhi) & 0xff);
821 WriteTIbyte((idhi >> 8) & 0xff);
822 WriteTIbyte((idhi >> 16) & 0xff);
823 WriteTIbyte((idhi >> 24) & 0xff); // data hi to lo
824 WriteTIbyte((crc) & 0xff); // crc lo
825 WriteTIbyte((crc >> 8) & 0xff); // crc hi
826 WriteTIbyte(0x00); // write frame lo
827 WriteTIbyte(0x03); // write frame hi
828 HIGH(GPIO_SSC_DOUT);
829 WaitMS(50); // programming time
831 if (ledcontrol) LED_A_OFF();
833 // get TI tag data into the buffer
834 AcquireTiType(ledcontrol);
836 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
837 DbpString("Now use `lf ti reader` to check");
838 StopTicks();
841 // note: a call to FpgaDownloadAndGo(FPGA_BITSTREAM_LF) must be done before, but
842 // this may destroy the bigbuf so be sure this is called before calling SimulateTagLowFrequencyEx
843 void SimulateTagLowFrequencyEx(int period, int gap, bool ledcontrol, int numcycles) {
845 // start us timer
846 StartTicks();
848 //FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_EDGE_DETECT | FPGA_LF_EDGE_DETECT_TOGGLE_MODE );
849 FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_EDGE_DETECT);
850 WaitMS(20);
852 int i = 0, x = 0;
853 uint8_t *buf = BigBuf_get_addr();
855 // set frequency, get values from 'lf config' command
856 sample_config *sc = getSamplingConfig();
858 if ((sc->divisor == 1) || (sc->divisor < 0) || (sc->divisor > 255))
859 FpgaSendCommand(FPGA_CMD_SET_DIVISOR, LF_DIVISOR_134); //~134kHz
860 else if (sc->divisor == 0)
861 FpgaSendCommand(FPGA_CMD_SET_DIVISOR, LF_DIVISOR_125); //125kHz
862 else
863 FpgaSendCommand(FPGA_CMD_SET_DIVISOR, sc->divisor);
865 AT91C_BASE_PIOA->PIO_PER = GPIO_SSC_DOUT | GPIO_SSC_CLK;
866 AT91C_BASE_PIOA->PIO_OER = GPIO_SSC_DOUT;
867 AT91C_BASE_PIOA->PIO_ODR = GPIO_SSC_CLK;
869 uint16_t check = 0;
871 for (;;) {
873 if (numcycles > -1) {
874 if (x != numcycles) {
875 ++x;
876 } else {
877 // exit without turning off field
878 return;
882 if (ledcontrol) LED_D_ON();
884 // wait until SSC_CLK goes HIGH
885 // used as a simple detection of a reader field?
886 while (!(AT91C_BASE_PIOA->PIO_PDSR & GPIO_SSC_CLK)) {
887 WDT_HIT();
888 if (check == 1000) {
889 if (data_available() || BUTTON_PRESS())
890 goto OUT;
891 check = 0;
893 ++check;
896 if (ledcontrol) LED_D_OFF();
898 if (buf[i])
899 OPEN_COIL();
900 else
901 SHORT_COIL();
903 check = 0;
905 //wait until SSC_CLK goes LOW
906 while (AT91C_BASE_PIOA->PIO_PDSR & GPIO_SSC_CLK) {
907 WDT_HIT();
908 if (check == 2000) {
909 if (BUTTON_PRESS() || data_available())
910 goto OUT;
911 check = 0;
913 ++check;
916 i++;
917 if (i == period) {
918 i = 0;
919 if (gap) {
920 SHORT_COIL();
921 WaitUS(gap);
925 OUT:
926 StopTicks();
927 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
928 if (ledcontrol) LED_D_OFF();
931 void SimulateTagLowFrequency(int period, int gap, bool ledcontrol) {
932 SimulateTagLowFrequencyEx(period, gap, ledcontrol, -1);
936 #define DEBUG_FRAME_CONTENTS 1
937 void SimulateTagLowFrequencyBidir(int divisor, int max_bitlen) {
940 // compose fc/X fc/Y waveform (FSKx)
941 static void fcAll(uint8_t fc, int *n, uint8_t clock, int16_t *remainder) {
942 uint8_t *dest = BigBuf_get_addr();
943 uint8_t halfFC = fc >> 1;
944 uint8_t wavesPerClock = (clock + *remainder) / fc;
945 // loop through clock - step field clock
946 for (uint8_t idx = 0; idx < wavesPerClock; idx++) {
947 // put 1/2 FC length 1's and 1/2 0's per field clock wave (to create the wave)
948 memset(dest + (*n), 0, fc - halfFC); //in case of odd number use extra here
949 memset(dest + (*n) + (fc - halfFC), 1, halfFC);
950 *n += fc;
952 *remainder = (clock + *remainder) % fc;
953 // if we've room for more than a half wave, add a full wave and use negative remainder
954 if (*remainder > halfFC) {
955 memset(dest + (*n), 0, fc - halfFC); //in case of odd number use extra here
956 memset(dest + (*n) + (fc - halfFC), 1, halfFC);
957 *n += fc;
958 *remainder -= fc;
962 // prepare a waveform pattern in the buffer based on the ID given then
963 // simulate a HID tag until the button is pressed
964 void CmdHIDsimTAGEx(uint32_t hi2, uint32_t hi, uint32_t lo, uint8_t longFMT, bool ledcontrol, int numcycles) {
967 HID tag bitstream format
968 The tag contains a 44bit unique code. This is sent out MSB first in sets of 4 bits
969 A 1 bit is represented as 6 fc8 and 5 fc10 patterns (manchester 10) during 2 clock periods. (1bit = 1clock period)
970 A 0 bit is represented as 5 fc10 and 6 fc8 patterns (manchester 01)
971 A fc8 is inserted before every 4 bits
972 A special start of frame pattern is used consisting a0b0 where a and b are neither 0
973 nor 1 bits, they are special patterns (a = set of 12 fc8 and b = set of 10 fc10)
975 FSK2a
976 bit 1 = fc10
977 bit 0 = fc8
980 // special start of frame marker containing invalid Manchester bit sequences
981 uint8_t bits[8 + 8 * 2 + 84 * 2] = { 0, 0, 0, 1, 1, 1, 0, 1 };
982 uint8_t bitlen = 0;
983 uint16_t n = 8;
985 if (longFMT) {
986 // Ensure no more than 84 bits supplied
987 if (hi2 > 0xFFFFF) {
988 DbpString("Tags can only have 84 bits.");
989 return;
991 bitlen = 8 + 8 * 2 + 84 * 2;
992 hi2 |= 0x9E00000; // 9E: long format identifier
993 manchesterEncodeUint32(hi2, 16 + 12, bits, &n);
994 manchesterEncodeUint32(hi, 32, bits, &n);
995 manchesterEncodeUint32(lo, 32, bits, &n);
996 } else {
998 if (hi > 0xFFF) {
999 DbpString("[!] tags can only have 44 bits. - USE lf simfsk for larger tags");
1000 return;
1002 bitlen = 8 + 44 * 2;
1003 manchesterEncodeUint32(hi, 12, bits, &n);
1004 manchesterEncodeUint32(lo, 32, bits, &n);
1006 CmdFSKsimTAGEx(10, 8, 0, 50, bitlen, bits, ledcontrol, numcycles);
1009 void CmdHIDsimTAG(uint32_t hi2, uint32_t hi, uint32_t lo, uint8_t longFMT, bool ledcontrol) {
1010 CmdHIDsimTAGEx(hi2, hi, lo, longFMT, ledcontrol, -1);
1011 reply_ng(CMD_LF_HID_SIMULATE, PM3_EOPABORTED, NULL, 0);
1014 // prepare a waveform pattern in the buffer based on the ID given then
1015 // simulate a FSK tag until the button is pressed
1016 // arg1 contains fcHigh and fcLow, arg2 contains STT marker and clock
1017 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) {
1019 FpgaDownloadAndGo(FPGA_BITSTREAM_LF);
1021 // free eventually allocated BigBuf memory
1022 BigBuf_free();
1023 BigBuf_Clear_ext(false);
1024 clear_trace();
1025 set_tracing(false);
1027 int n = 0, i = 0;
1028 int16_t remainder = 0;
1030 if (separator) {
1031 //int fsktype = ( fchigh == 8 && fclow == 5) ? 1 : 2;
1032 //fcSTT(&n);
1034 for (i = 0; i < bitslen; i++) {
1035 if (bits[i])
1036 fcAll(fchigh, &n, clk, &remainder);
1037 else
1038 fcAll(fclow, &n, clk, &remainder);
1041 WDT_HIT();
1043 Dbprintf("FSK simulating with rf/%d, fc high %d, fc low %d, STT %d, n %d", clk, fchigh, fclow, separator, n);
1045 if (ledcontrol) LED_A_ON();
1046 SimulateTagLowFrequencyEx(n, 0, ledcontrol, numcycles);
1047 if (ledcontrol) LED_A_OFF();
1050 // prepare a waveform pattern in the buffer based on the ID given then
1051 // simulate a FSK tag until the button is pressed
1052 // arg1 contains fcHigh and fcLow, arg2 contains STT marker and clock
1053 void CmdFSKsimTAG(uint8_t fchigh, uint8_t fclow, uint8_t separator, uint8_t clk, uint16_t bitslen, const uint8_t *bits, bool ledcontrol) {
1054 CmdFSKsimTAGEx(fchigh, fclow, separator, clk, bitslen, bits, ledcontrol, -1);
1055 reply_ng(CMD_LF_FSK_SIMULATE, PM3_EOPABORTED, NULL, 0);
1058 // compose ask waveform for one bit(ASK)
1059 static void askSimBit(uint8_t c, int *n, uint8_t clock, uint8_t manchester) {
1060 uint8_t *dest = BigBuf_get_addr();
1061 uint8_t halfClk = clock / 2;
1062 // c = current bit 1 or 0
1063 if (manchester == 1) {
1064 memset(dest + (*n), c, halfClk);
1065 memset(dest + (*n) + halfClk, c ^ 1, halfClk);
1066 } else {
1067 memset(dest + (*n), c, clock);
1069 *n += clock;
1072 static void biphaseSimBit(uint8_t c, int *n, uint8_t clock, uint8_t *phase) {
1073 uint8_t *dest = BigBuf_get_addr();
1074 uint8_t halfClk = clock / 2;
1075 if (c) {
1076 memset(dest + (*n), c ^ 1 ^ *phase, halfClk);
1077 memset(dest + (*n) + halfClk, c ^ *phase, halfClk);
1078 } else {
1079 memset(dest + (*n), c ^ *phase, clock);
1080 *phase ^= 1;
1082 *n += clock;
1085 static void stAskSimBit(int *n, uint8_t clock) {
1086 uint8_t *dest = BigBuf_get_addr();
1087 uint8_t halfClk = clock / 2;
1088 //ST = .5 high .5 low 1.5 high .5 low 1 high
1089 memset(dest + (*n), 1, halfClk);
1090 memset(dest + (*n) + halfClk, 0, halfClk);
1091 memset(dest + (*n) + clock, 1, clock + halfClk);
1092 memset(dest + (*n) + clock * 2 + halfClk, 0, halfClk);
1093 memset(dest + (*n) + clock * 3, 1, clock);
1094 *n += clock * 4;
1096 static void leadingZeroAskSimBits(int *n, uint8_t clock) {
1097 uint8_t *dest = BigBuf_get_addr();
1098 memset(dest + (*n), 0, clock * 8);
1099 *n += clock * 8;
1102 static void leadingZeroBiphaseSimBits(int *n, uint8_t clock, uint8_t *phase) {
1103 uint8_t *dest = BigBuf_get_addr();
1104 for (uint8_t i = 0; i < 8; i++) {
1105 memset(dest + (*n), 0 ^ *phase, clock);
1106 *phase ^= 1;
1107 *n += clock;
1113 // args clock, ask/man or askraw, invert, transmission separator
1114 void CmdASKsimTAG(uint8_t encoding, uint8_t invert, uint8_t separator, uint8_t clk,
1115 uint16_t size, const uint8_t *bits, bool ledcontrol) {
1116 FpgaDownloadAndGo(FPGA_BITSTREAM_LF);
1117 set_tracing(false);
1119 int n = 0, i = 0;
1121 if (encoding == 2) { //biphase
1122 uint8_t phase = 0;
1124 // iceman, if I add this, the demod includes these extra zero and detection fails.
1125 // now, I only need to figure out just to add carrier without modulation
1126 // the old bug, with adding ask zeros messed up the phase variable and deteion failed because of it in LF FDX
1127 // leadingZeroBiphaseSimBits(&n, clk, &phase);
1129 for (i = 0; i < size; i++) {
1130 biphaseSimBit(bits[i] ^ invert, &n, clk, &phase);
1132 if (phase == 1) { //run a second set inverted to keep phase in check
1133 for (i = 0; i < size; i++) {
1134 biphaseSimBit(bits[i] ^ invert, &n, clk, &phase);
1137 } else { // ask/manchester || ask/raw
1139 leadingZeroAskSimBits(&n, clk);
1141 for (i = 0; i < size; i++) {
1142 askSimBit(bits[i] ^ invert, &n, clk, encoding);
1144 if (encoding == 0 && bits[0] == bits[size - 1]) { //run a second set inverted (for ask/raw || biphase phase)
1145 for (i = 0; i < size; i++) {
1146 askSimBit(bits[i] ^ invert ^ 1, &n, clk, encoding);
1150 if (separator == 1 && encoding == 1)
1151 stAskSimBit(&n, clk);
1152 else if (separator == 1)
1153 Dbprintf("sorry but separator option not yet available");
1155 WDT_HIT();
1157 Dbprintf("ASK simulating with rf/%d, invert %d, encoding %s (%d), separator %d, n %d"
1158 , clk
1159 , invert
1160 , (encoding == 2) ? "ASK/BI" : (encoding == 1) ? "ASK/MAN" : "RAW/MAN"
1161 , encoding
1162 , separator
1166 if (ledcontrol) LED_A_ON();
1167 SimulateTagLowFrequency(n, 0, ledcontrol);
1168 if (ledcontrol) LED_A_OFF();
1169 reply_ng(CMD_LF_ASK_SIMULATE, PM3_EOPABORTED, NULL, 0);
1172 //carrier can be 2,4 or 8
1173 static void pskSimBit(uint8_t waveLen, int *n, uint8_t clk, uint8_t *curPhase, bool phaseChg) {
1174 uint8_t *dest = BigBuf_get_addr();
1175 uint8_t halfWave = waveLen / 2;
1176 //uint8_t idx;
1177 int i = 0;
1178 if (phaseChg) {
1179 // write phase change
1180 memset(dest + (*n), *curPhase ^ 1, halfWave);
1181 memset(dest + (*n) + halfWave, *curPhase, halfWave);
1182 *n += waveLen;
1183 *curPhase ^= 1;
1184 i += waveLen;
1186 //write each normal clock wave for the clock duration
1187 for (; i < clk; i += waveLen) {
1188 memset(dest + (*n), *curPhase, halfWave);
1189 memset(dest + (*n) + halfWave, *curPhase ^ 1, halfWave);
1190 *n += waveLen;
1194 // args clock, carrier, invert,
1195 void CmdPSKsimTAG(uint8_t carrier, uint8_t invert, uint8_t clk, uint16_t size,
1196 const uint8_t *bits, bool ledcontrol) {
1197 FpgaDownloadAndGo(FPGA_BITSTREAM_LF);
1198 set_tracing(false);
1200 int n = 0, i = 0;
1201 uint8_t curPhase = 0;
1202 for (i = 0; i < size; i++) {
1203 if (bits[i] == curPhase) {
1204 pskSimBit(carrier, &n, clk, &curPhase, false);
1205 } else {
1206 pskSimBit(carrier, &n, clk, &curPhase, true);
1210 WDT_HIT();
1212 Dbprintf("PSK simulating with rf/%d, fc/%d, invert %d, n %d", clk, carrier, invert, n);
1214 if (ledcontrol) LED_A_ON();
1215 SimulateTagLowFrequency(n, 0, ledcontrol);
1216 if (ledcontrol) LED_A_OFF();
1217 reply_ng(CMD_LF_PSK_SIMULATE, PM3_EOPABORTED, NULL, 0);
1220 // compose nrz waveform for one bit(NRZ)
1221 static void nrzSimBit(uint8_t c, int *n, uint8_t clock) {
1222 uint8_t *dest = BigBuf_get_addr();
1223 // uint8_t halfClk = clock / 2;
1224 // c = current bit 1 or 0
1225 memset(dest + (*n), c, clock);
1226 *n += clock;
1229 // args clock,
1230 void CmdNRZsimTAG(uint8_t invert, uint8_t separator, uint8_t clk, uint16_t size,
1231 const uint8_t *bits, bool ledcontrol) {
1233 FpgaDownloadAndGo(FPGA_BITSTREAM_LF);
1234 set_tracing(false);
1236 int n = 0, i = 0;
1238 // NRZ
1240 leadingZeroAskSimBits(&n, clk);
1242 for (i = 0; i < size; i++) {
1243 nrzSimBit(bits[i] ^ invert, &n, clk);
1246 if (bits[0] == bits[size - 1]) {
1247 for (i = 0; i < size; i++) {
1248 nrzSimBit(bits[i] ^ invert ^ 1, &n, clk);
1252 if (separator == 1)
1253 Dbprintf("sorry but separator option not yet available");
1255 WDT_HIT();
1257 Dbprintf("NRZ simulating with rf/%d, invert %d, separator %d, n %d"
1258 , clk
1259 , invert
1260 , separator
1264 if (ledcontrol) LED_A_ON();
1265 SimulateTagLowFrequency(n, 0, ledcontrol);
1266 if (ledcontrol) LED_A_OFF();
1267 reply_ng(CMD_LF_NRZ_SIMULATE, PM3_EOPABORTED, NULL, 0);
1270 // loop to get raw HID waveform then FSK demodulate the TAG ID from it
1271 int lf_hid_watch(int findone, uint32_t *high, uint32_t *low, bool ledcontrol) {
1273 size_t size;
1274 uint32_t hi2 = 0, hi = 0, lo = 0;
1275 int dummyIdx = 0;
1276 // Configure to go in 125kHz listen mode
1277 LFSetupFPGAForADC(LF_DIVISOR_125, true);
1279 uint8_t *dest = BigBuf_get_addr();
1280 BigBuf_Clear_keep_EM();
1281 clear_trace();
1282 set_tracing(false);
1284 //clear read buffer
1285 BigBuf_Clear_keep_EM();
1287 int res = PM3_SUCCESS;
1288 for (;;) {
1290 WDT_HIT();
1292 if (data_available() || BUTTON_PRESS()) {
1293 res = PM3_EOPABORTED;
1294 break;
1297 DoAcquisition_default(-1, false, ledcontrol);
1299 // FSK demodulator
1300 // 50 * 128 * 2 - big enough to catch 2 sequences of largest format
1301 size = MIN(12800, BigBuf_max_traceLen());
1303 int idx = HIDdemodFSK(dest, &size, &hi2, &hi, &lo, &dummyIdx);
1304 if (idx < 0) continue;
1306 if (idx > 0 && lo > 0 && (size == 96 || size == 192)) {
1307 // go over previously decoded manchester data and decode into usable tag ID
1308 if (hi2 != 0) { //extra large HID tags 88/192 bits
1309 Dbprintf("TAG ID: " _GREEN_("%x%08x%08x") " (%d)",
1310 hi2,
1313 (lo >> 1) & 0xFFFF
1315 } else { //standard HID tags 44/96 bits
1316 uint8_t bitlen = 0;
1317 uint32_t fac = 0;
1318 uint32_t cardnum = 0;
1320 if (((hi >> 5) & 1) == 1) { //if bit 38 is set then < 37 bit format is used
1321 uint32_t lo2 = 0;
1322 lo2 = (((hi & 31) << 12) | (lo >> 20)); //get bits 21-37 to check for format len bit
1323 uint8_t idx3 = 1;
1324 while (lo2 > 1) { //find last bit set to 1 (format len bit)
1325 lo2 >>= 1;
1326 idx3++;
1328 bitlen = idx3 + 19;
1329 fac = 0;
1330 cardnum = 0;
1331 if (bitlen == 26) {
1332 cardnum = (lo >> 1) & 0xFFFF;
1333 fac = (lo >> 17) & 0xFF;
1335 if (bitlen == 37) {
1336 cardnum = (lo >> 1) & 0x7FFFF;
1337 fac = ((hi & 0xF) << 12) | (lo >> 20);
1339 if (bitlen == 34) {
1340 cardnum = (lo >> 1) & 0xFFFF;
1341 fac = ((hi & 1) << 15) | (lo >> 17);
1343 if (bitlen == 35) {
1344 cardnum = (lo >> 1) & 0xFFFFF;
1345 fac = ((hi & 1) << 11) | (lo >> 21);
1347 } else { //if bit 38 is not set then 37 bit format is used
1348 bitlen = 37;
1349 cardnum = (lo >> 1) & 0x7FFFF;
1350 fac = ((hi & 0xF) << 12) | (lo >> 20);
1352 Dbprintf("TAG ID: " _GREEN_("%x%08x (%d)") " - Format Len: " _GREEN_("%d") " bit - FC: " _GREEN_("%d") " - Card: "_GREEN_("%d"),
1355 (lo >> 1) & 0xFFFF,
1356 bitlen,
1357 fac,
1358 cardnum
1361 if (findone) {
1362 *high = hi;
1363 *low = lo;
1364 break;
1366 // reset
1368 hi2 = hi = lo = idx = 0;
1370 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
1371 BigBuf_free();
1372 if (ledcontrol) LEDsoff();
1373 return res;
1376 // loop to get raw HID waveform then FSK demodulate the TAG ID from it
1377 int lf_awid_watch(int findone, uint32_t *high, uint32_t *low, bool ledcontrol) {
1379 size_t size;
1380 int dummyIdx = 0;
1382 uint8_t *dest = BigBuf_get_addr();
1383 BigBuf_Clear_keep_EM();
1384 clear_trace();
1385 set_tracing(false);
1387 LFSetupFPGAForADC(LF_DIVISOR_125, true);
1389 int res = PM3_SUCCESS;
1390 for (;;) {
1392 WDT_HIT();
1394 if (data_available() || BUTTON_PRESS()) {
1395 res = PM3_EOPABORTED;
1396 break;
1399 DoAcquisition_default(-1, false, ledcontrol);
1400 // FSK demodulator
1402 size = MIN(12800, BigBuf_max_traceLen());
1404 //askdemod and manchester decode
1405 int idx = detectAWID(dest, &size, &dummyIdx);
1407 if (idx <= 0 || size != 96) continue;
1408 // Index map
1409 // 0 10 20 30 40 50 60
1410 // | | | | | | |
1411 // 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
1412 // -----------------------------------------------------------------------------
1413 // 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
1414 // 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
1415 // |---26 bit---| |-----117----||-------------142-------------|
1416 // b = format bit len, o = odd parity of last 3 bits
1417 // f = facility code, c = card number
1418 // w = wiegand parity
1419 // (26 bit format shown)
1421 //get raw ID before removing parities
1422 uint32_t rawLo = bytebits_to_byte(dest + idx + 64, 32);
1423 uint32_t rawHi = bytebits_to_byte(dest + idx + 32, 32);
1424 uint32_t rawHi2 = bytebits_to_byte(dest + idx, 32);
1426 size = removeParity(dest, idx + 8, 4, 1, 88);
1427 if (size != 66) continue;
1428 // ok valid card found!
1430 // Index map
1431 // 0 10 20 30 40 50 60
1432 // | | | | | | |
1433 // 01234567 8 90123456 7890123456789012 3 456789012345678901234567890123456
1434 // -----------------------------------------------------------------------------
1435 // 00011010 1 01110101 0000000010001110 1 000000000000000000000000000000000
1436 // bbbbbbbb w ffffffff cccccccccccccccc w xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
1437 // |26 bit| |-117--| |-----142------|
1438 // b = format bit len, o = odd parity of last 3 bits
1439 // f = facility code, c = card number
1440 // w = wiegand parity
1441 // (26 bit format shown)
1443 uint8_t fmtLen = bytebits_to_byte(dest, 8);
1444 if (fmtLen == 26) {
1445 uint32_t fac = bytebits_to_byte(dest + 9, 8);
1446 uint32_t cardnum = bytebits_to_byte(dest + 17, 16);
1447 uint32_t code1 = bytebits_to_byte(dest + 8, fmtLen);
1448 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 } else {
1450 uint32_t cardnum = bytebits_to_byte(dest + 8 + (fmtLen - 17), 16);
1451 if (fmtLen > 32) {
1452 uint32_t code1 = bytebits_to_byte(dest + 8, fmtLen - 32);
1453 uint32_t code2 = bytebits_to_byte(dest + 8 + (fmtLen - 32), 32);
1454 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 } else {
1456 uint32_t code1 = bytebits_to_byte(dest + 8, fmtLen);
1457 Dbprintf("AWID Found - Bit length: " _GREEN_("%d") " -unknown bit length- (%d) - Wiegand: %x, Raw: %08x%08x%08x", fmtLen, cardnum, code1, rawHi2, rawHi, rawLo);
1460 if (findone) {
1461 *high = rawHi;
1462 *low = rawLo;
1463 break;
1467 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
1468 BigBuf_free();
1469 if (ledcontrol) LEDsoff();
1470 return res;
1473 int lf_em410x_watch(int findone, uint32_t *high, uint64_t *low, bool ledcontrol) {
1475 size_t size, idx = 0;
1476 int clk = 0, invert = 0, maxErr = 20;
1477 uint32_t hi = 0;
1478 uint64_t lo = 0;
1480 uint8_t *dest = BigBuf_get_addr();
1481 clear_trace();
1482 set_tracing(false);
1483 BigBuf_Clear_keep_EM();
1485 LFSetupFPGAForADC(LF_DIVISOR_125, true);
1487 int res = PM3_SUCCESS;
1488 for (;;) {
1489 WDT_HIT();
1491 if (data_available() || BUTTON_PRESS()) {
1492 res = PM3_EOPABORTED;
1493 break;
1496 DoAcquisition_default(-1, false, ledcontrol);
1498 size = MIN(16385, BigBuf_max_traceLen());
1500 //askdemod and manchester decode
1501 int errCnt = askdemod(dest, &size, &clk, &invert, maxErr, 0, 1);
1502 if (errCnt > 50) continue;
1504 WDT_HIT();
1506 int type = Em410xDecode(dest, &size, &idx, &hi, &lo);
1507 if (type > 0) {
1508 if (type & 0x1) {
1509 Dbprintf("EM TAG ID: " _GREEN_("%02x%08x") " - ( %05d_%03d_%08d )",
1510 (uint32_t)(lo >> 32),
1511 (uint32_t)lo,
1512 (uint32_t)(lo & 0xFFFF),
1513 (uint32_t)((lo >> 16LL) & 0xFF),
1514 (uint32_t)(lo & 0xFFFFFF));
1516 if (type & 0x2) {
1517 Dbprintf("EM XL TAG ID: " _GREEN_("%06x%08x%08x") " - ( %05d_%03d_%08d )",
1519 (uint32_t)(lo >> 32),
1520 (uint32_t)lo,
1521 (uint32_t)(lo & 0xFFFF),
1522 (uint32_t)((lo >> 16LL) & 0xFF),
1523 (uint32_t)(lo & 0xFFFFFF));
1525 if (type & 0x4) {
1526 uint64_t data = (lo << 20) >> 20;
1527 // Convert back to Short ID
1528 uint64_t id = ((uint64_t)hi << 16) | (lo >> 48);
1529 if ((data & 0xFFFFFFFF) == 0) {
1530 Dbprintf("EM TAG ID: " _GREEN_("%02x%08x") " - ( %05d_%03d_%08d ) Electra "_GREEN_("%i"),
1531 (uint32_t)(id >> 32),
1532 (uint32_t)id,
1533 (uint32_t)(id & 0xFFFF),
1534 (uint32_t)((id >> 16LL) & 0xFF),
1535 (uint32_t)(id & 0xFFFFFF),
1536 (uint32_t)(data >> 32));
1537 } else {
1538 Dbprintf("EM TAG ID: " _GREEN_("%02x%08x") " - ( %05d_%03d_%08d ) on 128b frame with data "_GREEN_("%03x%08x"),
1539 (uint32_t)(id >> 32),
1540 (uint32_t)id,
1541 (uint32_t)(id & 0xFFFF),
1542 (uint32_t)((id >> 16LL) & 0xFF),
1543 (uint32_t)(id & 0xFFFFFF),
1544 (uint32_t)(data >> 32),
1545 (uint32_t)data);
1548 if (findone) {
1549 *high = hi;
1550 *low = lo;
1551 break;
1554 hi = lo = size = idx = 0;
1555 clk = invert = 0;
1558 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
1559 BigBuf_free();
1560 if (ledcontrol) LEDsoff();
1561 return res;
1564 int lf_io_watch(int findone, uint32_t *high, uint32_t *low, bool ledcontrol) {
1566 int dummyIdx = 0;
1567 uint32_t code = 0, code2 = 0;
1568 uint8_t version = 0, facilitycode = 0;
1569 uint16_t number = 0;
1571 uint8_t *dest = BigBuf_get_addr();
1572 BigBuf_Clear_keep_EM();
1573 clear_trace();
1574 set_tracing(false);
1576 // Configure to go in 125kHz listen mode
1577 LFSetupFPGAForADC(LF_DIVISOR_125, true);
1579 int res = PM3_SUCCESS;
1580 for (;;) {
1582 WDT_HIT();
1584 if (data_available() || BUTTON_PRESS()) {
1585 res = PM3_EOPABORTED;
1586 break;
1589 DoAcquisition_default(-1, false, ledcontrol);
1591 size_t size = MIN(12000, BigBuf_max_traceLen());
1593 //fskdemod and get start index
1594 int idx = detectIOProx(dest, &size, &dummyIdx);
1595 if (idx < 0) continue;
1596 //valid tag found
1598 //Index map
1599 //0 10 20 30 40 50 60
1600 //| | | | | | |
1601 //01234567 8 90123456 7 89012345 6 78901234 5 67890123 4 56789012 3 45678901 23
1602 //-----------------------------------------------------------------------------
1603 //00000000 0 11110000 1 facility 1 version* 1 code*one 1 code*two 1 checksum 11
1605 //Checksum:
1606 //00000000 0 11110000 1 11100000 1 00000001 1 00000011 1 10110110 1 01110101 11
1607 //preamble F0 E0 01 03 B6 75
1608 // How to calc checksum,
1609 // http://www.proxmark.org/forum/viewtopic.php?id=364&p=6
1610 // F0 + E0 + 01 + 03 + B6 = 28A
1611 // 28A & FF = 8A
1612 // FF - 8A = 75
1613 // Checksum: 0x75
1614 //XSF(version)facility:codeone+codetwo
1615 //Handle the data
1616 // if(findone){ //only print binary if we are doing one
1617 // 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]);
1618 // 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]);
1619 // 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]);
1620 // 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]);
1621 // 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]);
1622 // 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]);
1623 // 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 // }
1625 code = bytebits_to_byte(dest + idx, 32);
1626 code2 = bytebits_to_byte(dest + idx + 32, 32);
1627 version = bytebits_to_byte(dest + idx + 27, 8); //14,4
1628 facilitycode = bytebits_to_byte(dest + idx + 18, 8);
1629 number = (bytebits_to_byte(dest + idx + 36, 8) << 8) | (bytebits_to_byte(dest + idx + 45, 8)); //36,9
1631 Dbprintf("IO Prox " _GREEN_("XSF(%02d)%02x:%05d") " (%08x%08x) (%s)", version, facilitycode, number, code, code2);
1633 if (findone) {
1634 *high = code;
1635 *low = code2;
1636 break;
1638 code = code2 = 0;
1639 version = facilitycode = 0;
1640 number = 0;
1642 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
1643 BigBuf_free();
1644 if (ledcontrol) LEDsoff();
1645 return res;
1648 /*------------------------------
1649 * T5555/T5557/T5567/T5577 routines
1650 *------------------------------
1651 * NOTE: T55x7/T5555 configuration register definitions moved to protocols.h
1653 * Relevant communication times in microsecond
1654 * To compensate antenna falling times shorten the write times
1655 * and enlarge the gap ones.
1656 * Q5 tags seems to have issues when these values changes.
1659 void turn_read_lf_on(uint32_t delay) {
1660 FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_READER | FPGA_LF_ADC_READER_FIELD);
1662 // measure antenna strength.
1663 //int adcval = ((MAX_ADC_LF_VOLTAGE * (SumAdc(ADC_CHAN_LF, 32) >> 1)) >> 14);
1664 WaitUS(delay);
1667 void turn_read_lf_off(uint32_t delay) {
1668 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
1669 WaitUS(delay);
1672 // Macro for code readability
1673 #define BITSTREAM_BYTE(x) ((x) >> 3) // iceman note: isn't this NIBBLE???
1674 #define BITSTREAM_BIT(x) ((x) & 7)
1676 #define T55_LLR_REF (136 * 8)
1678 // Write one bit to chip
1679 static void T55xxWriteBit(uint8_t bit, uint8_t downlink_idx) {
1681 switch (bit) {
1682 case 0 :
1683 // send bit 0/00
1684 turn_read_lf_on(T55xx_Timing.m[downlink_idx].write_0);
1685 break;
1686 case 1 :
1687 // send bit 1/01
1688 turn_read_lf_on(T55xx_Timing.m[downlink_idx].write_1);
1689 break;
1690 case 2 :
1691 // send bits 10 (1 of 4)
1692 turn_read_lf_on(T55xx_Timing.m[downlink_idx].write_2);
1693 break;
1694 case 3 :
1695 // send bits 11 (1 of 4)
1696 turn_read_lf_on(T55xx_Timing.m[downlink_idx].write_3);
1697 break;
1698 case 4 :
1699 // send Long Leading Reference
1700 turn_read_lf_on(T55xx_Timing.m[downlink_idx].write_0 + T55_LLR_REF);
1701 break;
1704 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
1705 WaitUS(T55xx_Timing.m[downlink_idx].write_gap);
1708 // Function to abstract an Arbitrary length byte array to store bit pattern.
1709 // bit_array - Array to hold data/bit pattern
1710 // start_offset - bit location to start storing new bits.
1711 // data - up to 32 bits of data to store
1712 // num_bits - how many bits (low x bits of data) Max 32 bits at a time
1713 // max_len - how many bytes can the bit_array hold (ensure no buffer overflow)
1714 // returns "Next" bit offset / bits stored (for next store)
1715 static uint8_t T55xx_SetBits(uint8_t *bs, uint8_t start_offset, uint32_t data, uint8_t num_bits, uint8_t max_len) {
1716 int8_t next_offset = start_offset;
1718 // Check if data will fit.
1719 if ((start_offset + num_bits) <= (max_len * 8)) {
1720 // Loop through the data and store
1721 for (int8_t offset = (num_bits - 1); offset >= 0; offset--) {
1723 if ((data >> offset) & 1)
1724 bs[BITSTREAM_BYTE(next_offset)] |= (1 << BITSTREAM_BIT(next_offset)); // Set 1
1725 else
1726 bs[BITSTREAM_BYTE(next_offset)] &= (0xff ^ (1 << BITSTREAM_BIT(next_offset))); // Set 0
1728 next_offset++;
1730 } else {
1731 // Note: This should never happen unless some code changes cause it.
1732 // So short message for coders when testing.
1733 Dbprintf(_RED_("T55 too many bits"));
1735 return next_offset;
1738 // Send one downlink command to the card
1739 static void T55xx_SendCMD(uint32_t data, uint32_t pwd, uint16_t arg) {
1742 arg bits
1743 xxxx xxxxxxx1 0x001 password mode (Y/N)
1744 xxxx xxxxxx1x 0x002 page (0|1)
1745 xxxx xxxxx1xx 0x004 test mode (Y/N)
1746 xxxx xxx11xxx 0x018 selected downlink mode (0|1|2|3|)
1747 xxxx xx1xxxxx 0x020 !reg_readmode (ICEMAN ?? Why use negative in the bool ??)
1748 xxxx x1xxxxxx 0x040 called for a read, so no data packet (Y/N)
1749 xxxx 1xxxxxxx 0x080 reset (Y/N)
1750 xxx1 xxxxxxxx 0x100 brute force (Y/N)
1751 111x xxxxxxxx 0xE00 block to write (0-7)
1753 bool t55_send_pwdmode = (arg & 0x1);
1754 bool t55_send_page = ((arg >> 1) & 0x1);
1755 bool t55_send_testmode = ((arg >> 2) & 0x1);
1756 bool t55_send_regreadmode = ((arg >> 5) & 0x1);
1757 bool t55_send_readcmd = ((arg >> 6) & 0x1);
1758 bool t55_send_reset = ((arg >> 7) & 0x1);
1759 bool t55_brute_mem = ((arg >> 8) & 0x1);
1761 uint8_t downlink_mode = (arg >> 3) & 0x03;
1762 uint8_t block_no = (arg >> 9) & 0x07;
1764 // no startup delay when in bruteforce command
1765 uint8_t start_wait = (t55_brute_mem) ? 0 : 4;
1767 // Max Downlink Command size ~74 bits, so 10 bytes (80 bits)
1768 uint8_t bs[10];
1769 memset(bs, 0x00, sizeof(bs));
1771 uint8_t len = 0;
1773 // build bit stream to send.
1775 // add Leading 0
1776 if (downlink_mode == T55XX_DLMODE_LEADING_ZERO)
1777 len = T55xx_SetBits(bs, len, 0, 1, sizeof(bs));
1779 // add 1 of 4 reference bit
1780 if (downlink_mode == T55XX_DLMODE_1OF4) {
1781 len = T55xx_SetBits(bs, len, 0, 1, sizeof(bs));
1782 // add extra zero
1783 len = T55xx_SetBits(bs, len, 0, 1, sizeof(bs));
1786 // add Opcode
1787 if (t55_send_reset) {
1788 // reset : r*) 00
1789 len = T55xx_SetBits(bs, len, 0, 2, sizeof(bs));
1790 } else {
1792 if (t55_send_testmode)
1793 Dbprintf(_YELLOW_("Using Test Mode"));
1795 len = T55xx_SetBits(bs, len, t55_send_testmode ? 0 : 1, 1, sizeof(bs));
1797 len = T55xx_SetBits(bs, len, t55_send_testmode ? 1 : t55_send_page, 1, sizeof(bs));
1799 if (t55_send_pwdmode) {
1800 // Leading 0 and 1 of 4 00 fixed bits if passsword used
1801 if ((downlink_mode == T55XX_DLMODE_LEADING_ZERO) || (downlink_mode == T55XX_DLMODE_1OF4)) {
1802 len = T55xx_SetBits(bs, len, 0, 2, sizeof(bs));
1804 len = T55xx_SetBits(bs, len, pwd, 32, sizeof(bs));
1807 // Add Lock bit 0
1808 if (t55_send_regreadmode == false)
1809 len = T55xx_SetBits(bs, len, 0, 1, sizeof(bs));
1811 // Add Data if a write command
1812 if (t55_send_readcmd == false)
1813 len = T55xx_SetBits(bs, len, data, 32, sizeof(bs));
1815 // Add Address
1816 if (t55_send_regreadmode == false)
1817 len = T55xx_SetBits(bs, len, block_no, 3, sizeof(bs));
1820 // Send Bits to T55xx
1821 // Set up FPGA, 125kHz
1822 LFSetupFPGAForADC(LF_DIVISOR_125, true);
1824 // make sure tag is fully powered up...
1825 WaitMS(start_wait);
1827 // Trigger T55x7 in mode.
1828 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
1829 WaitUS(T55xx_Timing.m[downlink_mode].start_gap);
1831 // If long leading 0 send long reference pulse
1832 if (downlink_mode == T55XX_DLMODE_LLR)
1833 T55xxWriteBit(T55XX_LONGLEADINGREFERENCE, downlink_mode);//Timing); // Send Long Leading Start Reference
1835 uint8_t sendbits;
1836 if ((downlink_mode == T55XX_DLMODE_1OF4) && (len > 0)) { // 1 of 4 need to send 2 bits at a time
1837 for (uint8_t i = 0; i < len - 1; i += 2) {
1838 sendbits = (bs[BITSTREAM_BYTE(i)] >> (BITSTREAM_BIT(i)) & 1) << 1; // Bit i
1839 sendbits += (bs[BITSTREAM_BYTE(i + 1)] >> (BITSTREAM_BIT(i + 1)) & 1); // Bit i+1;
1840 T55xxWriteBit(sendbits & 3, downlink_mode);
1842 } else {
1843 for (uint8_t i = 0; i < len; i++) {
1844 sendbits = (bs[BITSTREAM_BYTE(i)] >> BITSTREAM_BIT(i));
1845 T55xxWriteBit(sendbits & 1, downlink_mode);
1850 // Send T5577 reset command then read stream (see if we can identify the start of the stream)
1851 void T55xxResetRead(uint8_t flags, bool ledcontrol) {
1853 uint8_t downlink_mode = ((flags >> 3) & 3);
1854 uint8_t arg = 0x80 | downlink_mode;
1856 if (ledcontrol) LED_A_ON();
1858 //clear buffer now so it does not interfere with timing later
1859 BigBuf_Clear_keep_EM();
1861 T55xx_SendCMD(0, 0, arg);
1863 turn_read_lf_on(T55xx_Timing.m[downlink_mode].read_gap);
1865 // Acquisition
1866 DoPartialAcquisition(0, false, BigBuf_max_traceLen(), 0, ledcontrol);
1868 // Turn the field off
1869 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
1870 reply_ng(CMD_LF_T55XX_RESET_READ, PM3_SUCCESS, NULL, 0);
1871 if (ledcontrol) LED_A_OFF();
1874 void T55xxDangerousRawTest(const uint8_t *data, bool ledcontrol) {
1875 // supports only default downlink mode
1876 const t55xx_test_block_t *c = (const t55xx_test_block_t *)data;
1878 uint8_t start_wait = 4;
1879 uint8_t bs[128 / 8];
1880 memset(bs, 0x00, sizeof(bs));
1881 uint8_t len = 0;
1882 if (c->bitlen == 0 || c->bitlen > 128 || c->time == 0)
1883 reply_ng(CMD_LF_T55XX_DANGERRAW, PM3_EINVARG, NULL, 0);
1884 for (uint8_t i = 0; i < c->bitlen; i++)
1885 len = T55xx_SetBits(bs, len, c->data[i], 1, sizeof(bs));
1887 if (g_dbglevel > 1) {
1888 Dbprintf("LEN %i, TIMING %i", len, c->time);
1889 for (uint8_t i = 0; i < len; i++) {
1890 uint8_t sendbits = (bs[BITSTREAM_BYTE(i)] >> BITSTREAM_BIT(i));
1891 Dbprintf("%02i: %i", i, sendbits & 1);
1895 if (ledcontrol) LED_A_ON();
1896 LFSetupFPGAForADC(LF_DIVISOR_125, true);
1897 // make sure tag is fully powered up...
1898 WaitMS(start_wait);
1899 // Trigger T55x7 in mode.
1900 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
1901 WaitUS(T55xx_Timing.m[0].start_gap);
1902 for (uint8_t i = 0; i < len; i++) {
1903 uint8_t sendbits = (bs[BITSTREAM_BYTE(i)] >> BITSTREAM_BIT(i));
1904 T55xxWriteBit(sendbits & 1, 0);
1906 turn_read_lf_on(c->time);
1907 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
1908 reply_ng(CMD_LF_T55XX_DANGERRAW, PM3_SUCCESS, NULL, 0);
1909 if (ledcontrol) LED_A_OFF();
1912 // Write one card block in page 0, no lock
1913 //void T55xxWriteBlockExt(uint32_t data, uint8_t blockno, uint32_t pwd, uint8_t flags) {
1914 void T55xxWriteBlock(uint8_t *data, bool ledcontrol) {
1917 flag bits
1918 xxxxxxx1 0x01 PwdMode
1919 xxxxxx1x 0x02 Page
1920 xxxxx1xx 0x04 testMode
1921 xxx11xxx 0x18 downlink mode
1922 xx1xxxxx 0x20 !reg_readmode
1923 x1xxxxxx 0x40 called for a read, so no data packet
1924 1xxxxxxx 0x80 reset
1927 t55xx_write_block_t *c = (t55xx_write_block_t *)data;
1928 // c->data, c->blockno, c->pwd, c->flags
1930 bool testMode = ((c->flags & 0x04) == 0x04);
1932 c->flags &= (0xff ^ 0x40); // Called for a write, so ensure it is clear/0
1934 if (ledcontrol) LED_A_ON();
1935 T55xx_SendCMD(c->data, c->pwd, c->flags | (c->blockno << 9));
1937 // Perform write (nominal is 5.6 ms for T55x7 and 18ms for E5550,
1938 // so wait a little more)
1940 // "there is a clock delay before programming"
1941 // - programming takes ~5.6ms for t5577 ~18ms for E5550 or t5567
1942 // so we should wait 1 clock + 5.6ms then read response?
1943 // but we need to know we are dealing with t5577 vs t5567 vs e5550 (or q5) marshmellow...
1944 if (testMode) {
1945 //TESTMODE TIMING TESTS:
1946 // <566us does nothing
1947 // 566-568 switches between wiping to 0s and doing nothing
1948 // 5184 wipes and allows 1 block to be programmed.
1949 // indefinite power on wipes and then programs all blocks with bitshifted data sent.
1950 turn_read_lf_on(5184);
1952 } else {
1953 turn_read_lf_on(20 * 1000);
1954 //could attempt to do a read to confirm write took
1955 // as the tag should repeat back the new block
1956 // until it is reset, but to confirm it we would
1957 // need to know the current block 0 config mode for
1958 // modulation clock another details to demod the response...
1959 // response should be (for t55x7) a 0 bit then (ST if on)
1960 // block data written in on repeat until reset.
1962 //DoPartialAcquisition(20, false, 12000, ledcontrol);
1964 // turn field off
1965 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
1967 reply_ng(CMD_LF_T55XX_WRITEBL, PM3_SUCCESS, NULL, 0);
1968 if (ledcontrol) LED_A_OFF();
1972 // uses NG format
1973 void T55xxWriteBlock(uint8_t *data) {
1974 t55xx_write_block_t *c = (t55xx_write_block_t *)data;
1975 T55xxWriteBlockExt(c->data, c->blockno, c->pwd, c->flags);
1976 // reply_ng(CMD_LF_T55XX_WRITEBL, PM3_SUCCESS, NULL, 0);
1980 // Read one card block in page [page]
1981 void T55xxReadBlockExt(uint16_t flags, uint8_t block, uint32_t pwd, bool ledcontrol) {
1983 flag bits
1984 xxxx xxxxxxx1 0x0001 PwdMode
1985 xxxx xxxxxx1x 0x0002 Page
1986 xxxx xxxxx1xx 0x0004 testMode
1987 xxxx xxx11xxx 0x0018 downlink mode
1988 xxxx xx1xxxxx 0x0020 !reg_readmode
1989 xxxx x1xxxxxx 0x0040 called for a read, so no data packet
1990 xxxx 1xxxxxxx 0x0080 reset
1991 xxx1 xxxxxxxx 0x0100 brute / leave field on
1993 size_t samples = 12000;
1994 bool brute_mem = (flags & 0x0100) >> 8;
1996 if (ledcontrol) LED_A_ON();
1998 if (brute_mem) samples = 1024;
2000 // Set Read Flag to ensure SendCMD does not add "data" to the packet
2001 flags |= 0x40;
2003 // RegRead Mode true block = 0xff, so read without an address
2004 if (block == 0xff) flags |= 0x20;
2006 //make sure block is at max 7
2007 block &= 0x7;
2009 //clear buffer now so it does not interfere with timing later
2010 BigBuf_Clear_keep_EM();
2012 T55xx_SendCMD(0, pwd, flags | (block << 9)); //, true);
2014 // Turn field on to read the response
2015 // 137*8 seems to get to the start of data pretty well...
2016 // but we want to go past the start and let the repeating data settle in...
2018 // turn_read_lf_on(210*8); // issues with block 1 reads so dropping down seemed to help
2019 turn_read_lf_on(137 * 8);
2021 // Acquisition
2022 // Now do the acquisition
2023 DoPartialAcquisition(0, false, samples, 0, ledcontrol);
2025 // Turn the field off
2026 if (!brute_mem) {
2027 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
2028 reply_ng(CMD_LF_T55XX_READBL, PM3_SUCCESS, NULL, 0);
2029 if (ledcontrol) LED_A_OFF();
2033 // Read one card block in page [page]
2034 void T55xxReadBlock(uint8_t page, bool pwd_mode, bool brute_mem, uint8_t block, uint32_t pwd, uint8_t downlink_mode, bool ledcontrol) {
2036 flag bits
2037 xxxx xxxxxxx1 0x0001 PwdMode
2038 xxxx xxxxxx1x 0x0002 Page
2039 xxxx xxxxx1xx 0x0004 testMode
2040 xxxx xxx11xxx 0x0018 downlink mode
2041 xxxx xx1xxxxx 0x0020 !reg_readmode
2042 xxxx x1xxxxxx 0x0040 called for a read, so no data packet
2043 xxxx 1xxxxxxx 0x0080 reset
2044 xxx1 xxxxxxxx 0x0100 brute / leave field on
2046 uint16_t flags = 0x0040; // read packet
2047 if (pwd_mode) flags |= 0x0001;
2048 if (page) flags |= 0x0002;
2049 flags |= (downlink_mode & 3) << 3;
2050 if (brute_mem) flags |= 0x0100;
2052 sample_config old_config;
2053 sample_config *curr_config = getSamplingConfig();
2054 memcpy(&old_config, curr_config, sizeof(sample_config));
2055 old_config.verbose = false;
2057 setDefaultSamplingConfig();
2059 size_t samples = 12000;
2061 if (ledcontrol) LED_A_ON();
2063 if (brute_mem) samples = 2048;
2065 //-- Set Read Flag to ensure SendCMD does not add "data" to the packet
2066 //-- flags |= 0x40;
2068 // RegRead Mode true block = 0xff, so read without an address
2069 if (block == 0xff) flags |= 0x20;
2071 //make sure block is at max 7
2072 block &= 0x7;
2074 //clear buffer now so it does not interfere with timing later
2075 BigBuf_Clear_keep_EM();
2077 T55xx_SendCMD(0, pwd, flags | (block << 9)); //, true);
2079 // Turn field on to read the response
2080 // 137*8 seems to get to the start of data pretty well...
2081 // but we want to go past the start and let the repeating data settle in...
2083 // turn_read_lf_on(210*8); // issues with block 1 reads so dropping down seemed to help
2084 turn_read_lf_on(137 * 8);
2086 // Acquisition
2087 // Now do the acquisition
2088 DoPartialAcquisition(0, false, samples, 1000, ledcontrol);
2090 // Turn the field off
2091 if (brute_mem == false) {
2092 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
2093 reply_ng(CMD_LF_T55XX_READBL, PM3_SUCCESS, NULL, 0);
2094 if (ledcontrol) LED_A_OFF();
2097 // reset back to old / save config
2098 setSamplingConfig(&old_config);
2102 void T55xx_ChkPwds(uint8_t flags, bool ledcontrol) {
2104 #define CHK_SAMPLES_SIGNAL 2048
2106 #ifdef WITH_FLASH
2107 DbpString(_CYAN_("T55XX Check pwds using flashmemory starting"));
2108 #else
2109 DbpString(_CYAN_("T55XX Check pwds starting"));
2110 #endif
2112 // First get baseline and setup LF mode.
2113 uint8_t *buf = BigBuf_get_addr();
2114 uint8_t downlink_mode = (flags >> 3) & 0x03;
2115 uint64_t b1, baseline_faulty = 0;
2117 DbpString("Determine baseline...");
2119 // collect baseline for failed attempt ( should give me block1 )
2120 uint8_t x = 32;
2121 while (x--) {
2122 b1 = 0;
2123 T55xxReadBlock(0, 0, true, 0, 0, downlink_mode, ledcontrol);
2124 for (uint16_t j = 0; j < CHK_SAMPLES_SIGNAL; ++j) {
2125 b1 += (buf[j] * buf[j]);
2127 b1 *= b1;
2128 b1 >>= 8;
2129 baseline_faulty += b1;
2131 baseline_faulty >>= 5;
2133 if (g_dbglevel >= DBG_DEBUG)
2134 Dbprintf("Baseline " _YELLOW_("%llu"), baseline_faulty);
2136 uint8_t *pwds = BigBuf_get_EM_addr();
2137 uint16_t pwd_count = 0;
2139 struct p {
2140 bool found;
2141 uint32_t candidate;
2142 } PACKED payload;
2144 payload.found = false;
2145 payload.candidate = 0;
2147 #ifdef WITH_FLASH
2149 BigBuf_Clear_EM();
2150 uint16_t isok = 0;
2151 uint8_t counter[2] = {0x00, 0x00};
2152 isok = Flash_ReadData(DEFAULT_T55XX_KEYS_OFFSET, counter, sizeof(counter));
2153 if (isok != sizeof(counter))
2154 goto OUT;
2156 pwd_count = (uint16_t)(counter[1] << 8 | counter[0]);
2157 if (pwd_count == 0)
2158 goto OUT;
2160 // since flash can report way too many pwds, we need to limit it.
2161 // bigbuff EM size is determined by CARD_MEMORY_SIZE
2162 // a password is 4bytes.
2163 uint16_t pwd_size_available = MIN(CARD_MEMORY_SIZE, pwd_count * 4);
2165 // adjust available pwd_count
2166 pwd_count = pwd_size_available / 4;
2168 isok = Flash_ReadData(DEFAULT_T55XX_KEYS_OFFSET + 2, pwds, pwd_size_available);
2169 if (isok != pwd_size_available)
2170 goto OUT;
2172 Dbprintf("Password dictionary count " _YELLOW_("%d"), pwd_count);
2174 #endif
2176 uint64_t curr, prev = 0;
2177 int32_t idx = -1;
2179 for (uint32_t i = 0; i < pwd_count; i++) {
2181 uint32_t pwd = bytes_to_num(pwds + (i * 4), 4);
2183 T55xxReadBlock(0, true, true, 0, pwd, downlink_mode, ledcontrol);
2185 uint64_t sum = 0;
2186 for (uint16_t j = 0; j < CHK_SAMPLES_SIGNAL; ++j) {
2187 sum += (buf[j] * buf[j]);
2189 sum *= sum;
2190 sum >>= 8;
2192 int64_t tmp_dist = (baseline_faulty - sum);
2193 curr = ABS(tmp_dist);
2195 if (g_dbglevel >= DBG_DEBUG)
2196 Dbprintf("%08x has distance " _YELLOW_("%llu"), pwd, curr);
2198 if (curr > prev) {
2199 idx = i;
2200 prev = curr;
2204 if (idx != -1) {
2205 payload.found = true;
2206 payload.candidate = bytes_to_num(pwds + (idx * 4), 4);
2209 #ifdef WITH_FLASH
2210 OUT:
2211 #endif
2213 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
2214 if (ledcontrol) LEDsoff();
2215 reply_ng(CMD_LF_T55XX_CHK_PWDS, PM3_SUCCESS, (uint8_t *)&payload, sizeof(payload));
2216 BigBuf_free();
2219 void T55xxWakeUp(uint32_t pwd, uint8_t flags, bool ledcontrol) {
2221 flags |= 0x01 | 0x40 | 0x20; //Password | Read Call (no data) | reg_read no block
2222 if (ledcontrol) LED_B_ON();
2224 T55xx_SendCMD(0, pwd, flags);
2226 //-- Turn and leave field on to let the begin repeating transmission
2227 turn_read_lf_on(20 * 1000);
2228 reply_ng(CMD_LF_T55XX_WAKEUP, PM3_SUCCESS, NULL, 0);
2231 /*-------------- Cloning routines -----------*/
2232 static void WriteT55xx(const uint32_t *blockdata, uint8_t startblock, uint8_t numblocks, bool ledcontrol) {
2234 // Sanity checks
2235 if (blockdata == NULL || numblocks == 0) {
2236 reply_ng(CMD_LF_T55XX_WRITEBL, PM3_EINVARG, NULL, 0);
2237 return;
2240 t55xx_write_block_t cmd = {
2241 .pwd = 0,
2242 .flags = 0
2245 // write in reverse order since we don't want to set
2246 // a password enabled configuration first....
2247 while (numblocks--) {
2249 // zero based index
2250 cmd.data = blockdata[numblocks];
2251 cmd.blockno = startblock + numblocks;
2253 // since this fct sends a NG packet every time, this loop will send I number of NG
2254 T55xxWriteBlock((uint8_t *)&cmd, ledcontrol);
2258 static void WriteEM4x05(uint32_t *blockdata, uint8_t startblock, uint8_t numblocks, bool ledcontrol) {
2259 if (g_dbglevel == DBG_DEBUG) {
2260 Dbprintf("# | data ( EM4x05 )");
2261 Dbprintf("--+----------------");
2264 for (uint8_t i = startblock; i < (uint8_t)(startblock + numblocks); i++) {
2265 if (i > 4) {
2266 blockdata[i - startblock] = reflect(blockdata[i - startblock], 32);
2268 if (g_dbglevel == DBG_DEBUG) {
2269 Dbprintf("%i | %08x", i, blockdata[i - startblock]);
2273 if (g_dbglevel == DBG_DEBUG) {
2274 Dbprintf("--+----------------");
2277 for (uint8_t i = numblocks + startblock; i > startblock; i--) {
2278 EM4xWriteWord(i - 1, blockdata[i - 1 - startblock], 0, 0, ledcontrol);
2282 // Copy HID id to card and setup block 0 config
2283 void CopyHIDtoT55x7(uint32_t hi2, uint32_t hi, uint32_t lo, uint8_t longFMT, bool q5, bool em, bool ledcontrol) {
2284 uint32_t data[] = {0, 0, 0, 0, 0, 0, 0};
2285 uint8_t last_block = 0;
2287 if (longFMT) {
2288 // Ensure no more than 84 bits supplied
2289 if (hi2 > 0xFFFFF) {
2290 DbpString("Tags can only have 84 bits");
2291 return;
2293 // Build the 6 data blocks for supplied 84bit ID
2294 last_block = 6;
2295 // load preamble (1D) & long format identifier (9E manchester encoded)
2296 data[1] = 0x1D96A900 | (manchesterEncode2Bytes((hi2 >> 16) & 0xF) & 0xFF);
2297 // load raw id from hi2, hi, lo to data blocks (manchester encoded)
2298 data[2] = manchesterEncode2Bytes(hi2 & 0xFFFF);
2299 data[3] = manchesterEncode2Bytes(hi >> 16);
2300 data[4] = manchesterEncode2Bytes(hi & 0xFFFF);
2301 data[5] = manchesterEncode2Bytes(lo >> 16);
2302 data[6] = manchesterEncode2Bytes(lo & 0xFFFF);
2303 } else {
2304 // Ensure no more than 44 bits supplied
2305 if (hi > 0xFFF) {
2306 DbpString("Tags can only have 44 bits, if you want more use long format");
2307 return;
2309 // Build the 3 data blocks for supplied 44bit
2310 last_block = 3;
2311 // load preamble
2312 // 24 bits left. ie 12 bits of data, not 16..
2313 data[1] = 0x1D000000 | (manchesterEncode2Bytes(hi & 0xFFF) & 0xFFFFFF);
2314 data[2] = manchesterEncode2Bytes(lo >> 16);
2315 data[3] = manchesterEncode2Bytes(lo & 0xFFFF);
2317 // load chip config block
2318 data[0] = T55x7_BITRATE_RF_50 | T55x7_MODULATION_FSK2a | last_block << T55x7_MAXBLOCK_SHIFT;
2320 //TODO add selection of chip for Q5 or T55x7
2321 if (q5) {
2322 data[0] = T5555_SET_BITRATE(50) | T5555_MODULATION_FSK2 | T5555_INVERT_OUTPUT | last_block << T5555_MAXBLOCK_SHIFT;
2323 } else if (em) {
2324 data[0] = (EM4x05_SET_BITRATE(50) | EM4x05_MODULATION_FSK2 | EM4x05_SET_NUM_BLOCKS(last_block));
2325 // EM4x05_INVERT not available on EM4305, so let's invert manually
2326 for (uint8_t i = 1; i <= last_block ; i++) {
2327 data[i] = data[i] ^ 0xFFFFFFFF;
2331 if (ledcontrol) LED_D_ON();
2332 if (em) {
2333 WriteEM4x05(data, 4, last_block + 1, ledcontrol);
2334 } else {
2335 WriteT55xx(data, 0, last_block + 1, ledcontrol);
2337 if (ledcontrol) LED_D_OFF();
2338 reply_ng(CMD_LF_HID_CLONE, PM3_SUCCESS, NULL, 0);
2341 // clone viking tag to T55xx
2342 void CopyVikingtoT55xx(const uint8_t *blocks, bool q5, bool em, bool ledcontrol) {
2344 uint32_t data[] = {T55x7_BITRATE_RF_32 | T55x7_MODULATION_MANCHESTER | (2 << T55x7_MAXBLOCK_SHIFT), 0, 0};
2345 if (q5) {
2346 data[0] = T5555_SET_BITRATE(32) | T5555_MODULATION_MANCHESTER | 2 << T5555_MAXBLOCK_SHIFT;
2347 } else if (em) {
2348 data[0] = (EM4x05_SET_BITRATE(32) | EM4x05_MODULATION_MANCHESTER | EM4x05_SET_NUM_BLOCKS(2));
2351 data[1] = bytes_to_num(blocks, 4);
2352 data[2] = bytes_to_num(blocks + 4, 4);
2354 // Program the data blocks for supplied ID and the block 0 config
2355 if (em) {
2356 WriteEM4x05(data, 4, 3, ledcontrol);
2357 } else {
2358 WriteT55xx(data, 0, 3, ledcontrol);
2360 if (ledcontrol) LED_D_OFF();
2361 reply_ng(CMD_LF_VIKING_CLONE, PM3_SUCCESS, NULL, 0);
2364 int copy_em410x_to_t55xx(uint8_t card, uint8_t clock, uint32_t id_hi, uint32_t id_lo, bool add_electra, bool ledcontrol) {
2366 // Define 9bit header for EM410x tags
2367 #define EM410X_HEADER 0x1FF
2368 #define EM410X_ID_LENGTH 40
2370 uint32_t clockbits = 0;
2371 if (card == 1) { //t55x7
2372 clockbits = GetT55xxClockBit(clock);
2373 if (clockbits == 0) {
2374 Dbprintf("Invalid clock rate: %d", clock);
2375 return PM3_EINVARG;
2379 int i;
2380 uint64_t id = EM410X_HEADER;
2381 uint64_t rev_id = 0; // reversed ID
2382 int c_parity[4]; // column parity
2383 int r_parity = 0; // row parity
2385 // Reverse ID bits given as parameter (for simpler operations)
2386 for (i = 0; i < EM410X_ID_LENGTH; ++i) {
2387 if (i < 32) {
2388 rev_id = (rev_id << 1) | (id_lo & 1);
2389 id_lo >>= 1;
2390 } else {
2391 rev_id = (rev_id << 1) | (id_hi & 1);
2392 id_hi >>= 1;
2396 for (i = 0; i < EM410X_ID_LENGTH; ++i) {
2397 int id_bit = rev_id & 1;
2399 if (i % 4 == 0) {
2400 // Don't write row parity bit at start of parsing
2401 if (i)
2402 id = (id << 1) | r_parity;
2403 // Start counting parity for new row
2404 r_parity = id_bit;
2405 } else {
2406 // Count row parity
2407 r_parity ^= id_bit;
2410 // First elements in column?
2411 if (i < 4)
2412 // Fill out first elements
2413 c_parity[i] = id_bit;
2414 else
2415 // Count column parity
2416 c_parity[i % 4] ^= id_bit;
2418 // Insert ID bit
2419 id = (id << 1) | id_bit;
2420 rev_id >>= 1;
2423 // Insert parity bit of last row
2424 id = (id << 1) | r_parity;
2426 // Fill out column parity at the end of tag
2427 for (i = 0; i < 4; ++i)
2428 id = (id << 1) | c_parity[i];
2430 // Add stop bit
2431 id <<= 1;
2433 if (ledcontrol) LED_D_ON();
2435 // Write EM410x ID
2436 uint32_t data[] = {0, (uint32_t)(id >> 32), (uint32_t)(id & 0xFFFFFFFF)};
2438 // default to 64
2439 clock = (clock == 0) ? 64 : clock;
2440 Dbprintf("Clock rate: %d", clock);
2442 uint32_t electra[] = { 0x7E1EAAAA, 0xAAAAAAAA };
2443 uint8_t blocks = 2;
2444 if (add_electra) {
2445 blocks = 4;
2448 if (card == 1) { // T55x7
2449 data[0] = clockbits | T55x7_MODULATION_MANCHESTER | (blocks << T55x7_MAXBLOCK_SHIFT);
2450 } else if (card == 2) { // EM4x05
2451 data[0] = (EM4x05_SET_BITRATE(clock) | EM4x05_MODULATION_MANCHESTER | EM4x05_SET_NUM_BLOCKS(blocks));
2452 } else { // T5555 (Q5)
2453 data[0] = T5555_SET_BITRATE(clock) | T5555_MODULATION_MANCHESTER | (blocks << T5555_MAXBLOCK_SHIFT);
2456 if (card == 2) {
2457 WriteEM4x05(data, 4, 3, ledcontrol);
2458 if (add_electra) {
2459 WriteEM4x05(electra, 7, 2, ledcontrol);
2461 } else {
2462 WriteT55xx(data, 0, 3, ledcontrol);
2463 if (add_electra) {
2464 WriteT55xx(electra, 3, 2, ledcontrol);
2468 if (ledcontrol) LEDsoff();
2470 Dbprintf("Tag %s written with 0x%08x%08x",
2471 card == 0 ? "T5555" : (card == 1 ? "T55x7" : "EM4x05"),
2472 (uint32_t)(id >> 32),
2473 (uint32_t)id
2476 if (add_electra) {
2477 Dbprintf("Electra 0x%08x%08x\n", electra[0], electra[1]);
2480 return PM3_SUCCESS;
2483 //-----------------------------------
2484 // EM4469 / EM4305 routines
2485 //-----------------------------------
2486 // Below given command set.
2487 // Commands are including the even parity, binary mirrored
2488 #define FWD_CMD_LOGIN 0xC
2489 #define FWD_CMD_WRITE 0xA
2490 #define FWD_CMD_READ 0x9
2491 #define FWD_CMD_PROTECT 0x3
2492 #define FWD_CMD_DISABLE 0x5
2494 static uint8_t forwardLink_data[64]; //array of forwarded bits
2495 static uint8_t *forward_ptr; //ptr for forward message preparation
2496 static uint8_t fwd_bit_sz; //forwardlink bit counter
2497 static uint8_t *fwd_write_ptr; //forwardlink bit pointer
2499 //====================================================================
2500 // prepares command bits
2501 // see EM4469 spec
2502 //====================================================================
2503 //--------------------------------------------------------------------
2504 // VALUES TAKEN FROM EM4x function: SendForward
2505 // START_GAP = 440; (55*8) cycles at 125kHz (8us = 1cycle)
2506 // WRITE_GAP = 128; (16*8)
2507 // WRITE_1 = 256 32*8; (32*8)
2509 // These timings work for 4469/4269/4305 (with the 55*8 above)
2510 // WRITE_0 = 23*8 , 9*8
2512 static uint8_t Prepare_Cmd(uint8_t cmd) {
2514 *forward_ptr++ = 0; //start bit
2515 *forward_ptr++ = 0; //second pause for 4050 code
2517 *forward_ptr++ = cmd;
2518 cmd >>= 1;
2519 *forward_ptr++ = cmd;
2520 cmd >>= 1;
2521 *forward_ptr++ = cmd;
2522 cmd >>= 1;
2523 *forward_ptr++ = cmd;
2525 return 6; //return number of emitted bits
2528 //====================================================================
2529 // prepares address bits
2530 // see EM4469 spec
2531 //====================================================================
2532 static uint8_t Prepare_Addr(uint8_t addr) {
2534 register uint8_t line_parity;
2536 uint8_t i;
2537 line_parity = 0;
2538 for (i = 0; i < 6; i++) {
2539 *forward_ptr++ = addr;
2540 line_parity ^= addr;
2541 addr >>= 1;
2544 *forward_ptr++ = (line_parity & 1);
2546 return 7; //return number of emitted bits
2549 //====================================================================
2550 // prepares data bits intreleaved with parity bits
2551 // see EM4469 spec
2552 //====================================================================
2553 static uint8_t Prepare_Data(uint16_t data_low, uint16_t data_hi) {
2555 register uint8_t column_parity;
2556 register uint8_t i, j;
2557 register uint16_t data;
2559 data = data_low;
2560 column_parity = 0;
2562 for (i = 0; i < 4; i++) {
2563 register uint8_t line_parity = 0;
2564 for (j = 0; j < 8; j++) {
2565 line_parity ^= data;
2566 column_parity ^= (data & 1) << j;
2567 *forward_ptr++ = data;
2568 data >>= 1;
2570 *forward_ptr++ = line_parity;
2571 if (i == 1)
2572 data = data_hi;
2575 for (j = 0; j < 8; j++) {
2576 *forward_ptr++ = column_parity;
2577 column_parity >>= 1;
2579 *forward_ptr = 0;
2581 return 45; //return number of emitted bits
2584 //====================================================================
2585 // Forward Link send function
2586 // Requires: forwarLink_data filled with valid bits (1 bit per byte)
2587 // fwd_bit_count set with number of bits to be sent
2588 //====================================================================
2589 static void SendForward(uint8_t fwd_bit_count, bool fast) {
2591 // iceman, 21.3us increments for the USclock verification.
2592 // 55FC * 8us == 440us / 21.3 === 20.65 steps. could be too short. Go for 56FC instead
2593 // 32FC * 8us == 256us / 21.3 == 12.018 steps. ok
2594 // 16FC * 8us == 128us / 21.3 == 6.009 steps. ok
2595 #ifndef EM_START_GAP
2596 #define EM_START_GAP 55*8
2597 #endif
2599 fwd_write_ptr = forwardLink_data;
2600 fwd_bit_sz = fwd_bit_count;
2602 if (! fast) {
2603 // Set up FPGA, 125kHz or 95 divisor
2604 LFSetupFPGAForADC(LF_DIVISOR_125, true);
2606 // force 1st mod pulse (start gap must be longer for 4305)
2607 fwd_bit_sz--; //prepare next bit modulation
2608 fwd_write_ptr++;
2610 turn_read_lf_off(EM_START_GAP);
2611 turn_read_lf_on(18 * 8);
2613 // now start writing with bitbanging the antenna. (each bit should be 32*8 total length)
2614 while (fwd_bit_sz-- > 0) { //prepare next bit modulation
2615 if (((*fwd_write_ptr++) & 1) == 1) {
2616 WaitUS(32 * 8);
2617 } else {
2618 turn_read_lf_off(23 * 8);
2619 turn_read_lf_on(18 * 8);
2624 static void EM4xLoginEx(uint32_t pwd) {
2625 forward_ptr = forwardLink_data;
2626 uint8_t len = Prepare_Cmd(FWD_CMD_LOGIN);
2627 len += Prepare_Data(pwd & 0xFFFF, pwd >> 16);
2628 SendForward(len, false);
2629 //WaitUS(20); // no wait for login command.
2630 // should receive
2631 // 0000 1010 ok
2632 // 0000 0001 fail
2635 void EM4xBruteforce(uint32_t start_pwd, uint32_t n, bool ledcontrol) {
2636 // With current timing, 18.6 ms per test = 53.8 pwds/s
2637 reply_ng(CMD_LF_EM4X_BF, PM3_SUCCESS, NULL, 0);
2638 StartTicks();
2639 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
2640 WaitMS(20);
2641 if (ledcontrol) LED_A_ON();
2642 LFSetupFPGAForADC(LF_DIVISOR_125, true);
2643 uint32_t candidates_found = 0;
2644 for (uint32_t pwd = start_pwd; pwd < 0xFFFFFFFF; pwd++) {
2645 if (((pwd - start_pwd) & 0x3F) == 0x00) {
2646 WDT_HIT();
2647 if (BUTTON_PRESS() || data_available()) {
2648 Dbprintf("EM4x05 Bruteforce Interrupted");
2649 break;
2652 // Report progress every 256 attempts
2653 if (((pwd - start_pwd) & 0xFF) == 0x00) {
2654 Dbprintf("Trying: %06Xxx", pwd >> 8);
2656 clear_trace();
2658 forward_ptr = forwardLink_data;
2659 uint8_t len = Prepare_Cmd(FWD_CMD_LOGIN);
2660 len += Prepare_Data(pwd & 0xFFFF, pwd >> 16);
2661 SendForward(len, true);
2663 WaitUS(400);
2664 DoPartialAcquisition(0, false, 350, 1000, ledcontrol);
2665 uint8_t *mem = BigBuf_get_addr();
2666 if (mem[334] < 128) {
2667 candidates_found++;
2668 Dbprintf("Password candidate: " _GREEN_("%08X"), pwd);
2669 if ((n != 0) && (candidates_found == n)) {
2670 Dbprintf("EM4x05 Bruteforce Stopped. %i candidate%s found", candidates_found, candidates_found > 1 ? "s" : "");
2671 break;
2674 // Beware: if smaller, tag might not have time to be back in listening state yet
2675 WaitMS(1);
2677 StopTicks();
2678 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
2679 if (ledcontrol) LEDsoff();
2682 void EM4xLogin(uint32_t pwd, bool ledcontrol) {
2684 StartTicks();
2685 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
2686 WaitMS(20);
2688 if (ledcontrol) LED_A_ON();
2690 // clear buffer now so it does not interfere with timing later
2691 BigBuf_Clear_ext(false);
2693 EM4xLoginEx(pwd);
2695 WaitUS(400);
2696 // We need to acquire more than needed, to help demodulators finding the proper modulation
2697 DoPartialAcquisition(0, false, 6000, 1000, ledcontrol);
2699 StopTicks();
2700 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
2701 reply_ng(CMD_LF_EM4X_LOGIN, PM3_SUCCESS, NULL, 0);
2702 if (ledcontrol) LEDsoff();
2705 void EM4xReadWord(uint8_t addr, uint32_t pwd, uint8_t usepwd, bool ledcontrol) {
2707 StartTicks();
2708 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
2709 WaitMS(20);
2711 if (ledcontrol) LED_A_ON();
2713 // clear buffer now so it does not interfere with timing later
2714 BigBuf_Clear_ext(false);
2716 /* should we read answer from Logincommand?
2718 * should receive
2719 * 0000 1010 ok
2720 * 0000 0001 fail
2722 if (usepwd) EM4xLoginEx(pwd);
2724 forward_ptr = forwardLink_data;
2725 uint8_t len = Prepare_Cmd(FWD_CMD_READ);
2726 len += Prepare_Addr(addr);
2728 SendForward(len, false);
2730 WaitUS(400);
2732 DoPartialAcquisition(0, false, 6000, 1000, ledcontrol);
2734 StopTicks();
2735 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
2736 reply_ng(CMD_LF_EM4X_READWORD, PM3_SUCCESS, NULL, 0);
2737 if (ledcontrol) LEDsoff();
2740 void EM4xWriteWord(uint8_t addr, uint32_t data, uint32_t pwd, uint8_t usepwd, bool ledcontrol) {
2742 StartTicks();
2743 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
2744 WaitMS(50);
2746 if (ledcontrol) LED_A_ON();
2748 // clear buffer now so it does not interfere with timing later
2749 BigBuf_Clear_ext(false);
2751 /* should we read answer from Logincommand?
2753 * should receive
2754 * 0000 1010 ok.
2755 * 0000 0001 fail
2757 if (usepwd) EM4xLoginEx(pwd);
2759 forward_ptr = forwardLink_data;
2760 uint8_t len = Prepare_Cmd(FWD_CMD_WRITE);
2761 len += Prepare_Addr(addr);
2762 len += Prepare_Data(data & 0xFFFF, data >> 16);
2764 SendForward(len, false);
2766 if (tearoff_hook() == PM3_ETEAROFF) { // tearoff occurred
2767 StopTicks();
2768 reply_ng(CMD_LF_EM4X_WRITEWORD, PM3_ETEAROFF, NULL, 0);
2769 } else {
2770 // Wait 20ms for write to complete?
2771 // No, when write is denied, err preamble comes much sooner
2772 //WaitUS(10820); // tPC+tWEE
2774 DoPartialAcquisition(0, false, 6000, 1000, ledcontrol);
2776 StopTicks();
2777 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
2778 reply_ng(CMD_LF_EM4X_WRITEWORD, PM3_SUCCESS, NULL, 0);
2780 if (ledcontrol) LEDsoff();
2783 void EM4xProtectWord(uint32_t data, uint32_t pwd, uint8_t usepwd, bool ledcontrol) {
2785 StartTicks();
2786 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
2787 WaitMS(50);
2789 if (ledcontrol) LED_A_ON();
2791 // clear buffer now so it does not interfere with timing later
2792 BigBuf_Clear_ext(false);
2794 /* should we read answer from Logincommand?
2796 * should receive
2797 * 0000 1010 ok.
2798 * 0000 0001 fail
2800 if (usepwd) EM4xLoginEx(pwd);
2802 forward_ptr = forwardLink_data;
2803 uint8_t len = Prepare_Cmd(FWD_CMD_PROTECT);
2804 len += Prepare_Data(data & 0xFFFF, data >> 16);
2806 SendForward(len, false);
2808 if (tearoff_hook() == PM3_ETEAROFF) { // tearoff occurred
2809 StopTicks();
2810 reply_ng(CMD_LF_EM4X_PROTECTWORD, PM3_ETEAROFF, NULL, 0);
2811 } else {
2812 // Wait 20ms for write to complete?
2813 // No, when write is denied, err preamble comes much sooner
2814 //WaitUS(13640); // tPC+tPR
2816 DoPartialAcquisition(0, false, 6000, 1000, ledcontrol);
2817 StopTicks();
2818 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
2819 reply_ng(CMD_LF_EM4X_PROTECTWORD, PM3_SUCCESS, NULL, 0);
2821 if (ledcontrol) LEDsoff();
2825 Reading COTAG.
2827 COTAG needs the reader to send a startsequence and the card has an extreme slow datarate.
2828 because of this, we can "sample" the data signal but we interpreate it to Manchester direct.
2830 This behavior looks very similar to old ancient Motorola Flexpass
2832 -----------------------------------------------------------------------
2833 According to patent EP0040544B1:
2834 Operating freq
2835 reader 132 kHz
2836 tag 66 kHz
2838 Divide by 384 counter
2840 PULSE repetition 5.82ms
2841 LOW 2.91 ms
2842 HIGH 2.91 ms
2844 Also references to a half-bit format and leading zero.
2845 -----------------------------------------------------------------------
2847 READER START SEQUENCE:
2849 burst 800 us gap 2.2 ms
2850 burst 3.6 ms gap 2.2 ms
2851 burst 800 us gap 2.2 ms
2852 pulse 3.6 ms
2854 This triggers COTAG tag to response
2857 void Cotag(uint32_t arg0, bool ledcontrol) {
2858 #ifndef OFF
2859 # define OFF(x) { FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); WaitUS((x)); }
2860 #endif
2861 #ifndef ON
2862 # define ON(x) { FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_READER | FPGA_LF_ADC_READER_FIELD); WaitUS((x)); }
2863 #endif
2864 uint8_t rawsignal = arg0 & 0xF;
2866 if (ledcontrol) LED_A_ON();
2868 LFSetupFPGAForADC(LF_FREQ2DIV(132), true); //132
2870 //clear buffer now so it does not interfere with timing later
2871 BigBuf_free();
2872 BigBuf_Clear_ext(false);
2874 // send COTAG start pulse
2875 // http://www.proxmark.org/forum/viewtopic.php?id=4455
2877 ON(740) OFF(2035)
2878 ON(3330) OFF(2035)
2879 ON(740) OFF(2035)
2880 ON(2000)
2882 ON(800) OFF(2200)
2883 ON(3600) OFF(2200)
2884 ON(800) OFF(2200)
2885 ON(2000) // ON(3400)
2887 FpgaSendCommand(FPGA_CMD_SET_DIVISOR, LF_FREQ2DIV(66)); // 66kHz
2889 switch (rawsignal) {
2890 case 0: {
2891 doCotagAcquisition();
2892 reply_ng(CMD_LF_COTAG_READ, PM3_SUCCESS, NULL, 0);
2893 break;
2895 case 1: {
2896 uint8_t *dest = BigBuf_malloc(COTAG_BITS);
2897 uint16_t bits = doCotagAcquisitionManchester(dest, COTAG_BITS);
2898 reply_ng(CMD_LF_COTAG_READ, PM3_SUCCESS, dest, bits);
2899 break;
2901 case 2: {
2902 DoAcquisition_config(false, 0, ledcontrol);
2903 reply_ng(CMD_LF_COTAG_READ, PM3_SUCCESS, NULL, 0);
2904 break;
2906 default: {
2907 reply_ng(CMD_LF_COTAG_READ, PM3_SUCCESS, NULL, 0);
2908 break;
2913 // Turn the field off
2914 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
2915 if (ledcontrol) LEDsoff();
2919 * EM4305 support