Archive for the ‘Reverse Engineer Microcontroller’ Category

PostHeaderIcon Reverse Engineering Chip LPC2114FBD64 Code: Reading It After You Have It

Recovering the bytes is the part everybody quotes for. Reading them is the part that produces the deliverable — a description of what the firmware does, which registers it touches, what protocol it speaks, and where the values that matter are stored.

On this device the reading has a specific character, because three properties of the platform shape what the compiler produced: a wide flash interface with an accelerator in front of it, a core that mixes two instruction sets, and an addressing model that puts constants inline in the code stream.

The accelerator explains the code layout

The flash array is read 128 bits at a time, and a memory accelerator module sits between the array and the core. Its job is to prefetch sequential fetches so that the core, which wants one instruction at a time, does not stall.

The accelerator is configured at start-up through two registers: one that selects the mode and one that sets the number of clocks the array needs. The values written there are the first thing to look for in a recovered image, because they tell you the clock rate the firmware expects. A build configured for a slow clock with generous wait states indicates a product that never ran near the maximum, which in turn suggests a design constrained by something else — power, an older board revision, or a safety margin somebody insisted on.

The layout consequence is more subtle. Code runs best when it is contiguous, and firmware that cares about timing places its inner loops in SRAM rather than in flash. When a disassembly shows a block of instructions that also exists as data earlier in the file, the data copy is the load image and the SRAM block is the execution copy. Recognising that duplication prevents the common mistake of treating the file as if it were the running program.

Two instruction sets in one stream

The core executes ARM instructions, which are four bytes wide, and Thumb instructions, which are two. Compilers mix them freely: an interrupt-heavy product typically keeps handlers in Thumb to reduce code size and puts arithmetic routines in ARM to use the barrel shifter and conditional execution.

The mixing is signalled by the low bit of a branch target address. A branch to an even address stays in the current instruction set; a branch to an odd address switches. Disassemblers handle this correctly when the symbols are present and get it wrong constantly when they are not, producing output that looks like a plausible but nonsensical instruction sequence.

The practical rule when reading a stripped image: follow the branches, not the linear sweep. Start at the reset vector, follow what it calls, and let the interworking bits tell you which decoder to use at each destination. A linear sweep from the base of the array will desynchronise within a few hundred bytes and take hours to recover from.

Literal pools are the giveaway for constants

Because ARM instructions are fixed width, a constant cannot be embedded in the instruction that uses it. The compiler places constants in a pool after the function that needs them and loads them with a program-counter-relative access.

In a recovered image these pools look like data in the middle of code, and they are the fastest way to find what the firmware is doing with hardware. A pool containing peripheral base addresses identifies every peripheral the product uses. A pool containing odd-looking values such as 0x0000A5A5 or 0x00000055 identifies a register written with a key sequence — and on this family several peripherals require exactly that.

What the pool holds What it tells you
peripheral block addresses which peripherals the product actually initialises
small magic values written twice a protected register that needs a key sequence
float or fixed-point constants control loop coefficients, filter tuning
table base addresses lookup tables for linearisation or calibration
the same constant in many functions a configuration value compiled in, not read from memory

That last row is worth attention. A constant repeated across unrelated functions is a design decision made at build time — a gain, a baud rate, a timeout. It is frequently the answer to a question the customer cannot answer from documentation, because the documentation describes the product and the constant describes the build.

Reading order that works

Start with the vector table and the reset path: what is initialised, in what order, and which clock configuration is set before anything else. Then the interrupt dispatcher, which reveals how many sources are handled and how work is organised. Then the functions the dispatcher calls, which are the product’s real behaviour. Then the data regions, which hold the configuration and the calibration.

Reading in this order produces a document that can be checked against the board. Reading in address order produces a pile of listings that nobody can verify.

Where the value lies

Customers usually ask for the source. What they need is almost never the source; it is the knowledge required to maintain, replicate, or repair the product. That knowledge is: the clock tree, the pin assignment, the protocol on each port, the calibration values and where they live, and the error handling.

Every one of those is recoverable from a dump read in the order above, and none of them requires the original variable names.

Neighbouring cases

The same reading discipline applies up and down the family. The differences are in what the device offers rather than in how the code looks — LPC2134FBD64 firmware work shows how the interrupt controller’s vector slots make the same analysis faster, and LPC2103FBD48 heximal delivery shows what has to be true before the image will boot at all. For a Cortex-M part where the same constants question arises with different instruction encodings, STM32F103CB recovery is a useful comparison.

A note on stripping

Compilers leave fingerprints: prologue patterns, switch tables, library calls that appear as recognisable stubs. Those fingerprints are how an unknown image gets attributed to a toolchain and, sometimes, to a vendor’s SDK. That attribution is worth recording in the report, because it tells the customer whether the code they are looking at was written in-house or licensed, which is often the first question their legal team asks.

PostHeaderIcon Reverse Engineering NXP Chip LPC2106FBD48 Flash by Live Capture

There are two ways to obtain firmware from a device. The first is to read the memory and reconstruct the program from what is stored. The second is to let the device run and take what it is using while it runs. On an unprotected part both work, and they produce the same answer, which is why the distinction is easy to ignore.

On a part that resists the first approach, the second is often the only one that produces anything at all. It also happens to be the more informative of the two, because a running device exposes the relationship between code and state that a static file only implies.

What the debug unit actually provides

The ARM7TDMI-S core in this family carries an embedded in-circuit emulator — a small block of logic, separate from the CPU, that can stop the core, examine registers, and read or write memory over the JTAG scan chain. It also carries two watchpoint comparators and a handful of breakpoint comparators, plus a vector catch facility that halts the core when an exception is taken.

The practical consequences are worth spelling out:

  • The core can be halted at an arbitrary instruction address and its complete register state read out, including the program counter, the mode, and the banked registers for each exception mode.
  • Memory can be read and written while halted, without the application’s cooperation and without going through any driver.
  • A watchpoint can stop the core when a chosen address is accessed, which turns an unknown routine into a located one.
  • Vector catch stops the core at the first instruction of an exception handler, which is the cleanest way to find code that only runs on an error path.

None of this needs the flash to be readable through the loader. The debug path reaches memory through the core’s own bus, which is a different door from the one the boot loader guards.

Property Cold dump of the array Live capture at a halt
what you get bytes as stored code as it runs, plus registers and RAM
relocated routines stub left behind the copy in SRAM
compressed images packed data expanded working set
requires the port to be open yes yes, but the debug path, not the loader
risk to the device none watchdog, low power, clock change
typical use protected but readable readable and deliberately obscured

Why that matters on this part

Firmware written for a 256 kilobyte array with 16 kilobytes of SRAM in a small package almost always does something at start-up that a static dump misrepresents.

The common pattern is relocation. A routine is copied from flash into SRAM and executed there, either because it programs flash — code cannot write the array it is running from — or because it needs to run faster than the memory accelerator allows. Once copied, some designs overwrite or deliberately corrupt the flash copy, and what remains in the array is a stub that will never run again.

The second pattern is decompression. A compressed image is expanded into SRAM at boot, and the flash holds only the compressor’s output. A dump of the array then yields data that looks like noise in a disassembler and contains no recognisable instruction stream.

The third pattern is a validity check with consequences. Firmware that finds an unexpected checksum, an unexpected debug attach, or an unexpected read of a protected region may clear its own working set or refuse to initialise. A cold dump taken after such a decision records the aftermath, not the program.

Live capture sidesteps all three, because it takes the image after the device has already done the work of making it usable.

The procedure that produces something

Reset the device with the debugger attached but not halting at the first instruction, and let it reach its idle loop. Then halt. At that point SRAM contains the relocated code, the initialised data, the stack, and the heap — the state the firmware considers normal.

Read SRAM in full, then read the array, then compare the two. Regions that appear in both are the copies. Regions that appear only in SRAM are the decompressed or generated content, and they are frequently the part that mattered.

For code that only exists briefly, use the watchpoint. Pick the address the routine will touch — a peripheral register, a table it must read, a buffer it must fill — and let the device run until the access happens. The core stops with the program counter inside the routine, and the surrounding memory holds whatever it had just produced. Repeat with different watchpoints to walk through the sequence.

The failure modes of halting

Stopping a running product is not free, and on an embedded target three things commonly go wrong.

The watchdog resets the device while the core is halted, because halting the CPU does not stop the watchdog counter. Either disable it before halting, or configure the debug unit to stop it too if the silicon supports that, or accept a short window and work in bursts.

A low-power mode kills the clock the debug logic needs. A device that enters a deep sleep state may become unreachable until it is woken by the peripheral that normally wakes it, and a watchpoint on that peripheral’s register is the way back in.

Adaptive clocking matters on a board with an unusual core clock. The debug unit can be configured to return a clock to the host that tracks the target, and without it a design running at an odd frequency will attach and then lose sync on the first speed change.

What the capture gives the customer

The output of a live capture is not just a binary. It is a binary plus a set of observations that explain it: where the code runs from, which regions are generated at start-up, which handlers exist, and what the device does when it decides something is wrong.

That last item is often the most valuable. Products that clear state on a suspicious event are common in metering and access control, and the only way to see the behaviour is to watch it happen rather than to read about it in a listing.

Where this sits among the other routes

When the protection word is open, the simplest job is a read through the boot loader, described in LPC2102FBD48 data recovery. When it is closed, the debug unit is gone as well, and the choice narrows to the invasive routes covered in LPC2104FBD48 erase behaviour. The same silicon in the other package brings its own access problems, covered in LPC2106FHN48 firmware work. The interesting middle ground — where the debug port answers but the array does not — is where live capture earns its keep, and the same core-level techniques transfer to neighbouring parts such as AT91SAM7S256, where the vendor’s protection policy differs but the ARM7 debug architecture is the same.

One practical note

Record the reset behaviour before halting anything. A single capture of what the device does on power-up, taken from the pins rather than from the debugger, is the baseline that tells you whether the state you later halt in is normal or already degraded. It costs two minutes and it prevents the most embarrassing class of wrong conclusion, which is a faithful dump of a device that had already given up.

PostHeaderIcon Reverse Engineering Microcontroller AVR ATxmega128A1 Heximal: 128 KB Is an Address Boundary

Most part numbers are chosen for marketing reasons and a few are chosen by arithmetic. The ATxmega128A1 belongs to the second group. AVR program memory is organised as sixteen-bit instruction words addressed in bytes, so 128 kilobytes is 65,536 words — and 65,536 is exactly the largest number a sixteen-bit register can hold. The part sits precisely at the point where the architecture stops needing help, and one size larger it starts.

That coincidence is the whole reason this device is pleasant to work on. It is also the reason images from it are so often wrong, because the same coincidence means that several different address conventions all produce numbers in a plausible range, and a mistake of a factor of two looks like a different but equally believable image.

The part in numbers

item ATxmega128A1
program memory 131072 bytes, 65536 words
SRAM 8 KB
EEPROM 2 KB, separate address space
I/O 78 pins in a 100-pin body
serial eight USARTs, four synchronous ports
analogue two 12-bit ADC sections, two DAC channels
timers eight 16-bit timer counters
extras AES and DES engine, DMA, event system
programming PDI, three pins
protection lock bits for flash, EEPROM and boot sections, inverted logic

Two rows carry the recovery consequence: the array size, and the fact that EEPROM is a separate address space reached by a different command. The rest of the list is what makes the part worth recovering — a design that used eight USARTs and an AES engine is a design that somebody would rather not rewrite.

Words, bytes and two different pointers

An AVR keeps two address conventions alive at the same time, and both are visible in a recovered image.

The program counter and the indirect jump mechanisms work in words. A register pair pointing at a subroutine holds a word address, and ICALL jumps to that word. The constant-data mechanism works in bytes: LPM treats the same register pair as a byte address. On a part with 64,000 words the two conventions differ by a factor of two across the entire map, and there is nothing in the image that says which one a given pointer holds.

The practical result is that an image can be complete and still produce a listing in which every computed jump goes to the wrong place. The disassembler has to track how the pointer was built: a value loaded as a literal and shifted left once is a word address, a value added to a base loaded from a table is usually a byte address.

The second convention matters more here than on smaller parts because of ELPM. Beyond sixty-four kilobytes of byte address, constant data needs the extension register, and a design that stores lookup tables near the top of the map will use it. Identifying those accesses is what tells you the table region is above 64 KB, which is exactly the region most likely to be truncated by a tool with a sixteen-bit address field.

Why the hex file grows extra records

A sixteen-bit address field in a hex record can express byte addresses up to 65,535. The ATxmega128A1 has 131,072 bytes. Half of the array therefore cannot be addressed by an ordinary record, and a well-formed file for this part must contain extended linear address records that set the upper bits before the data that needs them.

Three failure modes follow, and all three are common.

A tool that ignores the extension records writes the entire image into the lower half, producing a 128 KB file in which the second half is a duplicate of the first. This looks like a plausible program and fails on the first jump above 64 KB.

A tool that emits extension records but resets them at the wrong point produces a file whose records are individually valid and collectively scrambled. Loaders accept it. The image is only detectably wrong when it is compared against a second read.

A tool that truncates at 64 KB produces a file that is exactly half the size it should be. This is the easiest to catch, and the easiest to explain to a customer, which is why the delivered file should state its own expected length in the first line of the accompanying note.

Lock bits are inverted, and that has a consequence

AVR lock bits are active low: a programmed bit means unlocked. This is the opposite of almost every other vendor’s convention and it catches people reading a fuse map for the first time.

The consequence at the bench is that a fuse dump which looks “all clear” may be the locked state, and a dump which looks “all set” may be the factory state. The only safe reading is to decode against the datasheet’s stated sense rather than against intuition.

The second consequence is that a chip erase clears the lock bits along with the array and the EEPROM. On this family, as on the PIC flash parts, unprotecting and destroying are the same operation, and the difference between them is only whether the content mattered. So a locked part is die-level work, and an unlocked part is a two-minute read.

PDI, and what it exposes

The programming interface is three pins: reset, clock and data, speaking a packet protocol. It exposes the flash array, the EEPROM in its own address space, the fuse bytes, the lock bits, the calibration row and a device signature.

For recovery the signature is the first useful artefact. It names the device exactly, which resolves the question of which family member is on the board — a distinction that matters here because the A1, A3 and A4 members of the family share a package and a pinout and differ in memory and peripherals, and a firmware image read under the wrong profile will be the right bytes at the wrong addresses.

The calibration row is the second. It holds factory trim values for the internal oscillators, and a rebuild that ignores it will run at an untrimmed frequency in the same way as the PIC parts described elsewhere on this site — with the same class of consequence, but on a design that has an AES engine and therefore probably a communications protocol that cares.

For a smaller member of the same family where the boot section rather than the array size is the interesting part, ATxmega64A1 heximal breaking continues the thread. For the eight-bit megaAVR part with an external memory bus, ATmega162A heximal recovery covers the sibling architecture. And for a device where the address convention problem is a twelve-bit one, PIC16C57 heximal file extraction makes the same point at a smaller scale.

FAQ

Does a 128 KB part need extended records in its hex file? Yes. Any byte address above 65,535 requires them, and half this array is above that.

Can the EEPROM be read at the same time as the flash? It is read in the same session but from a different address space, and it should be delivered as a separate file. Merging the two produces a file that no programmer will accept and that no one can verify.

Why does the signature matter if the part number is printed on it? Because the printed number on a recovered board may be a variant, a remarked device, or a family member whose profile reads different addresses. The signature is the only authority.

The short version

128 KB is 65,536 words, which is exactly what a sixteen-bit pointer can hold, and that coincidence defines both the charm and the hazard of this part. Keep words and bytes apart, expect extended records in the file, decode lock bits against the datasheet’s inverted sense, and start with the signature so the rest of the read happens under the right profile. Everything above 64 KB is where a convention error hides, so verify there first.

PostHeaderIcon Reverse PIC16LF77 protected flash memory

A request to reverse PIC16LF77 protected flash memory begins with the fact that PIC16LF77 carries 8K words of 14-bit flash program memory and 368 bytes of data RAM and runs at 20 MHz in a 40-pin PDIP / 44-lead PLCC body. The work starts with the configuration word, because a mid-range PIC16 protects its program array with a single code-protect bit rather than a bank of lock bits.

Reverse Microchip MCU PIC16LF77 Flash memory and readout hex of microcontroller PIC16LF77, status of processor PIC16LF77 can be opened and unlocking MCU’s tamper resistance system

how to reverse PIC16LF77 protected flash memory without losing the array

This PIC16 family uses a 14-bit instruction word and a single configuration word mapped at address 0x2007, outside the user program space and reachable only in programming mode. The code-protection bit, named CP0 on the larger members of this group and CP on the smaller flash parts, is the whole of the read-out control: left unprogrammed it allows normal reads, and programmed it protects the entire program array at once. ID locations and the configuration word itself remain readable even when the array is protected, which is why the first bench step is a read of 0x2007.

the PIC16LF77 memory geometry and its protection cost

On the PIC16LF77 the program array holds 8K words of 14 bits, with 368 bytes of data RAM beside it and no data EEPROM on this member. There is no separate boot section and no separate data array to preserve, so the geometry question is simply how many words the programmer must return. Once code protection is enabled every program-memory location reads back as zeros and further programming of the array is disabled, while the ID locations and the configuration word still respond. The 40-pin PDIP / 44-lead PLCC body with 40 pins changes only the lead frame; the word count is fixed by the device number, not by the package suffix.

PIC16LF77 recovery geometry Value
Program memory 8K x 14-bit words of flash
Data EEPROM no data EEPROM on this member
Data RAM 368 bytes
Core and clock 14-bit PIC16 core at 20 MHz
Protection CP code-protect bit in the 0x2007 configuration word
Package 40-pin PDIP / 44-lead PLCC, 40 pins

reading the PIC16LF77 over the programming interface

In-circuit serial programming reaches the part over the clock and data pins with the programming voltage applied to the reset pin, and the same path reads the configuration word and the ID locations. What fails under an active code-protect bit is the array read: a verification pass returns zeros from every program-memory location while the part continues to execute its firmware normally. Disabling code protection is not a non-destructive unlock. The programming specification requires a chip erase command, which erases the program memory first and then the configuration memory, and in doing so clears the code-protect bit back to the unprotected state. The practical routes are therefore a clean read while CP is off, or an erase that the customer must approve in writing because it removes the program along with the protection.

when a reverse PIC16LF77 protected flash memory job needs an authorised erase

Read the configuration word at 0x2007 first and check the code-protect bit, because that single bit settles whether any firmware can be read at all. With protection off the array reads cleanly and the heximal can be assembled directly from the returned words. With protection on there is no partial read and no selective block to keep, so the only route to a blank device is the chip erase with its permanent cost. The PIC16LF77 is the 8K words of 14-bit program memory device in a 40-pin PDIP / 44-lead PLCC body, so the capacity marking and the package settle the array size before anything is priced. The low-voltage LF grade with the larger program array is the identifying trait here. What survives the protection: the configuration word, the ID locations, the device ID word at 0x2006 and the register contents the running firmware exposes.

identifying the PIC16LF77 against its siblings

When a board carries only a partial marking, the mid-range PIC16 flash family is the place to look, because its members share the 14-bit core, the 0x2007 configuration word and the same code-protect behaviour while differing in program words, RAM, pin count and peripherals such as the ADC and the capture compare module. Neighbouring members span 2K to 8K words of program memory in 18-pin to 40-pin bodies, all using the same 14-bit core and the same single code-protect bit, with no data EEPROM anywhere in this group. Reading the device ID word at 0x2006 against the package marking settles which member is on the board before any protection work begins.

The same read-first routine appears in attack chip dspic33fj256gp506a software, attack chip pic16c622a software, attack chip pic16c73a program and attack chip pic16f72 heximal, with attack chip pic18f66k90 software showing how the larger array changes the pricing.

the deliverable for a reverse PIC16LF77 protected flash memory request

For a board that arrived as a reverse PIC16LF77 protected flash memory request, the deliverable is a confirmed word count, a code-protect state and a priced route agreed in writing before any destructive step, and our engineers read the configuration word at 0x2007 first.

PostHeaderIcon Instruction-Fetch Decryption: Why Real Code Encryption Is Rare

A request to decrypt source code carries an assumption that is worth testing before any work is quoted: that the code is encrypted. On a microcontroller this is usually false, and the reason is architectural rather than commercial.

A microcontroller executes instructions directly from flash. There is no loader, no decompression step, no operating system to decrypt an image before running it. The fetch unit reads an address and receives an instruction word, and it does that millions of times per second. If the flash contents were encrypted, the decryption would have to happen inside the fetch path, on every access, at full speed.

That is a hardware feature. It exists, it is expensive, and most parts do not have it.

What it would take

Consider what fetching an encrypted instruction requires. The ciphertext is at an address. The plaintext depends on the ciphertext, the key, and the position — because otherwise identical instruction words would produce identical ciphertext, which leaks structure.

So the decryption needs a positional input, which means an address-dependent tweak, which means a block cipher mode with a tweak such as XTS, or a stream cipher seeded per address. Either one costs silicon area and power, and both add latency to the fetch path, which limits the maximum clock.

Requirement Consequence
Decrypt in the fetch path Dedicated hardware between flash and core
Address-dependent key stream Tweak or counter per fetch
No latency penalty Pipelined decryption, more area
Key held on die OTP or a factory-provisioned key

That is a substantial feature, and the parts that have it are the ones sold specifically as secure: secure elements, some automotive parts, and a few application processors with an encrypted external memory interface.

The four things people call encryption

In practice, a customer who reports that their code is encrypted is describing one of four quite different arrangements.

Read protection is the first and by far the most common. The array cannot be read, so from the customer’s point of view the code is inaccessible. There is no cipher involved and nothing to decrypt; the code is in plaintext behind a lock.

Application-level encryption is the second. The developer encrypted a data region — a key table, a configuration blob, a licence file — using a key that is embedded in the code. The code itself is plaintext, and the key is findable.

Arrangement What is encrypted Where the key is Is there anything to decrypt
Read protection Nothing None No
Application-level A data region In the code Yes, and the key is in the image
External bus encryption Everything on the bus On the SoC Yes, and the key is not readable
On-die fetch decryption The instruction stream On the die, protected Yes, and the key is not readable

Bus encryption is the third. The code sits in an external flash and travels over a bus in encrypted form, and the SoC decrypts it as it arrives. This is common on application processors with external memory and rare on microcontrollers with internal flash.

On-die fetch decryption is the fourth and the only one that is genuinely hard. The array holds ciphertext, the core receives plaintext, and the key never leaves the die.

The test that tells them apart

The distinction is not academic, because it determines whether a read yields anything.

The test is to read the array and look at what came out. Two measurements settle it.

Entropy is the first. Plaintext code has a characteristic histogram: certain byte values dominate because of instruction encoding, and the entropy is well below the maximum. Ciphertext has a flat histogram and entropy close to eight bits per byte. A region that is compressive is not ciphertext.

Measurement Plaintext code Ciphertext
Byte histogram Peaked Flat
Entropy per byte 5 to 7 bits 7.9 bits or more
Compressibility 40 to 60 percent Near zero
Disassembles to plausible flow Yes No

The fourth row is the decisive one and it is qualitative rather than numeric. Plaintext code disassembles into something with coherent control flow: functions that end in returns, branches that land on instruction boundaries, calls to addresses that contain prologues. Ciphertext disassembles into a mess that contains no coherent flow, no consistent prologues, and branches that land in the middle of instructions.

The test takes an hour and it converts an ambiguous request into a definite one. If the dump disassembles, there is nothing to decrypt and the job is an analysis. If it does not, the code is either encrypted or the dump is wrong — and a wrong dump is more common than encryption.

Why a wrong dump is the usual explanation

Before concluding that code is encrypted, three dump errors have to be excluded, because each produces high-entropy garbage that looks like ciphertext.

A one-byte shift produces a dump that is almost right and disassembles to nonsense. A wrong address width produces a dump of the wrong region. A read taken while the flash was busy produces a dump with corrupted passages.

Symptom Cause Check
Entropy high everywhere, no structure Shifted read Look for a vector table at offset 0
First part readable, rest not Address width Compare the dump size to the array size
Isolated corrupted passages Read during a write Re-read and compare
Correct at the start, garbage after a boundary Two regions, one encrypted Check for a length field

The fourth row is the case that is actually encrypted, and it is usually a data region rather than code: a firmware image that contains an encrypted blob, or an application that decrypts its own resources. That is arrangement two, and the key is in the image.

When there is genuinely nothing to decrypt

If the array holds ciphertext and the key is on the die in a protected area, then the read has succeeded and produced nothing. This is the case that ends projects, and it is worth describing precisely so that it is recognised.

The evidence is a dump with flat entropy, no structure, and a device that runs normally. The device running is the proof that decryption is happening: the core is executing code that the array does not contain in plaintext.

Observation Conclusion
Device runs, dump is high entropy Fetch-path decryption present
Device runs, dump is plaintext No encryption; read protection only
Device does not run, dump is garbage Read error, not encryption
Device runs, part of dump is plaintext Mixed: code with an encrypted data region

In the first case, the remaining routes are the key — which is on the die — or a side channel that observes the plaintext after decryption. Neither is a read. The fault-injection route described in glitch attacks as a search problem can sometimes make the device release plaintext through an interface that would normally refuse, and that is the only electrical approach that does not require the key.

What the customer usually needs instead

The request for decryption is almost always a request for something narrower, and identifying the narrower thing changes the job entirely.

If the goal is to understand how an algorithm works, the deliverable is a behavioural specification with the constants extracted, and the code does not need to be decryptable at all — it needs to be observable. That route is the one in extracting coefficient tables from a DSP, and it works on a device whose flash cannot be read.

If the goal is to modify a behaviour, the deliverable is a patch, which requires the code to be in plaintext in memory somewhere. On a device with fetch-path decryption, that somewhere is the instruction cache or the prefetch buffer, and reading it requires either a debug session the device does not offer or a physical probe.

Goal Needs plaintext Route
Understand an algorithm No Observation and modelling
Modify a behaviour Yes, at the point of patch Plaintext in cache or buffer
Reproduce a function No Behavioural characterisation
Recover a key Depends Key location analysis

The table is the reason the first conversation matters so much. Two customers with the same sentence — “we need the code decrypted” — need two different engagements, and one of them does not need decryption at all.

What the service does

The first deliverable here is a classification rather than a decryption: whether the array holds plaintext, ciphertext, or a mixture, with the evidence for the conclusion. It is produced in a day from the dump and it prevents the most common wasted engagement in this area, which is a decryption project on an image that was never encrypted.

Where the array is plaintext and the customer believed otherwise, the work becomes the analysis in MCU source code reverse engineering. Where a data region is encrypted with a key in the code, the key is found by the search described in cracking MCU firmware. Where the encryption is in the fetch path, the honest answer is that no decryption is possible from the dump, and the alternatives are physical or side-channel.

The distinction between read protection and encryption is worth restating because it appears in almost every first conversation: a part whose code cannot be read is not a part whose code is encrypted, and the difference is the whole difference between a job that can be done and one that cannot. The read protection side of that distinction is set out in three protection layers.

PostHeaderIcon Four Steps Toward Source, Three Points of No Return

“Can you get the source code back” is the question that starts most reverse engineering engagements and the one that has the least satisfactory answer. The honest answer is that a binary contains enough information to reconstruct something that compiles and behaves identically, and not enough to reconstruct what the developer wrote.

The difference is not a matter of effort. Three specific kinds of information are discarded by the compiler, and no amount of analysis recovers them. Knowing which three sets the expectation before the work starts.

Stage one: disassembly

The first stage turns bytes into instructions, and it is the only stage that is fully mechanical.

The output is a listing of instructions at addresses, with the control flow made explicit. On a modern architecture with a decompiler-friendly debug format this stage is minutes; without it, the main work is deciding where code begins, which is the subject of finding the code.

The artefact is complete in the sense that it loses nothing. Every byte of code is represented, and every instruction is shown as the processor sees it.

Stage Input Output Automation
Disassembly Binary Instruction listing Complete
Decompilation Listing plus flow C-like functions High, with errors
Structure recovery C-like functions Types, structs, globals Partial
Naming Structure plus behaviour Readable program Manual

Stage two: decompilation

The second stage groups instructions into functions and expresses them in a C-like form. It is where the tooling is best and where the results are most often mistaken for source.

A decompiler recovers the control flow reliably and the expressions approximately. It produces code that reads like C and does not compile, because the types are wrong, the variable scopes are invented, and the expressions contain casts that no developer wrote.

Decompiler output Reliable Why
Control flow Yes It is in the instructions
Arithmetic expressions Mostly Recoverable from the operations
Local variable count Approximate Register allocation decides
Types No Nothing in the binary records them
Structure layout Partially Offsets are evidence, not definition

The fourth row is the first point of no return. A thirty-two-bit value in a register is an integer, a pointer, a float, or four characters, and the instruction that loaded it does not say which. A decompiler guesses from how the value is used, and the guess is right perhaps three times in four.

Stage three: structure recovery

The third stage is where a human is required, and it is the stage that determines whether the output is useful.

Recovering structure means deciding what the global variables are, how they group into structures, what the function signatures are, and which functions belong to which module. The evidence is usage: a global that is always accessed at offsets 0, 4 and 12 from a base pointer is a structure with three fields at those offsets; a function whose first argument is always a pointer to such a structure has that structure as its first parameter.

Evidence Inference Confidence
Constant offsets from a base Field layout High, but padding unknown
Same base passed to several functions Shared structure High
Base allocated with a size Structure size Medium; size may be rounded
Field used as a pointer Pointer member High
Field compared against small values Enumeration or flags Medium

The second row of the table above hides the second point of no return. The offsets are known exactly, and the size of the structure is known approximately, but the order of fields and the padding between them are gone. Two structures with the same field types in different orders can produce the same offsets after padding, and the binary cannot distinguish them.

Stage four: naming

The fourth stage is entirely manual and entirely about the reader.

Naming means replacing sub_8004C10 with something a person can follow. It is done from behaviour: a function that writes to a UART data register is a transmit function; a function called from an interrupt vector that reads a timer is a tick handler; a function that compares a buffer against a constant is a check.

The output of this stage is the only artefact that a customer can actually use, and it is also the only one whose quality cannot be measured mechanically.

Naming source Example Reliability
Peripheral register access uart_send High
Vector table position systick_handler High
String constants used error_message_7 Medium
Call graph position main_loop Medium
Behaviour under test checksum_verify High, with effort

The three points of no return

The three losses are worth stating precisely, because they are the reason a quotation for “recovering source” should be a quotation for something narrower.

Types are the first. The binary records operations, not types. A signed and an unsigned comparison differ by one instruction and a decompiler can often tell them apart; an integer and a pointer of the same width are indistinguishable except by how they are used, and a pointer that is never dereferenced looks exactly like an integer.

Structure layout is the second. Offsets survive, order and padding do not. A structure whose fields were declared in a different order but padded to the same total size produces identical access patterns.

Inlining is the third and the most consequential for readability. A function that was inlined by the compiler does not exist as a callable entity in the binary, so the recovered program has no such function. Conversely, a piece of code that the compiler duplicated into several call sites appears as several separate functions, and the decompiler will present them as such.

Lost What survives Consequence
Type identity Operations and widths Casts everywhere in the recovered code
Field order and padding Offsets and total size Structures that work but look wrong
Inlining decisions The resulting instructions Function boundaries that never existed
Macro expansion The expanded code Repetition that was written once
Optimisation choices The chosen form Expressions no developer would write

The fourth and fifth rows are not among the three points of no return because they are recoverable in principle — a macro is a repeated pattern and an optimisation is a choice — but in practice they are not worth recovering, and the result reads as code that was generated rather than written.

What to ask for instead

The productive reframing is to replace “recover the source” with a question about purpose.

If the purpose is to understand how a specific behaviour is implemented, the deliverable is a documented function, not a program. That requires stages one to three for one function and produces something far more useful than a whole decompiled image.

If the purpose is to modify the behaviour, the deliverable is a patched binary and the analysis needed to place the patch, which is the work described in patching IC code.

If the purpose is to rebuild a maintainable product, the deliverable is a specification and a new implementation, because a recovered program is correct and unmaintainable in equal measure.

Purpose Deliverable Stage reached
Understand one behaviour Documented function Three, for one function
Modify one behaviour Patched image One, plus a patch
Rebuild the product Specification plus new code Three, as input to a rewrite
Prove equivalence Test suite plus model One and two

Where the service fits

We quote by stage, not by image. A stage-one deliverable is a listing with the flow resolved. A stage-two deliverable adds decompiled functions with the tool’s output reviewed rather than trusted. A stage-three deliverable adds structures, signatures and a region map with uncertainty marked. Stage four is quoted by function, because it is manual and its cost is proportional to how much of the program matters.

What we will not do is describe stage two as recovered source. A decompiled image compiles only after a week of type corrections, and a customer who expects that week to be included in a stage-two quotation will be disappointed.

The function-level work that makes stage three possible is described in MCU break, and the reason a read image is sometimes encrypted at rest — which defeats all four stages at once — is in decrypting IC flash.

PostHeaderIcon PIC16F77 Flash: Watching the Bus Instead of Reading the Array

Not every question about a microcontroller is a question about its bits. The PIC16F77 is a forty-pin part with eight thousand words of flash and one feature its smaller relatives lack: a port that can be configured as a parallel slave, so the device can sit on an eight-bit bus as a peripheral rather than being the only processor in the design. Where a product uses that, there is a second way to learn what the firmware does.

Reverse Microchip MCU PIC16F77 Flash memory and locate the fuse bit of microcontroller, and extract code from MCU PIC16F777

Why the pins change the question

A design that puts this part on a host bus has already solved the observability problem for you. Address lines, data lines and strobes are physical signals on the board, at logic levels, in a protocol that the host drives. Clipping a logic analyser to them records the conversation between the two processors, and that conversation is the interface specification of the firmware in the only form that matters: what it accepts, what it returns, and in what order.

What the slave port exposes

The port presents an eight-bit data register with control lines for read, write and chip select, and the device’s program sees each transaction as a byte arriving or leaving. From outside, that means every value the host sends is visible, and every value the device returns is visible, along with the timing. What is not visible is the code that produced the response, or anything the device does when the host is not talking to it.

What the host already knows

The other processor in the product is usually documented, and its side of the protocol may exist as a data sheet with register names. That turns a capture into a decode: the host writes a command byte, then a parameter, then reads a status byte, and each of those fields has a name on the host side. Starting from the host’s documentation and confirming it with the bus is far faster than reverse engineering the protocol from timing alone, and it produces a specification that can be handed to whoever writes the replacement.

Timing that identifies the build

Strobe timing carries information that the values do not. The number of instruction cycles between a request and a response reflects the code path taken, so two units with different firmware revisions show different latencies for the same command. On a product with several field updates, that difference is how a capture can be attributed to a specific build, which matters when the customer needs to know which version the recovered behaviour corresponds to.

Observation is not extraction

Question Array read answers Bus capture answers
What exact instructions run Yes No
What the device accepts Partially Yes
What it returns and when Partially Yes
How it behaves when idle No Only if the bus is quiet

The first row is the one to be honest about. A capture is a specification of behaviour, not an image of code, and a second unit built to a specification will match on the paths that were exercised and diverge everywhere else. That is the same gap that separates a bit copy from a behavioural rebuild in copying a microcontroller, and it is wider than it looks from the outside.

What a capture does prove

It proves the protocol, the timing and the values, which is often enough to write a replacement that satisfies the host. It also proves which byte positions are meaningful, which is useful when the EEPROM image has to be decoded and the field layout is unknown. And it produces a test vector set: replay the capture against the replacement and the divergence is visible immediately, which is the only kind of acceptance test that means anything.

When this is the right tool

When the device still runs, when the product has a host bus, and when the customer needs a compatible replacement rather than the original source. It is also the right tool when the array is protected and the die-level route is refused on cost, because it produces something usable for a fraction of the price of an extraction, as long as the scope is stated honestly at the start.

The limit worth saying out loud

A capture cannot recover the firmware, and no amount of analysis turns it into one. If the customer’s real need is to modify the code, or to manufacture identical units, the bus is the wrong instrument and the answer is the array. The distinction between the two is what separates a working replacement from a copy, and it is the same distinction that makes PIC16F76 a code-reading problem rather than a bus problem. Where the data rather than the program is the target, PIC16F74 data sets out the two locks involved.

PostHeaderIcon PIC16F76: The 8K-Word Page Boundary That Breaks Naive Disassembly

The PIC16F76 is the 28-pin, 8K-word member of Microchip’s mid-range Flash family: 8192 × 14 bits of program memory, 368 bytes of RAM, 256 bytes of data EEPROM, five 10-bit ADC channels, two CCP modules and 22 I/O pins. It is the larger sibling of the PIC16F73 and PIC16F74, and it exists because 4K words was not enough for designs that needed a serial stack plus an ADC front end plus a control loop.

The 8K figure is where the interesting engineering is. It is exactly twice the 4K that the mid-range core was originally laid out for, and the extra bit of address does not fit in the instruction.

What the PIC16F76 actually contains

Item PIC16F76
Core 14-bit instruction word, 35 instructions
Program memory 8192 × 14-bit Flash (14 KB)
Data RAM 368 bytes (4 banks)
Data EEPROM 256 bytes
Hardware stack 8 levels
I/O pins 22 (PORTA 5, PORTB 8, PORTC 8, plus RE bits)
A/D converter 5 channels, 10-bit
PWM CCP1 and CCP2, up to 2 outputs
Serial USART, SSP (SPI/I²C)
Timers Timer0, Timer1 (16-bit), Timer2
Packages 28-pin PDIP, SOIC, SSOP
Programming ICSP, high voltage on MCLR

Four RAM banks of 96 bytes each, minus the mapped SFRs at the top of each bank, is what 368 bytes looks like in practice. The bank select bits RP1:RP0 in STATUS are set and cleared around almost every register access, and that pattern is one of the clearest fingerprints in a recovered listing.

CALL and GOTO carry 11 bits

On the mid-range core, CALL and GOTO encode an 11-bit destination. That addresses 2048 words. The PIC16F76 has 8192.

The remaining two bits come from PCLATH<4:3>, which the firmware has to load before the jump and which the jump itself does not change. The hardware behaviour is specific and worth stating precisely: a GOTO or CALL loads PCLATH<4:3> into PCL<12:11> for the duration of the jump, and then PCL<12:11> reverts to whatever PCLATH<4:3> held before the instruction completed. In other words the page bits apply to the destination only, not to the return, and not to subsequent instruction fetches.

Two consequences follow for anyone reading a recovered image.

First, a linear disassembly from address 0000h that ignores PCLATH will mislabel every cross-page destination. The 11-bit field is correct; the missing two bits are in a register write that may be several instructions earlier. Every call graph built without tracking PCLATH<4:3> on this part is wrong above 7FFh.

Second, the reverse is also true: because PCLATH<4:3> is set by ordinary MOVLW/MOVWF sequences, a static analyser can recover the page bits reliably. They are not hidden in a computed jump — they are in the instruction stream, just not in the instruction. This is why the 16F76 recovers more cleanly than chips where jump targets are computed at runtime.

The computed jump, which is the real problem

The one place the page bits are not statically visible is the RETLW table idiom, and the PIC16F76 uses it heavily because 256 bytes of data EEPROM is not much room for a segmented sensor linearisation.

The idiom is: compute an offset, add it to PCL, and let the program counter walk into a run of RETLW instructions. On an 8K device the addition can carry out of the low byte into PCLATH, and the firmware must handle that carry explicitly. Get it wrong and the routine jumps into the wrong page; get it right and the table is a sequence of literal values sitting in the listing.

For recovery this is good news. A RETLW table is data with no obfuscation — the values appear as they were written. The difficulty is knowing where the table ends, since RETLW is also a legitimate way to return a constant from an ordinary routine.

The configuration word at 2007h

Bit Field Meaning
13:7 — Unimplemented, read as 1
6 CP Program memory protection; 1 = disabled, 0 = enabled
5 CPD Data EEPROM protection; 1 = disabled, 0 = enabled
4 BOREN Brown-out reset; 1 = enabled
3 PWRTEN Power-up timer; 1 = disabled, 0 = enabled
2 WDTEN Watchdog; 1 = enabled
1:0 FOSC1:FOSC0 11 RC, 10 HS, 01 XT, 00 LP

Two things are absent that appear on the following generation. There is no LVP bit — this family is programmed by applying high voltage to MCLR, and there is no single-supply path to consider. There is also no partial protection: CP covers all 8192 words as one unit, with no equivalent of the CP1:CP0 field that the PIC16F87X parts use to protect the upper half separately.

The four-value oscillator field is the other generational marker. Where the 16F87X offers eight oscillator modes including two internal RC configurations, the 16F7X offers four, and all four require external components or an external clock. On a recovered image, that means the clock frequency is determined by the board, not by the configuration word — a simpler situation than on parts where INTOSC is an option, but one that makes the board itself part of the record.

Protection, and the clause that decides it

CP = 0 blocks external reads over ICSP. It does not alter execution. Microchip’s programming specification for the Flash mid-range parts attaches the standard note to the CP bit:

The entire program memory will be erased when code protection is turned off.

So clearing CP performs a bulk erase, and a subsequent read returns erased words. The same note applies to CPD and the 256-byte data EEPROM: turning data protection off erases the array. Both barriers are of the same kind, and neither can be opened without destroying what is behind it.

What a complete image contains

  • 0000h–1FFFh — 8192 × 14-bit program Flash, spanning four code pages
  • 2000h–2003h — four user ID locations
  • 2006h — device ID
  • 2007h — the configuration word
  • 256 bytes of data EEPROM in a separate address space

The user ID locations are worth noting on this family. They are four 14-bit words that the programmer can write but the firmware cannot read at runtime, and in production they frequently hold a board revision, a serial number or a build date. When present they date the firmware and identify which variant of a product a given binary came from — useful when a product line shipped several incompatible revisions under one model number.

Related notes

The 4K-word members of the same family use an identical configuration word with half the address space: the PIC16F74 and the PIC16F72. The later PIC16F767 replaces this part with enhanced peripherals, and the smaller PIC16F716 covers the 18-pin end of the range.

FAQ

Why is the page boundary a problem for disassembly? CALL and GOTO encode only 11 address bits. The upper two bits of the destination come from PCLATH<4:3>, set by an earlier instruction, so a linear disassembler that ignores it mislabels every cross-page target above 7FFh.

Does PCLATH affect the return address? No. The page bits apply to the jump destination only, and PCL<12:11> reverts afterwards. Return instructions use the hardware stack, which holds the full 13-bit address.

Can CP be cleared without erasing the program? No. The programming specification states that the entire program memory is erased when code protection is turned off.

Does this part support low-voltage programming? No. The configuration word has no LVP bit; programming requires high voltage on MCLR.

Is there partial protection like the PIC16F87X? No. CP covers all 8192 words.

Conclusion

The PIC16F76 is a case where the interesting limitation is arithmetic rather than physical. Two bits of address do not fit in a 14-bit instruction, so they live in a register, so the jump structure of the firmware is only reconstructable by reading the instructions around each jump. The protection mechanism is the ordinary Flash mid-range arrangement, and the single fact that governs it is the one about erasing on unprotect. Everything else is a question about reading the image correctly.

PostHeaderIcon Decrypt Locked MCU LPC2103FBD48 Heximal: The Word at 0x14

Every recovery job has a moment where the content is in hand, the file looks correct, and the device still does nothing. On an ARM7 part from this family, that moment is almost always the same four bytes.

The LPC2103FBD48 has eight exception vectors at the bottom of the array. Seven of them are addresses the core will jump to when something happens. The eighth, at 0x00000014, is reserved, and the boot loader uses it as a checksum slot: the sum of all eight words must be zero for the image to be considered valid. Get the other seven right and the eighth wrong, and the loader concludes that no program exists.

Why a boot loader needs an opinion about your code

The loader has to decide, in the first few hundred microseconds after reset, whether to start the application or to wait for a command on the UART. There is no configuration pin for that decision and no flag stored elsewhere; the flash itself has to carry the answer.

A blank array is unambiguously invalid, because erased flash reads as all ones. The problem is a partly written array — a device that lost power during programming, or one whose first sector was corrupted. Those bytes look plausible. A checksum over the vector table is a cheap test that catches the common failure and costs the loader nothing but eight additions.

The rule is arithmetic: the eight words from 0x00 to 0x1C must sum to zero. Since seven of them are addresses the compiler chose, the eighth is whatever makes the total wrap to zero. Any build that produces a bootable binary writes that word automatically, and any process that rebuilds the table by hand must compute it.

What the failure looks like

The symptom is quiet. Power on the board and nothing happens on the application pins, no banner appears on the port the product normally speaks on, and current draw sits at the idle figure instead of rising through the boot sequence.

A debugger attached with the core halted sees an image that looks entirely reasonable: a plausible reset vector at 0x00 pointing into the middle of the array, plausible handler addresses, plausible code at the destination. Nothing in the listing says the checksum is wrong, because the checksum is not a property of the code — it is a property of the table.

The giveaway is the failure mode itself. If the UART answers a question mark after reset, the loader is running, which means it decided the image was invalid. That is a checksum verdict, not a hardware fault.

Three ways to get the word wrong

The first is the simplest: the image was reassembled from a partial read, and the bottom of the array was rebuilt while the reserved slot was left as erased flash. All ones do not sum to zero with any real vector table.

The second is more subtle. Some builds place a jump instruction at 0x00 and others place the address of the reset routine. Both are legal on this core, and a table assembled from one convention and a checksum computed for the other will be wrong by exactly the difference between the two interpretations.

The third is a genuine modification. When the recovered code is adjusted — a peripheral initialisation removed, an address patched to make a board variant work — the vector table changes and the checksum must be recomputed. Forgetting that step produces an image that runs on the bench under a debugger, because a debugger does not ask the loader for permission, and fails completely when the device boots on its own.

Offset Word Meaning Touched by a rebuild
0x00 reset vector first instruction or address yes
0x04 undefined instruction handler address rarely
0x08 software interrupt handler address rarely
0x0C prefetch abort handler address rarely
0x10 data abort handler address rarely
0x14 checksum makes the sum zero must be recomputed
0x18 IRQ handler address sometimes
0x1C FIQ handler address sometimes

MEMMAP changes where the vectors are

There is a second mechanism layered on top, and it matters when the firmware runs code out of SRAM.

The memory map register selects which memory appears at address zero: the boot loader’s own block, the user flash, or the user RAM. A product that copies a routine into SRAM and executes it there — a flash programming routine, a fast interrupt path, a self-modifying decoder — typically switches the map to SRAM so that the vectors it installed at the base of RAM are the ones the core actually uses.

A recovered image therefore sometimes contains two vector tables: the one in flash that the loader checks, and the one the application builds in RAM at run time to redirect interrupts. Only the first is protected by the checksum rule. The second is created by code, and if the code is incomplete, the second table may be missing entries that nothing in the static image reveals.

Reading the dump as a product description

Once the checksum rule is handled, the vector table becomes the most useful page in the file. The IRQ entry is a dispatcher, and the dispatcher’s structure tells you how the firmware organises its work: a table of function pointers indexed by an interrupt source, a chain of comparisons, or a hardware vector controller whose registers were programmed at start-up.

Counting the pointers in that dispatcher gives the number of interrupt sources the product actually uses, which is often far fewer than the silicon supports and is a direct clue about what the board does. On a device with a locked array and a working board, this is frequently the fastest route to understanding the product.

Delivering a hex that boots

A heximal handed to a customer is only useful if the device starts from it. That means the file must carry the checksum, must match the memory map the product was built for, and must not include the region the loader occupies at the top of the array.

Verification is by behaviour, not by byte comparison: write the image, release reset with the entry pin in its normal state, and confirm the first output the product normally produces. If the port stays silent and a question mark gets an answer, the image was rejected — go back to 0x14.

Two related pieces explain the surrounding mechanics: LPC2101FBD48 protection states covers the control word that decides whether the loader will serve you at all, and LPC2104FBD48 mass erase behaviour covers what happens when an erase removes the table you were relying on. For a device where the same boot-time validity check exists under a different vendor’s rules, STM32F101C4 binary recovery is a useful contrast, because there the check is a protection level rather than a checksum.

A short procedure

Read the bottom four words and the top of the array before anything else, compute the sum of the eight vectors, and record it. If the sum is not zero, the device has been telling you all along why it will not start. Fix the word, write sector 0 only, and confirm the loader accepts the image before touching the rest of the device. The check takes a minute and removes the most common cause of a job that appears to have failed when it has actually succeeded.

PostHeaderIcon Decrypt Locked LPC2101FBD48 Program: The Gate Is Not a Cipher

The first sentence of most enquiries about this part is a vocabulary problem. Somebody has a board with an LPC2101FBD48 on it, the debugger refuses to attach, and the request arrives as a request to decrypt the program. That framing sets an expectation that cannot be met, because there is nothing on this device that encrypts the flash array in the first place.

The instruction memory of an LPC2101 is plain. If you can read it, you read ARM code, immediately, with no post-processing step and no secret. What blocks you is not mathematics but a permission bit — a single control word that the boot loader and the debug logic both consult before they will let a byte leave the array.

Understanding that difference changes what a job on a locked part can realistically deliver, and it changes the order in which you attack the unit.

What the protection actually is

The mechanism is called Code Read Protection, and on every member of this family it is implemented the same way: one 32-bit value stored in the last four bytes of flash sector 0. That location is deliberate. It is inside the first erase block, so it cannot be changed without touching the sector that holds the reset vector, and it is the first thing the boot loader examines after reset.

There is no key register, no decryption engine, no per-device secret fused at test. The value written there is a constant that anybody can look up in the user manual, and its only job is to select one of four access states.

Word stored at end of sector 0 State Debug port ISP read commands ISP erase commands
any other value open full access allowed allowed
0x12345678 CRP1 blocked blocked allowed, sector 0 erase wipes the array
0x87654321 CRP2 blocked blocked blocked except the Go command
0x43218765 CRP3 blocked blocked blocked entirely, boot loader stays silent

Because the constants are public, a locked device would tell you its own state if you could read one word. The difficulty is that the states which block the read also block the read of that word, so the diagnosis usually has to be inferred from behaviour rather than read out directly.

CRP1 is a field-update compromise

CRP1 is the state most products actually ship in, because it is the only one that leaves a legitimate update path open. The debug port is closed, the read and copy and compare commands are refused, but the erase and program commands still work on sectors other than the first. A boot loader sitting in the application can therefore pull a new image over UART or CAN and write it, while an outsider with a debugger and a flash utility gets nothing.

The trap is in the exception. If sector 0 is erased through the boot loader while CRP1 is engaged, the device does not erase eight kilobytes. It erases the entire array. NXP built it that way on purpose: without the guard, an attacker could erase only the vector table, drop in a two-hundred-byte routine that reads the rest of the flash and prints it out, and walk away with the firmware through the front door. Making the first sector special makes that attack cost exactly the same as losing everything.

CRP2 and CRP3 remove the door

CRP2 closes the debug port and reduces the ISP command set to a single verb: Go. The boot loader will still start the application, which is all a finished product needs, but it will not read, will not erase, will not report the part identifier. There is no authorised update path left, so a product shipping in CRP2 is telling you that its firmware is never meant to change.

CRP3 goes further and removes the boot loader from the conversation completely. No commands, no Go, no entry. On a CRP3 part the only interface left is the pins the application itself drives, and whatever those pins happen to expose is the only handle you have.

For recovery work the consequence is blunt. On CRP2 and CRP3 there is nothing to negotiate with. The job stops being a firmware job and becomes a silicon job.

So what does a locked LPC2101 still give you

Quite a lot, none of it the array. The device runs. A device that runs can be observed: current draw at reset over time, bus activity on the external memory interface if the design uses one, the timing of the first output on each port pin, the access pattern to an external serial memory if the board carries one. On a small part like this one, with eight kilobytes of flash and two kilobytes of SRAM, the firmware is compact enough that its behaviour is often a stronger description than its listing would be.

There is also the honest intermediate outcome. If the board carries an external EEPROM or a configuration serial flash, that content is usually unprotected and often holds the calibration and product identity that the customer actually needs, even though it is not the program.

The order that avoids destroying the evidence

Do the passive work first, and do all of it before anything is erased. Photograph the board, identify every memory device, dump anything on an external bus, record boot behaviour, and only then consider touching the protected part. The reason is cumulative: every step that involves erasing sector 0 is irreversible, and it also clears the protection word, so a unit that was unlocked and blank cannot afterwards be told apart from one that never held a program.

Then measure the state. Attempt a debug attach with adaptive clocking enabled and record whether the core answers at all. Attempt an ISP synchronisation with the boot entry pin held at the required level during reset, and record whether the boot loader replies, replies and refuses, or stays silent. Those two results place the part in one of the four rows above with high confidence, without writing anything.

Only after that is it reasonable to discuss invasive options, and only with the customer told plainly what they cost.

What the word decrypt means in this trade

It survives because it is short, and because customers use it to mean any situation in which firmware is inaccessible. It is worth correcting once, in writing, at the start of a job: the array is readable given access, the access is a permission state rather than a cryptographic one, and where that state has been set to its highest level, no amount of computation recovers the flash from outside.

That correction is not pedantry. It decides whether the next two weeks are spent with a scope and a decapping station or with a debugger, and it decides what the customer is told to expect at the end.

Where the small parts fit

The LPC2101FBD48 is the eight-kilobyte member of a family that runs from eight kilobytes to five hundred and twelve, all on the same ARM7TDMI-S core with the same boot loader behaviour and the same protection word. What is learned here transfers upward almost unchanged: the control word sits at the end of the first sector, erasing that sector costs the whole array, and the command set is identical on every density.

The details that change with size are the ones that matter later in a job. The larger members are covered in LPC2114FBD64 code work and in LPC2138FBD64 locked flash recovery, where the array is big enough for partial recovery to be meaningful.

A short checklist before the bench

Confirm the exact ordering code, because the same die ships in more than one package and board access differs even when the silicon does not. Confirm the crystal, because ISP autobaud is derived from it and a board with an unusual clock will not synchronise at the rates written in the manual. Confirm whether the product was ever field-updated, because a shipping update path is strong evidence of CRP1 rather than CRP2. And confirm what the customer actually needs — the whole image, the calibration block, or the protocol spoken on a port. Those three answers lead to different procedures, and only the first one requires the array at all.