Commit Graph
23283 Commits
Author SHA1 Message Date
iceman1001andClaude Opus 5 89305b2f8b usb: bound the wait for the host to collect a STALL
AT91F_USB_SendStall spun on STALLSENT with no exit. That bit only
arrives once the host polls the endpoint and takes the handshake, so a
host that vanishes in between wedges the device. It was the last
unbounded wait in the file without an escape.

Exit on RXSETUP (host abandoned the request and sent a new SETUP), on
ENDBUSRES, or on a spin count, reusing the 0x1FFF that usb_read already
uses. usb_check() is not usable here: it calls back into
AT91F_CDC_Enumerate, which is what calls this.

Do not test RXSUSP. Nothing writes it back to UDP_ICR, so it latches on
the first bus idle and stays set, which makes the guard fire on every
stall and stops the STALL from ever being delivered.

The second wait is bounded too, since leaving the first one early can
let the host set STALLSENT after the clear.

Also ISOERROR -> STALLSENT. Same bit 3, but only one of those names is
true on a control endpoint.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-15 18:12:34 +02:00
iceman1001andClaude Opus 5 fcb61153f8 usb: pack the CDC line coding struct to its 7 wire bytes
uint32_t plus three uint8_t pads to 8, so sizeof(line) was 8 where CDC
defines 7. Hosts asking for more than 7 got a byte of uninitialised
static padding. The commented out SET_LINE_CODING loop already hardcodes
i < 7, so the wire format was understood; the struct just did not match.

No observable change for cdc_acm or usbser.sys, which both ask for
exactly 7.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-15 18:00:09 +02:00
iceman1001andClaude Opus 5 5cf1b18c1e usb: terminate short control IN transfers with a ZLP
AT91F_USB_SendData only took length, and every caller passed
MIN(sizeof(x), wLength), so the function could not tell it had
truncated. A control IN transfer ends on wLength bytes or on a short
packet; returning fewer than wLength in whole 8 byte packets is neither,
and the host polls until it times out.

Take wLength too, do the MIN inside, and send a ZLP when the reply is
shorter than asked and lands on a packet boundary. The length > 0 guard
avoids a second termination, since the send loop already emits an empty
packet for an empty payload.

This is what the serial number descriptor's '(size % 8) == 0 OS bug
workaround' padding was dodging. Not an OS bug.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-15 17:54:18 +02:00
iceman1001andClaude Opus 5 485180e055 usb: answer the WCID vendor request instead of stalling it
StrMS_OSDescriptor advertises MSFT100 and vendor code 0x1C, but the
handler for that request was commented out, so it fell through to the
standard switch and stalled. Windows caches that under
usbflags\<VID><PID><bcdDevice> and stops asking, and bcdDevice never
changes, so no reflash could recover it.

Enable both feature descriptors and answer 0x1C in AT91F_CDC_Enumerate.
The compatible ID is left empty so usbser.sys keeps binding; WINUSB
there would take interface 0 away from CDC and kill the COM port.
DeviceInterfaceGUID was GUID_DEVCLASS_PORTS, a setup class GUID in an
interface GUID field - replaced with a fixed project GUID.

AT32 is unchanged; both descriptors are behind #ifndef PM5.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-15 17:41:43 +02:00
iceman1001andClaude Opus 5 f653897286 hf mfdes sim: answer GetDFNames and GetISOFileIDs
Both were unimplemented, so they fell through to ILLEGAL_COMMAND_CODE and a
reader walking the simulated card saw every ISO file id and DF name blank.

GetDFNames (0x6D) is PICC level and chains, one application per frame: AID
LSB first, ISO file id little endian, then the DF name. Applications without a
DF name are not sent back at all, which the spec is explicit about (M134034
9.4.4, "If the DC [sic, DF] has no DF name it is not sent back within this
command"), so the walk steps past them and only the last record carries
OPERATION_OK. Verified on the wire against a reader, and the frames come back
the same shape a genuine EV1 8K produces:

    90 6D  ->  03 02 01 | 34 12 | "test1"  91 AF
    90 AF  ->  33 22 11 | 45 23 | "test2"  91 AF
    90 AF  ->  CC BB AA | 56 34 | "test3"  91 00

GetISOFileIDs (0x61) is application level and lists the ISO file ids of the
files that have one. Value files and transaction MAC files never carry one, so
they are skipped -- that matters because the client maps the returned ids onto
files positionally, and including them would shift every id after onto the
wrong file. When no file in the application has an ISO file id the answer is
FILE_NOT_FOUND, which is what 9.5.2 means by "If there is no ISO File EF, only
an error code can be returned", and is already what the client reads as an
application created without ISO file ids.

With these in place `hf mfdes lsapp` and `hf mfdes lsfiles` report the
simulated card completely: ISO ids 0x1234 / 0x2345 / 0x3456, DF names test1 /
test2 / test3, and per file ids 0001, 0002, 0011, 0033, 0055 with the value
file correctly showing n/a.

Not done: 0x61 is answered in a single frame. The spec allows it to chain, 27
file ids in the first frame and up to 5 more after, so an application holding
more ISO file ids than fit one frame would need the chained path that 0x6D
already has.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-15 14:55:41 +02:00
iceman1001 6755b96323 added a couple of desfire test files for easy simmulation 2026-09-15 14:49:32 +02:00
iceman1001andClaude Opus 5 2d70fcb4ff hf mfdes sim: self contained DESFire simulation, and stop bitstream downloads eating emulator memory
The DESFire simulation gets its own ISO 14443-A loop in armsrc/desfiresim.c
rather than hooking into SimulateIso14443aTag(). That function is complicated
enough without a DESFire state machine threaded through it, and the hook had
already got the ATQA wrong once. It still borrows the library helpers from
iso14443a.c -- the precompiled activation answers, the receive call, the send
calls -- so there is no duplicated state machine, and iso14443a.c goes back to
knowing nothing about DESFire. desfiresim.h exports one symbol.

Three fixes were needed to make it actually answer a reader.

1. ISO 7816 wrapping. A reader sends `02 90 60 00 00 00`, not `02 60`. The
   simulation read in[0] as the DESFire command and so saw 0x90, the class
   byte, answering ILLEGAL_COMMAND_CODE to everything -- and in native form
   (status || data) when the reader wanted the wrapped form (data || 91 SW).
   Both framings are handled now, including the Lc/Le distinction: five bytes
   means no data and in[4] is Le, longer means in[4] is Lc with data following.

2. A bitstream download frees and clears BigBuf to get scratch space for the
   decompressor. SimulateIso14443aTagEx() and Mifare1ksim() both guard against
   this by calling FpgaDownloadAndGo_keep_EM() before they allocate anything;
   the new loop did not, so iso14443a_setup() wiped the emulator memory holding
   the card image and the precompiled answers after they had been filled. The
   pointers survive, the bytes do not, and the tag then clocks out zeros.

3. iso14443a_setup() itself used the plain FpgaDownloadAndGo(), which does
   BigBuf_free() and BigBuf_Clear_ext() -- taking the emulator memory with it.
   Every 14a command comes through there, so a card image that `eload` had just
   put in place was destroyed by the next `hf 14a` command whenever the HF
   bitstream was not already resident. Demonstrated before and after:
   `eload` then `hf 14a reader` then `eview` used to report "No DESFire card
   image in emulator memory" and now returns the image intact. This affected
   every emulator memory user, not only DESFire.

Verified against a second Proxmark3 acting as reader, simulating a real
DESFire EV1 8K dump: activation (UID 04268512A25680, ATQA 03 44, SAK 20,
ATS 06 75 77 81 02 80), the three frame GetVersion chain over 0xAF, GetFreeMem,
GetApplicationIDs, SelectApplication, GetKeySettings and GetFileSettings.
`hf mfdes info`, `getaids`, `freemem`, `lsapp` and `lsfiles` all read correctly,
including per application key types (AES, 2TDEA, 3TDEA) and all five EV1 file
types with their real settings -- a value file holding 1000 with limits
[0..10000], a linear record 2/8 of 16 bytes, a cyclic record 1/4 of 24 bytes,
standard files of 256 and 64 bytes, and a backup file of 128 bytes in MAC mode
with keyed rights 1200.

Not implemented yet: GetDFNames (0x6D) and GetISOFileIDs (0x61), so a reader
sees empty ISO IDs and DF names. Everything else answers
ILLEGAL_COMMAND_CODE, which is what a PICC says to a command it does not have.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-15 14:43:52 +02:00
iceman1001 d882c716af adaptations of VIGIK parsers 2026-09-15 14:39:14 +02:00
iceman1001 a528d5ac1b text 2026-09-15 11:16:15 +02:00
Iceman d3f626c0d2 Merge pull request #3627 from Antiklesys/master
Fix PM5 I2C speed issues
2026-09-15 15:17:40 +07:00
Antiklesys 9d2a594f75 Fix PM5 I2C speed issues 2026-09-15 16:02:46 +08:00
iceman1001 e6c1c4e1a7 final batch of adding NULL checks 2026-09-15 08:36:13 +02:00
iceman1001 0cfe0e0e8d add NULL checks 2026-09-15 08:29:06 +02:00
iceman1001 45d4856f3a add NULL checks. this might be the most time sensitive one 2026-09-15 08:26:01 +02:00
iceman1001 6ab8c8f381 maybe this silence MacOS about the homebrew repo 2026-09-15 08:23:37 +02:00
iceman1001 c80f0dd93f add NULL checks 2026-09-15 08:21:25 +02:00
iceman1001 a8fcc081b5 add NULL checks 2026-09-15 08:17:05 +02:00
iceman1001 57f8613b83 add NULL checks 2026-09-15 08:14:02 +02:00
iceman1001 e3429580fd added NULL checks 2026-09-15 08:10:09 +02:00
iceman1001 4024639e5d add NULL checks 2026-09-15 08:03:54 +02:00
iceman1001 7eb4ecb332 text 2026-09-14 22:31:35 +02:00
iceman1001 c0e20a9121 text 2026-09-14 22:27:58 +02:00
iceman1001 7b16d091ac text 2026-09-14 22:27:31 +02:00
iceman1001 b706d715b9 text 2026-09-14 22:27:01 +02:00
iceman1001 06ebe87cae desfire simulation to support native and iso7816 wrapping 2026-09-14 22:19:38 +02:00
iceman1001 59cd76905f minor fix, obey 2026-09-14 22:18:27 +02:00
iceman1001 72f3f15dd3 found a new public key! 2026-09-14 22:17:13 +02:00
iceman1001andClaude Opus 5 8225d76ccd hf mfdes: stop GetDFNames from permanently disabling DESFire EV1 cards
Sending GetDFNames (0x6D) inside an authenticated session destroys DESFire EV1
silicon. When the response chains, the card answers the first 0xAF continuation
frame with 0xC1 PICC_INTEGRITY_ERROR, "PICC will be disabled", and from that
moment every command returns 0xCD PICC_DISABLED_ERROR. The ATS historical byte
changes 0x80 -> 0x90. Three cards were destroyed establishing this.

It is reached by `hf mfdes dump`, `hf mfdes lsapp` and `hf mfdes info --files`,
all of which authenticate and then call DesfireFillAppList.

HOW IT WAS ISOLATED

One variable at a time, on a card that survived all of it. Unauthenticated, the
identical frames are answered normally:

  - 0x6D on a blank card
  - 0x6D with an application that has no DF name (empty, per 9.4.4)
  - 0x6D with one DF name, single frame, no chaining
  - 0x6D chained over two and then three DF names, sent by hand
  - the chain abandoned mid-way with the field dropped
  - a stray 0xAF with no chain open, answered 91 1C
  - the client's own chaining code with splitbysize

Authenticated, the same card died on the first continuation frame. The client
appends no MAC to 0x6D -- it is not in EV1D40TransmitMAC -- so the bytes on the
wire are `90 6D 00 00 00` then `90 AF 00 00 00` either way, byte for byte
identical to the probes that passed. Only the card's session state differs.

Ruled out along the way:

  - Failed or wrong-algorithm authentication. `hf mfdes chk` has fired hundreds
    of failed auths per card for years without harm.
  - Abandoned authentication chains. DesfireCheckAuthCmd sends only the first
    frame of an auth and then drops the field, six times per `hf mfdes info`
    run; 30 of them left the test card healthy.
  - Malformed commands. The only out-of-spec command in the original sequence
    (UpdateRecord, 18 bytes into a 16 byte record) was refused client-side and
    never reached the card.
  - Chaining itself, DF names themselves, and the record count.

THE FIX

Drop the PICC session around the call and restore it afterwards.

It is the card's session that has to go, not the context. Clearing
DesfireContext_t alone would leave the card authenticated and change nothing, so
SelectApplication is used: "each SelectApplication command invalidates the
current authentication status" (M134034 9.4.5).

The session is then re-established on whatever AID was selected when we were
called, not on 000000. The issuer info path enters DesfireFillAppList with an
application already selected, and re-authenticating the PICC with that
application's key would silently fail. A context selected by DF name has no AID
to return to, so the DF name list is skipped rather than guessed at.

No configuration forces the unsafe order. Key settings bit 1 governs whether the
directory commands need authentication, and its "needs auth" branch names only
GetApplicationIDs and GetKeySettings, not GetDFNames (M134034 p.39). A card that
refuses the plain command costs the DF name column; sending it authenticated
costs the card.

WHAT THE DATASHEETS SAY

EV1 never specifies how secure messaging applies across 0xAF frames. EV3 had to
write the rule down later, ev3.pdf 7.3.2.2: "the secure messaging is applied as
if the command or response would have been sent in a single large frame. The
0xAF command and response codes are ignored for these calculations." The exact
interaction that destroys these cards is the one EV1 left unwritten.

EV2 and EV3 then deleted the whole self-disable family: ev3.pdf contains zero
occurrences of PICC_DISABLED or PICC_INTEGRITY, which M134034 defines. EV3
renames 0xEE to MEMORY_ERROR and says the part may execute a reset rather than
disable itself.

Whether the disabled state is recoverable is SILENT in every direction. The five
codes appear once each, in one status table, with no prose anywhere, and there is
no lifecycle command in DESFire to rehabilitate a PICC. Measured on a dead card,
nothing works: FormatPICC cannot authenticate (0x1A -> 91 CD) and is refused raw
(90 FC -> 91 CD); SelectApplication is refused (91 CD) even though it needs no
authentication and no bit can gate it; every ISO 7816 command including ACTIVATE
FILE and TERMINATE DF answers 65 81 "Memory failure". A malformed GetVersion
still answers 91 7E LENGTH_ERROR, so anticollision, RATS, the command parser and
length validation all still run -- only the application layer underneath is gone.

Note M075031 is the D40 datasheet, not EV1; the EV1 document is M134034.

ALSO IN THIS CHANGE, because without them the cause was invisible

Every card error collapsed to PM3_EAPDU_FAIL before reaching a caller, and both
send paths only printed the status when -a was given. That is why the first two
cards told us nothing about how they died.

  - The five codes M134034 Table 11 footnotes as "not expected to appear during
    normal operation" (0xC1, 0xCD, 0xA1, 0xF1, 0xEE) are now reported from both
    DESFIRESendRaw and DESFIRESendApduEx whether or not -a is given. Ordinary
    refusals stay at debug level, so chk and the ISO file id probes stay quiet.
  - A chained 0xAF is attributed to the command it is continuing, so a failure
    reads "command 0x6D frame 0xAF -> 0xC1" rather than a bare 0xAF.
  - DesfireContext_t keeps lastRespCode, set where both exchange paths meet.

A command error also ends the authentication on the PICC, so the client now
drops its side of the session rather than continuing to MAC into a session the
card has thrown away. The tree already did this at one call site
(DesfireGetFileISOIDList); it is now done at the choke point every native
command passes through, plus the paths that bypass it: DesfireReadSignature,
DesfireCreateDelegatedApplication, DesfireISOSelectEx, the ISO data plane
(ReadBinary, UpdateBinary, ReadRecords, AppendRecord) and GetDelegateInfo. The
three ISO authentication wrappers are deliberately left alone, since they run
before a session exists and clearing would wipe the handshake's own state.

`hf mfdes pc` checked only the transport result and treated a card error as
success: DesfireExchangeEx returns PM3_SUCCESS with the card's status in
respcode, so PreparePC, the proximity check rounds and VerifyPC went on to parse
error responses as data. They now check respcode.

DesfireFillFileList discarded the result of DesfireFileSettingsStruct, so a file
whose settings could not be read became a zeroed entry indistinguishable from a
valid 0 byte standard data file. FileListElm_t now carries fileSettingsRead and
five consumers honour it: the ISO id mapping loop (positional, an unread file
would shift every id after it onto the wrong file), `hf mfdes chk`'s used-key
set, lsfiles, the application walk print, and `hf mfdes dump`, where settings_ok
was being set true unconditionally.

DesfireFillAppList tested a stale `res` after DesfireGetKeySettings, whose return
value was discarded; only an incidental buflen guard kept it from consuming
garbage key settings.

`hf mfdes sim` now runs through the shared ISO14443-A simulation loop as tag
type 3 rather than a duplicate 14a loop, which had got the ATQA wrong. The
DESFire logic stays in armsrc/desfiresim.c behind a small hook API.

KNOWN, NOT FIXED HERE

DesfireFillAppList reads the DF name list into uint8_t buf[250] while
DesfireCommandEx copies records * 24 bytes. The EV1 limit of 28 applications
would write 672 bytes into it. Harmless at the record counts seen here, but a
stack overflow waiting for a full card.

VERIFICATION

On a fourth card from the same lot (batch B9 0C 17 49 70, week 27 / 2017, EV1 8K,
HW 04010101001A05, SW 04010101041A05): the sequence that killed the third card
now completes, the chained 0xAF is answered 91 00, and the card is healthy
afterwards. The APDU log shows GetDFNames and its continuation carrying no MAC
while the commands either side of them do, confirming the session is dropped and
restored. A full `hf mfdes dump` of three applications (AES, 2TDEA, 3TDEA) and
all five EV1 file types completes and round-trips through the dump format.

Scope: all four cards are from one production lot. This is not established as an
EV1-wide erratum.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-14 21:50:21 +02:00
iceman1001 52f3225661 parser adaptation 2026-09-14 21:13:52 +02:00
iceman1001 a7b1276781 phase 1 simulation and desfire fixes... 2026-09-14 21:13:10 +02:00
iceman1001 e5a44e1874 fix more parsing 2026-09-14 20:30:15 +02:00
iceman1001 e72bcdb1c0 fix identifyer 2026-09-14 20:04:18 +02:00
iceman1001 522cb742b5 remove unused fct 2026-09-14 19:56:57 +02:00
iceman1001 ce370d5384 fix codeql warning 2026-09-14 19:55:08 +02:00
iceman1001andClaude Opus 5 (1M context) ee2d55fafb hf mfdes: put a DESFire card image in emulator memory
Adds the on-device card image a DESFire simulation will read, the client
side that packs a dump into it, and eload / esave / eview.

The layout is in include/desfire_em.h. Tables grow up from the header,
file data grows down from the end, and an allocation only has to leave
the two frontiers apart -- so a three-file card spends a few hundred
bytes rather than a worst case, and the space between them is what the
card has left. The PICC is application 000000 and uses the same struct
as any other application, so key settings and keys are always stated
against an AID. Delete sets a tombstone rather than compacting, which is
not a shortcut: a real card does not reclaim on delete either, measured
as 2080 bytes free with zero applications before an experiment and 2560
after FormatPICC.

Two size limits, and a reader only ever sees the first. cardsize is what
the emulated card claims to hold, so GetFreeMem answers from that and
CreateFile will refuse with OUT_OF_EEPROM when it runs out. Without it a
card impersonating a 2K part would report 7434 bytes free, which no 2K
part does. The image size is what emulator memory physically holds, is
the harder limit, and is never visible.

cardsize is anchored to the free memory the real card reported when the
dump was taken -- observed free plus what we reserve for the same content
-- so the emulation answers what its original answered. That is also a
check on the reservation rule rather than only a convenience: for the
bench card it computed 576 bytes spent, and 1984 + 576 is 2560, exactly
what that card reports when formatted.

Reservation follows what CommitTransaction covers. Backup data, value and
record files each get a shadow region because writes to them are staged
until commit; a standard data file writes through and does not. Sizes
round to a 32 byte granule, which is the granule a real card allocates in.
It deliberately does not reproduce NXP's allocator -- that is
undocumented and does not fit a simple model, a declared 1024 byte record
file costs 1088 on silicon -- so what matters is that the figure is
self-consistent and shrinks as the reader writes.

No new device command. Emulator memory is one shared region, so
CMD_HF_MIFARE_EML_MEMSET and BIG_BUF_EML already reach it, and both
inherit the bounds checking those paths gained earlier.

Verified with the client only, no simulation yet: packing a dump taken
from a DESFire EV2 and walking it back reproduces every field including
file contents byte for byte, the same round trip through the device via
eload and esave is identical, and an image too large is refused by name
rather than truncated -- 'Out of emulator memory laying out AID 112233
file 00: needs 4066 more bytes'.

Co-Authored-By: Claude Opus 5 (1M context)
2026-09-14 19:48:45 +02:00
iceman1001 669319b690 update desfire dumpformat to support verison HW,SW,PROD 2026-09-14 19:39:42 +02:00
iceman1001 c0792409b0 update samples 2026-09-14 19:36:28 +02:00
iceman1001 95f6072e94 minor parse fix for vigik 2026-09-14 19:35:34 +02:00
iceman1001 064f8dd071 added a warning for anti clone counter measures 2026-09-14 18:32:53 +02:00
iceman1001andClaude Opus 5 (1M context) 708d400c57 gpio: let an AT91 board without an FPGA power switch build
PLATFORM=PM3ICOPYX has not compiled at all -- it dies on obj/start.o,
before anything else is built:

    common_arm/gpio/gpio_hw_at91.h:77: error: 'GPIO_FPGA_ON' undeclared
        (first use in this function); did you mean 'GPIO_FPGA_DONE'?

PA26 has two different jobs depending on the FPGA, per
config_gpio_proxmark3.h:

    #if defined XC3
    #define GPIO_FPGA_SWITCH    AT91C_PIO_PA26
    #else
    #define GPIO_FPGA_ON        AT91C_PIO_PA26
    #endif

ICopyX has no FPGA power rail to switch; that pin selects the FPGA
instead. But Gpio_FPGA_ON_High(), Gpio_FPGA_ON_Low() and
gpio_fpga_on_setup() all referenced GPIO_FPGA_ON unconditionally, so the
symbol simply does not exist on XC3.

'This board has no FPGA power switch' is already a supported case: the
AT32 port stubs both accessors with a bare '// Unsupported' comment, and
PM5 depends on that, while Gpio_FPGA_SWITCH_High()/Low() two functions
further down in this same header are guarded with #ifdef for the mirror
case. The AT91 header just never grew the XC3 arm. All three now carry
the same guard.

fpga_loader.c calls Gpio_FPGA_ON_High() from shared code; on ICopyX that
compiles to nothing, which is correct -- the rail is always on.

Verified: fullimage builds for PM3ICOPYX (356832 bytes, with
PLATFORM_EXTRAS=FLASH), and for PM3RDV4, PM3GENERIC, PM3ULTIMATE and
PM5. For the boards that do have the pin the guard costs nothing -- the
.text section is byte-identical before and after, 289464 bytes on
PM3RDV4 and 243584 on PM3GENERIC; only the embedded build timestamp and
source hash move in the full ELF.

Co-Authored-By: Claude Opus 5 (1M context)
2026-09-14 18:20:35 +02:00
Iceman b24dad31c4 Merge pull request #3625 from nieldk/master
Fix ble name resolution and hitag dump (ble)
2026-09-14 23:17:32 +07:00
iceman1001andClaude Opus 5 (1M context) 584624a624 fpga_compress: stop rejecting a bitstream set that exactly fills the buffer
PLATFORM=PM3ULTIMATE has not built since c0ecb1c62 (2026-04-14), which
fixed a real heap overflow by changing one character:

    -        if (total_size > num_infiles * FPGA_CONFIG_SIZE) {
    +        if (total_size >= num_infiles * FPGA_CONFIG_SIZE) {

The old '>' checked after the fact, so a round could start with the
buffer already full and write num_infiles * FPGA_INTERLEAVE_SIZE bytes
past the end. But '>=' answers the wrong question: a buffer that is
exactly full is not an error, it is the expected end state for a
platform whose bitstreams are sized to FPGA_CONFIG_SIZE.

Two things had to change.

all_feof() tested the EOF flag, and C only sets that once a read has
already run off the end -- consuming the last byte of a file leaves it
clear. A file whose length is an exact multiple of FPGA_INTERLEAVE_SIZE
therefore still looked unfinished after its final whole chunk, and the
interleave loop ran one more round of pure zero padding. It now peeks a
byte with fgetc/ungetc instead, so a file read to its last byte counts
as finished right away.

PM3ULTIMATE is the only platform this reaches:

    fpga_pm3_ult_felica.bit   69984   = 243 * 288 exactly
    fpga_pm3_ult_hf_15.bit    69983
    fpga_pm3_ult_hf.bit       69980
    fpga_pm3_ult_lf.bit       69980

243 rounds * 4 files * 288 = 279936, which is exactly
4 * FPGA_CONFIG_SIZE for 2s50vq144. Round 244 was padding only, and '>='
killed it there. Stock PM3's largest bitstream is 42172, not a chunk
multiple, so its last round trips feof naturally and it never gets that
far -- which is why this went unnoticed, nothing in CI builds ULTIMATE.

The guard now asks whether the next round fits, which is the condition
it was always meant to express and is strictly stronger than the
original '>':

    if (total_size + (num_infiles * FPGA_INTERLEAVE_SIZE) > num_infiles * FPGA_CONFIG_SIZE)

Verified: PM3ULTIMATE compresses 279936 bytes to 40195 and all four
bitstreams decompress back byte-exact. Output is byte-identical to
before for stock 2s30vq100 (169344 -> 106628), for icopyx XC3
(72864 -> 27292) and for the '-s' .data section path. fullimage builds
for PM3ULTIMATE, PM3RDV4, PM3GENERIC and PM5.

Note FPGA_CONFIG_SIZE is now exactly the size of the largest ULTIMATE
bitstream. Regenerate that one byte larger and the guard fires again,
correctly; bump the constant by one interleave step rather than touching
the guard.

Co-Authored-By: Claude Opus 5 (1M context)
2026-09-14 18:12:16 +02:00
iceman1001 e51ef6caff fix defines 2026-09-14 17:24:31 +02:00
iceman1001 fd292048a8 fix redundant definition of ARRAYLEN 2026-09-14 16:58:42 +02:00
iceman1001 1dbb77e238 lesson learned 2026-09-14 16:57:59 +02:00
iceman1001 e3096510c5 text 2026-09-14 16:54:28 +02:00
iceman1001 1f450c9bf8 add missing HF_LEGIC_RDV4 2026-09-14 16:53:50 +02:00
Niel Nielsen d7fb9654d3 fix(hitag): only one reply_ng on reader/writer abort path
ReaderHitag() and WriterHitag() double-replied on the abort path: when a
new command arrives mid-loop, data_available() sets checked = -1 and breaks,
then the out: block calls reply_ng(PM3_ESOFT) *and* falls through to a second
reply_ng(PM3_SUCCESS/EFAILED) — two NG responses for one command.

USB tolerates the stray frame, but over the BLE/FPC bridge the extra
unsolicited response desyncs the pipeline and the device appears to stop
responding until reconnect (reproducible with `lf hitag dump --pwd` on empty
air, then any following command over BLE).

Gate the final reply_ng behind an else so each command yields exactly one
response on every path: abort -> PM3_ESOFT, otherwise -> PM3_SUCCESS/EFAILED.

Signed-off-by: Niel Nielsen <nieldk@gmail.com>
2026-09-14 16:23:38 +02:00
Niel Nielsen 5f641c6f75 Merge branch 'RfidResearchGroup:master' into master 2026-09-14 16:20:54 +02:00
iceman1001andClaude Opus 5 (1M context) 3e98b2dfe4 hf legic: stop eload losing everything after its first packet
'hf legic eload' writes emulator memory as a burst of back-to-back
packets. CMD_HF_LEGIC_ESET called FpgaDownloadAndGo(FPGA_BITSTREAM_HF)
on every one of them, and when that actually had a bitstream to download
the device stopped servicing USB for long enough that the packets already
in flight behind it were dropped.

Reproducible, and it only shows after a command that left a different
bitstream loaded, which is why it has gone unnoticed:

    hf iclass eload ...      # loads FPGA_BITSTREAM_HF_15
    hf legic eload -f x.bin  # first packet downloads FPGA_BITSTREAM_HF
    hf legic esave --1024    # 404 bytes of 1024 come back as zeros

The boundary is always 619, which is max_cmd_data_size minus
sizeof(legic_packet_t) -- exactly one packet. Back to back a second time
it works, because the bitstream is then already loaded. The 'fast push
mode' in legic_seteml() is not involved: block_after_ACK only applies to
OLD frames and these are NG.

So the handler does no FPGA work at all now. The comment it used to carry
-- 'if it is called later, it might destroy the Emulator Memory' -- was
aiming at a real problem but solving it at the wrong end. init_tag() in
legicrfsim.c is where the bitstream is genuinely needed, and it was using
the plain variant twelve lines above 'legic_mem = BigBuf_get_EM_addr()',
so 'hf legic sim' was wiping the image it was about to serve. That one
becomes _keep_EM.

Five sibling handlers carry the same copy-pasted comment and the same
wipe-before-use pattern and are switched to _keep_EM as well:
CMD_LF_EM4X50_SIM (em4x50_sim reads its tag out of emulator memory),
CMD_LF_EM4X50_ESET, CMD_HF_ISO15693_EML_SETMEM, EML_GETMEM and
CMD_HF_MIFARE_EML_MEMCLR. Only the LEGIC path has a reproducer; the rest
is the same fix applied where the same mistake is visible.

Verified on an RDV4: the reproducer above now loses 0 bytes over three
runs, 'hf legic sim' reports the MCD/MSN of the uploaded image, and
eload/esave still round-trips byte-identical for MIFARE Classic 4K,
iso15693 and iCLASS.

Co-Authored-By: Claude Opus 5 (1M context)
2026-09-14 15:05:31 +02:00