Refactor BLE error handling to return standard error codes instead of PM3_* constants. Update time-related functions to use a consistent method for obtaining the current time.
Signed-off-by: Niel Nielsen <nieldk@gmail.com>
MifareNested collected nonces in 'while (target_nt[i] == 0)' with no
attempt counter. When the tag NAKs the nested authentication the loop
re-sent the identical frame forever, so the client's 2s wait expired and
autopwn returned PM3_ETIMEOUT — throwing away every key recovered up to
that point. Reported on a card whose sector 16 refuses the standard MFC
EV1 keys: 32 keys cracked, nothing saved.
A NAK is a refusal, not a glitch, so the device now gives up on it and
reports PM3_EWRONGANSWER. autopwn names the sector it skipped and carries
on, and a timeout falls through to the key table and the dump whenever
anything was recovered.
Co-Authored-By: Claude Opus 5 (1M context)
DesfireSelectAndAuthenticate*() and its callers both printed the same
error at different severities, so every failure came out as two lines.
The core helper now owns the message and names the AID and the step;
the 23 restatements in cmdhfmfdes.c are gone. Same duplicate pair fixed
in cmdhfgallagher.c.
Also: DesfireAuthErrorToStr() falls back to DesfireGetErrorString() for
the PM3_E* codes the select paths pass through, which used to print an
empty reason, and auth error 7 no longer reuses the text of error 1.
Co-Authored-By: Claude Opus 5 (1M context)
Added a function to check if a string is a valid Bluetooth address and updated the BLE connection logic to handle both addresses and names.
Signed-off-by: Niel Nielsen <nieldk@gmail.com>
'-f card.mfd' looked for card.mfd.bin and saved to card.mfd.bin,
because the caller's suffix was appended unless the name already
ended in that exact suffix.
searchFile() now tries the name as typed before falling back to the
suffixed one. newfilenamemcopyEx() keeps an extension that denotes
the same kind of file it is about to write, and swaps any other for
its own, so 'hf mf dump -f card.mfd' gives card.mfd + card.json
rather than card.mfd + card.mfd.json. Both classify with
get_filetype() so load and save cannot drift apart.
Also drops the size_t underflow in newfilenamemcopyEx(), where a long
path plus a configured save path made the snprintf bound wrap past
the 1000 byte buffer.
Co-Authored-By: Claude Opus 5 (1M context)
is_valid_vigik_card() only fired when the MAD advertised aid 0x4910. Plenty of
VIGIK based deployments ship no MAD at all - a Hexact card has HEXACT as key A
on every sector and nothing in sector 0 block 1 - so hf mf view and hf mf dump
--ns said nothing whatsoever about them.
These systems use the same keys on every card they issue, which makes them
identifiable outright. Take the schemas out of armsrc/Standalone/hf_colin.c,
where they sit commented out inside the standalone mode, and match a whole dump
against them:
Infineon / Hexact / COGELEC / Intratone key A HEXACT x16, 15 static key B
Noralsy ALARON / BLARON
Urmet Captiv 8829da9daf76 throughout
VIGIK service badge MAD key, then 1KIGIV on sectors 1-4
Every slot a schema pins down has to match, VIGIK_KEY_ANY marks the ones it does
not, so there are 31 exact keys to hit for Hexact and no room for a coincidence.
A HID card carrying a MAD, and a card on default keys, both still match nothing.
Co-Authored-By: Claude Opus 5 (1M context)
The shared viewer had the VIGIK sector assembly inlined, and the HID PACS
decode sat in hf mf mad's file branch where hf mf view and hf mf dump --ns
could not reach it. Neither scheme had a home of its own.
Give each one a parser next to parsehrt.c, same shape as that one - an
is_valid_x_card() detector and an x_parser_parse() that prints:
parsers/parsehid.c MAD aid 0x484d, PACS sector, Wiegand decode
parsers/parsevigik.c MAD aid 0x4910/0x4916, sector assembly
parsevigik.c also takes vigik_get_service(), vigik_verify() and
vigik_annotate() out of mifare/mifarehost.c, 306 lines that were VIGIK only
with a single caller.
mf_view_dump() is now two detector calls, so hf mf view -f and hf mf dump --ns
both decode a HID credential off a live card for the first time, and adding a
scheme is a new file plus two lines. hf mf mad -f keeps its HID decode through
the same parser.
The sector copy in the VIGIK path gains a bounds check; a MAD entry pointing
past the end of a short dump used to read past the buffer.
All three source lists get the new files: client/Makefile,
client/CMakeLists.txt and client/experimental_lib/CMakeLists.txt. The library
one matters because vigik_annotate() moved; without it anything linking
libpm3rrg_rdv4 loses the symbol.
hf mf mad against a card still cannot decode PACS. It authenticates with the
MAD key alone and never reads the application sector, so it has no credential
bytes to work with - unchanged here.
Co-Authored-By: Claude Opus 5 (1M context)
zlib_decompress() walks its output in whole FPGA_INTERLEAVE_SIZE chunks:
for (long k = 0; k < *outsize / (FPGA_INTERLEAVE_SIZE * num_outfiles); k++)
so a stream that is not a whole number of chunks loses its trailing partial one.
With two or more inputs the read loop zero-pads each stream past EOF and the
total lands on a boundary, but the padding was guarded by 'num_infiles > 1', so
the single input case was left ragged. 42172 bytes of fpga_pm3_hf.bit is 146.43
chunks, and -d handed back 39788 - a clean looking prefix, short by 2384 bytes,
22 of them real bitstream data.
Gate the padding on single_block instead. It must not be 'always pad': -s is the
.data section, and start.c's uncompress_data_section() sizes the decompression
with __data_end__ - __data_start__. Rounding .data from 14944 up to 14976 makes
LZ4_decompress_safe() return an error, and that path is the LED panic loop, so
the firmware would never reach AppMain().
1 bitstream 42172 in -> 42336 packed, -d round trip byte identical,
archive 28730 -> 28731
4 bitstreams archive byte identical to 43fe6c3eb, round trip exact
-s .data byte identical to 43fe6c3eb on the same input, unpadded
The 164 padding bytes never reach the FPGA: DownloadFPGA() shifts out only
bitstream_length bytes, taken from the .bit 'e' section header.
Also simulated the ARM decoder over the new archive - LZ4_decompress_safe_continue()
block by block into a FPGA_RING_BUFFER_BYTES buffer - 3 blocks of 16384/16384/9568,
none over the ring buffer.
Co-Authored-By: Claude Opus 5 (1M context)
'hf mf view -f' decoded VIGIK PACS and could extract keys with '--sk'. 'hf mf dump
--ns', which reads the same 1K off the card, printed only the blocks and the
verbose key/ACL tables. Same bytes, less analysis, purely because of where they
came from so getting a PACS decode off a live card meant dumping it to a file
and viewing that.
Move everything view does once the blocks are in hand into mf_view_dump() and
call it from both. 'hf mf dump --ns' and 'hf mf view -f' now print byte identical
output for the same card, and dump gains '--sk' to match. The old view leaked its
dump buffer on both VIGIK error returns; the shared version frees it in one place.
Drops a stale commented out convert_mfc_2_arr() call referencing a pdump
variable that no longer exists.
Rounds off #1942. mfc_read_tag() and '--ns' landed long ago, this was the piece
still missing.
hf mf eview, cview and the gen4 view share the same print block but omit
mf_analyse_acl() in verbose, so folding them in changes their output and is
left for a separate decision.
Co-Authored-By: Claude Opus 5 (1M context)
The 1 MB block branch exists for the ARM .data section: start.c's
uncompress_data_section() reads one 4-byte length and does one
LZ4_decompress_safe(), so .data has to arrive as a single block. It was
selected by 'num_infiles == 1', which is not what tells the two callers apart.
A build that skips LF, FeliCa and ISO15693 leaves FPGA_BITSTREAMS holding just
fpga_pm3_hf.bit, so the bitstream took that same branch and was packed as one
42 kB block. get_from_fpga_combined_stream() decompresses into a
FPGA_RING_BUFFER_BYTES buffer, 16 kB since 83c3f81b1:
[#] inflate returned: -13247
[#] reset_fpga_stream failed
Before 83c3f81b1 the copy was clamped with MIN(FPGA_RING_BUFFER_BYTES, ...)
whatever buffer_size said, so the blocks came out at 30 kB and the 30 kB ring
buffer still took them. That is why the commit looks like the cause - it only
removed the clamp that was covering for the wrong branch.
Add -s for the single block case and let the FPGA path always chop at
FPGA_RING_BUFFER_BYTES, however many bitstreams went in:
4 bitstreams 169344 in -> 106933 out, byte identical to before
1 bitstream 42172 in -> 28718 out, 3 blocks 13265/13206/2247,
was 1 block of 27627
.data (-s) 14944 in -> 8786 out, byte identical to the
obj/fullimage.data.bin.z in tree
Also hand the ring buffer back when reset_fpga_stream() fails. The early
return left it allocated for the rest of the session, which is the reporter's
[#] BigBuf_size............. 48116
[#] Available memory........ 31732
48116 - 31732 is 16384, exactly FPGA_RING_BUFFER_BYTES.
No CAPABILITIES_VERSION bump: fpga_all.bit.z is objcopy'd into the same
fullimage as the decompressor that reads it, so nothing here is client facing.
Reported and correctly diagnosed by @ewangsoft.
Fixes#3599
Co-Authored-By: Claude Opus 5 (1M context)
The six plain/mac assertion pairs differed only by -m, and the file they ran
against was created with no --amode and no --rawrights - so plain mode, free
access. Free access is served in plain whatever the file says, and the client
derives the mode from the file settings rather than from -m, so both halves of
every pair sent the same bytes:
--op credit -m mac -> 90 0C 00 00 05 02 0A 00 00 00 00
--op credit -m plain -> 90 0C 00 00 05 02 0A 00 00 00 00
They passed on a client that could not do MAC mode at all, which is how
e1598cd62 shipped: it had removed CREDIT/DEBIT/LIMITED_CREDIT from
EV1D40TransmitMAC, and this suite stayed green.
Build a fixture that makes the client answer a different question per file
instead, and drop the -m flags, since deriving the mode is the thing under
test:
data 00 mac EEEE free access, MACed file
data 01 mac 0000 key protected
data 02 encrypt EEEE free access, enciphered file
data 03 encrypt 0000 key protected
value 10 mac 00E0 credit plain, debit MAC, same file
value 11 mac 0000 key protected
value 12 plain EEEE the original case
value 13 encrypt 0000 plus FreeValue, so GetValue is plain
File 10 is the one worth having: credit is granted by read & write only, which
is free there, while debit is also granted by the write right, which is key 0.
A single communication mode for the whole file cannot satisfy both.
Also dump the application. It has no ISO file ids, so the client's
GetISOFileIDs probe is refused and the PICC ends the session on it; a dump
that does not notice reads the first file's plain content as a response CMAC
and reports it as no data.
Checked against a client built at 08e389c0b, before the three fixes: the free
access data writes fail -20, the MACed value credit fails -20, and the dump
loses file 00. The 00E0 and FreeValue cases pass there too - they guard the
derivation against future regressions rather than reproducing an old bug.
Co-Authored-By: Claude Opus 5 (1M context)
A card runs the protocol its TD1 names until a PPS changes it. --t1 only
picked the module's T=1 send opcode, so on a card whose ATR offers T=0 first
the APDU went out as T=1 blocks to a card still speaking T=0 and got no
answer at all:
smart raw --t1 -s -d 00a4040007a000000004101000
[!] smart card response failed
'smart pps --t1' in the same client session made it work, which is what the
help for 'smart pps' already promised was unnecessary:
Note 'smart raw --t1' already switches a card to T=1 by itself when
the ATR offers it; this is for negotiating Fi/Di explicitly.
Do it for real. SmartCardRaw() now runs the PPS when T=1 is asked for and
nothing has selected it yet, taking the ATR it needs first because PPS is
only legal in that window. It fires once per activation: a second --t1 apdu
sees the protocol already in force and sends straight away. A card that does
not offer T=1 is left alone and the apdu still goes out, as before.
Also fix the flag names in the docs and in the error path. 'smart raw's
first example and both 'Choose either' messages said -0 / -1, which have
never existed. tools/pm3_online_tests.sh had copied the example, so its T=0
checks failed with 'invalid option' on every run; its T=1 checks needed no
change beyond dropping the now unnecessary reset.
Co-Authored-By: Claude Opus 5 (1M context)
DesfireFillFileList() ends with GetISOFileIDs (0x61). An application created
without ISO file ids answers 0x91F0, and the PICC ends the authentication on a
command error. The client never noticed: dctx->secureChannel still said ev1, so
every later command was framed as MACed against a dead session.
For hf mfdes dump that meant the first file was read as if its response carried
a CMAC. An 8 byte plain free access file came back as exactly 8 bytes of data,
which were consumed as the MAC, so the file content was thrown away and reported
as
Received MAC is not match with calculated
received MAC: A0 A1 A2 A3 A4 A5 A6 A7
Read operation returned no data from file 0
The next key protected file then failed with 0x91AE, and only that failure
triggered the loop's blind re-authentication, after which the rest of the dump
was correct. Dumping an application that does have ISO file ids was never
affected, because 0x61 succeeds there.
Drop our side of the session when the probe fails so the context tells the
truth, and re-authenticate in CmdHF14ADesDump before the read loop. The two
warnings the probe printed are demoted to DEBUG: an application without ISO
file ids is the normal case, not something to warn about.
Key settings 2 bit 0x20 is not usable to predict this. On a DESFire EV2 both an
application with working ISO file ids and one without report key settings 0F 83,
so the bit reads back as 0 either way.
Co-Authored-By: Claude Opus 5 (1M context)
The PICC applies a file's communication mode only when access is granted by
a key right matching the authenticated key. When the operation is granted by
the free access right (0x0E) instead, it runs in plain, whatever the file
settings say. The client used the file comm mode unconditionally, so any file
created with the default EEEE rights failed with 0x917E on write, and a free
access Full file was printed as its data plus eight unstripped CMAC bytes
instead of being decrypted. Fixes#3393.
Which rights can grant an operation varies, and the rule above is evaluated
over that set. Measured on DESFire EV2, ev1 and ev2 secure channels:
read / write data w (or r), rw
GetValue 0x6C r, w, rw
Credit 0x0C rw only
Debit 0xDC r, w, rw
LimCredit 0x1C r, w, rw
Credit is the odd one out: a file with r=key0 w=key0 rw=free needs Credit in
plain but Debit in MAC, in the same session. The FreeValue option bit forces
GetValue to plain regardless of the rights.
hf mfdes value never read the file settings at all, which is #2712. e1598cd62
worked around that by dropping CREDIT/DEBIT/LIMITED_CREDIT from
EV1D40TransmitMAC and retrying in plain on a length error. That made MACed
value files impossible to credit by any route, and the retry resent a
byte-identical APDU after the failure had already desynced the CMAC chain,
turning a clear 0x7E into a misleading 0x91AE. Both are reverted and the
command now reads the file settings like read and write do. Fixes#2712.
hf mfdes write resolves the comm mode even when --type is given explicitly,
since that path skipped detection entirely.
The DACLRP branch in the read path is left alone: no LRP capable card was
available to test against.
Co-Authored-By: Claude Opus 5 (1M context)
Three ways this command reported a credential that was not on the tag.
CmdIdteckDemod always passed its local raw[8] to demodIdteck, never NULL, so
without --raw the command decoded a zeroed stack array rather than the
graphbuffer and reported card id 0 every time. The help's own first example,
plain `lf idteck demod`, has been doing that since --raw was added. It now
passes NULL when no --raw is given, which is the signal path demodIdteck
already has and lf idteck reader already uses.
A raw frame whose first word is not 4944544B printed "No genuine IDTECK found"
and then fell through and announced a tag anyway, with a card id read out of
whatever was passed in. It now stops there. The signal path cannot reach this:
detectIdteck matches the full 32 bit preamble, so lf search and lf idteck
reader are unaffected.
Finally the Idteck card id was packed into a 26 bit wiegand_message_t and run
through HIDUnpack, which prints an HID H10301 line with a facility code and
card number. That is not a decode of anything - the id is 24 bits, byte
reversed off the wire, and Unpack_H10301 returns true for any 26 bit message,
so the parity flag is the only hint and it reads ok for 25% of card ids by
chance. Both committed Idteck traces show it: 4944544B351FBE4B prints
FC: 37 CN: 57103 parity ( ok ), AC40E069 prints FC: 52 CN: 61472 parity
( fail ). Dropped, with the wiegand_formats.h include that came in with it.
Added five offline regression tests. Three fail without this change, one per
defect; lf search over every committed lf trace is byte identical before and
after apart from the two removed H10301 lines.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
`trace save` saved the client side trace buffer whenever it was non-empty
and only downloaded from device when it was empty. After `trace load` or
`trace list -1` a following sniff -> `trace save` silently wrote the old
trace, byte identical to the previous save, with no way to reset it.
See #3592, and #1252 / #1512 for earlier reports of the same thing.
- `trace save` now downloads from device by default and takes `-1` to save
the client side buffer, mirroring `trace list`. Offline it falls back to
the buffer so `trace load` -> `trace save` still works.
- split download_trace() into download_trace_ex(), which hands the caller
its own buffer. `trace save` uses it and no longer mutates gs_trace, so
`-1` means the client buffer regardless of what ran before.
- download_trace() freed gs_trace before it knew the download had worked,
so a timeout threw away a loaded trace. It now swaps on success only.
- added `trace clear` to discard the client side buffer, and a shared
ClearTraceBuffer() to replace the free/NULL/zero pattern that was
open coded in ImportTraceBuffer() and CmdTraceLoad().
Help text for both new commands names the device vs client distinction.
Co-Authored-By: Claude Opus 5 (1M context)
Every answer was modulated after the reader's frame arrived, landing
~1812 carrier periods late against the 1172 the FDT allows, so readers
timed out before any of it mattered. All answers are now precomputed the
way hf 14a sim does it, and a phone answers at 1172 exactly.
Cascade mode sent a cascade tag at every level, which a conforming reader
rejects in the last level its ATQA announced - it dropped the card before
ever sending a SELECT. The cascade tag now appears only below that level;
it is the SAK that lies about the UID being incomplete, and that is what
walks a reader up to cascade level 7.
A bit oriented ANTICOLLISION was answered with the whole UID instead of
the bits the reader still lacked, handing it a frame of the wrong length.
One encoder now builds any tail, with or without collisions in it.
--coll leaves the first UID byte clean and collides every bit after it, so
a reader resolves 24 bits one round trip at a time, is then given a BCC
that checks out, and is cascaded into the same again - 183 answers per
poll against the 3 a real card needs. Colliding byte 0 as well only
produced a UID of all ones, which readers drop before asking for the BCC.
Reader frames that go unanswered are traced instead of silently dropped,
LED B marks an attempt in progress and LED C flips on each step deeper,
and the closing line reports rounds run and how far a reader got.
trace list -t 14a decodes SEL 0x99..0x9F, shows how many UID bits a bit
oriented ANTICOLL claims, and no longer flags those CRC-less frames as
bad CRC.
Co-Authored-By: Claude Opus 5 (1M context)
FpgaDownloadAndGoEx() with keep_em false does BigBuf_free() plus
BigBuf_Clear_ext(): the emulator memory pointer is nulled and all of BigBuf is
zeroed. iso14443a_setup() calls that variant, and Mifare1ksim(),
SimulateIso14443aTagEx() and SimulateIso14443aTagAID() build their precompiled
anticollision responses in BigBuf first. CMD_HF_MIFARE_EML_MEMGET had it the
other way round - it downloaded, then read the memory it had just wiped, so
'hf mf eview' and 'hf mf esave' returned their own zeros after any lf hitag,
hf iclass or hf 15 command. A download already cached early-returns, so which
image the FPGA held decided whether any of this happened.
All five now call FpgaDownloadAndGo_keep_EM() before any BigBuf allocation.
Free-BigBuf floor at download time goes 16384 -> 20480 (ring plus the 4096 byte
emulator block); BigBuf measures 29084..31420 across all standalone configs on
RDV4 and 40120 on a PM3 Easy.
The sim paths also clear the trace before taking their modulation buffer -
BigBuf_malloc() refuses memory a stale trace holds, and MifareSimInit() ignored
the NULL, leaving prepare_tag_modulation() to memcpy 571 bytes over the vector
table at address 0.
'hf mf eload' now zeroes emulator memory device side: CMD_HF_MIFARE_EML_MEMSET
takes a flags byte, set on the first chunk only, so 'hf mf esetblk' and every
other partial write still touch only their own blocks. That byte is why
CAPABILITIES_VERSION goes 9 -> 10; mismatched client and firmware refuse to
connect rather than write everything one byte offset.
Reported in #2836, whose USB drop is separately addressed by bc289cf43.
Builds clean for PM3RDV4, PM5 and the client; astyle clean. Not yet verified on
hardware.
Co-Authored-By: Claude Opus 5 (1M context)