/writeups

Patching Snap Tap into keyboard firmware

11 min read#reverse-engineering#firmware#keyboards

My Razer Huntsman V3 Pro Mini (USB 1532:02B0) only runs one Snap Tap pair in stock firmware, locked to last-input-wins. I wanted a second pair and selectable SOCD rules running natively on the keyboard rather than in host software.

With the HID command protocol and class-02 dispatcher mapped out in the previous post, I moved from read-only probing to patching the 2.01.00 firmware itself—carving out a code cave by compressing stock metadata templates, validating the patch through a differential emulator harness, and flashing it onto my own board.

One note upfront: flashing custom firmware can permanently brick a keyboard. This is a write-up of the design and findings, not flashing instructions, and I’m not publishing firmware images or flashing tools.

What stock firmware does

The Snap Tap engine lives inside the normal key-event function at 0x2000D5D4. Its configuration is three bytes in the live profile at 0x200270AC: enable at +0x128C, key A at +0x128D, key B at +0x128E. The host writes them with command 02:21 and reads them with 02:A1. A global mode byte at 0x200283AA bypasses the engine completely when it equals 3.

Each key has a held flag and a reported flag. Press one key of the pair and the firmware clears the other key’s reported flag and sends its release, but leaves its held flag set. Release a key and the other one gets re-pressed if it’s still held. That’s last-input-wins, for exactly one pair.

The chip and the image

The main image is 131,072 bytes. Its first two vector words give a stack pointer of 0x04008000 and a reset address of 0x20000215, so it’s linked to run from RAM. The reset code executes MSR MSPLIM, r0, an instruction a Cortex-M4 doesn’t have. The peripheral addresses the code builds match NXP’s LPC55S69 header and contradict the LPC54114 one.

Earlier I’d assumed a Cortex-M4 from SDK driver strings. That was wrong: it’s a Cortex-M33 in the LPC55xx family (LPC55S6x or LPC55S2x), though I haven’t pinned down the exact part number.

0x04000000..0x04008000  SRAMX: stack at the top (limit 0x04006000), report and control buffers
0x20000000..0x20020000  the image, running from SRAM
  0x20000200..0x2001B634  code (804 recovered functions)
  0x2001BE74..0x2001C480  six 258-byte profile metadata templates
  0x2001E584..0x2001E5C4  four scatter-load descriptors
0x20020800..0x20026C00  data decompressed at startup (includes the LED routing table)
0x20026C00..0x2002CD08  zero-filled data (includes the live profile at 0x200270AC)
flash 0x49C00..0x7F400  settings, profiles and macros

A separate bootloader (not included in the updater’s main image) copies this image into RAM at startup. A second chip on the board has its own encrypted firmware, which I left untouched.

One finding from the disassembly shaped every decision after it: the HardFault handler erases flash 0x49C00..0x7F400 and then resets. A patch that faults doesn’t just crash—it wipes every stored profile and macro.

The first cave broke typing

A code cave is a run of bytes in an image that nothing uses, where new code can go. My first attempt was on the previous firmware, 2.00.01. I put a small handler in what looked like 24 unused bytes at 0x2001B746, after checking for direct branches, constructed addresses and PC-relative loads into it. All three checks came back clean. I flashed it, and normal typing broke before I’d even sent the new command.

Those bytes were inside an LED routing table that the lighting refresh reads as a whole: six groups of 22 five-byte entries. My code turned four empty entries into live ones whose channel bytes pointed outside any LED bank. No instruction references that address directly, so no reference search could have found it. I recovered by reflashing stock through the bootloader.

Finding space, and auditing it

After that I built a byte-level occupancy ledger of the 2.01.00 image: recursive disassembly, hand-reviewed switch tables, then emulated runs of startup data loading, LED refresh and all 256 class-02 commands. The result isn’t flattering. 96,826 bytes of reached code, 11,446 of data, 22,800 unknown, and zero bytes confirmed free. Unknown doesn’t mean free.

So I stopped looking for a cave and made one. The six metadata templates take up 1,548 bytes, and each is a prefix of at most 35 meaningful bytes followed by zeros. The firmware already contains the decompressor it uses for startup data. Each template can be rewritten as a 40-byte record that the existing routine expands back to the same 258 bytes:

00 25 DC | <36 template bytes> | 01
header: 36 literals, then 222 bytes copied from distance 1 (repeating the final zero)

Three copy sites change five instructions each, same sizes, so they call the decompressor instead of the copy helper. Six records take 240 bytes, which leaves [0x2001BF64, 0x2001C480), 1,308 bytes, unused. In emulation, all 108 combinations of template, consumer and poisoned destination reconstruct identical bytes.

Then I tried to break my own claim that only three places read those templates. A scanner decodes every one of the 65,536 halfword offsets and follows address arithmetic symbolically. An emulated matrix of 177,152 host commands ran with read hooks on the range and a guard on every executed store. Every template read came through the three known copy sites, and none of the 1,729,067 executed store instructions touched the range. Because the image runs from RAM, I also bounded the DMA and USB controllers’ buffers away from it, statically.

That audit still has boundaries: emulated boot stops at a flash read outside the image, 313 commands hit their instruction budget, and the bus bounds come from NXP’s docs rather than a logic analyser. It was more than enough confidence to take the cave to hardware.

The patch, in stages

Each stage contains the one before it. Every step asks one question, so a failure points at one change.

Stage Adds Cave bytes used On my keyboard
S0 Stock, re-emitted by my own writer 0 Flashed
S1 One changed character in an assert string 0 Flashed
S2 Template compaction (creates the cave) 0 Flashed
S3 Second pair, last-input-wins 548 Never flashed
S4 Modes 1 (neutral) and 2 (first-input-wins) 928 Never flashed
S5 Mode 3, depth-based “Rappy Snappy” 1,096 Never flashed
S6 Host command and strict enable 1,300 Flashed

S0 proves my image writer reproduces stock byte for byte. S1 asks only whether the bootloader accepts a modified image. I found no checksum over the image statically, but I didn’t have the bootloader to read, so only the device could answer.

S3 hooks three stock sites: the “is this key B?” check at 0x2000D6E0, the pair-1 enable check at 0x2000D662, and the last write of the profile-switch reset at 0x2001AD86. Each becomes a branch into the cave, where the displaced check is reproduced before pair 2’s keys get tested. Pair 2’s configuration goes in record bytes +0x12BB..+0x12BE (enable, key A, key B, mode). No stock instruction references those bytes, but the record CRC covers them.

Mode Rule
0 Last input wins (the stock rule)
1 Neutral: both held reports neither
2 First input wins until it is released
3 Depth: the strictly deeper key wins, a tie keeps the incumbent

Mode 3 needs each key’s depth. The six Rapid Trigger call sites into the key-event function already hold the resolved key id in r0 and the depth sample in r9. So each call is redirected through a trampoline that latches the depth for pair-2 keys and then tail-calls the original. That means depth is compared on Rapid Trigger events, not on every scan.

S3, S4 and S5 must never be flashed. They have no host command, so there’d be no way to exercise their features. Worse, the bytes I’d called free aren’t zero. When the firmware rebuilds a profile it copies a template tail over them, leaving 1F 04 96 00. S3 to S5 test “enable is nonzero”, so on a record like that they’d arbitrate keys 4 and 150 without anyone asking. My tests missed this at first because they always wrote enable as 0. S6 rewrites the three enable checks in place to require exactly 1.

The host command

Stock 02:21 validates nothing—even a declared size of 0 rewrites pair 1. Extending it would change the meaning of requests the vendor software already sends, so S6 adds a new pair inside the same 90-byte HID report format: 02:22 to set and 02:A2 to get. Both ids used to fall through to the “unsupported” case in the class-02 jump table. S6 updates those two table entries and adds a 204-byte handler at [0x2001C3AC, 0x2001C478), leaving 8 cave bytes to spare.

90-byte report
+0x00  status           +0x06  class   02
+0x05  declared size 5  +0x07  command 22 (SET) or A2 (GET)
+0x08  ProfileId        0 = live RAM, 1..6 = stored slot
+0x09  enable2          0 or 1
+0x0A  keyA2            analog key id
+0x0B  keyB2            analog key id
+0x0C  mode             0..3
+0x58  XOR of bytes 2..0x57

Anything invalid gets status 03 before any write. This is the oracle my fuzzer checks the handler against:

def valid_request(command, size, payload):
    if size != 5 or payload[0] > 6:
        return False
    if command == GET_ID:
        return True
    enable, key_a, key_b, mode = payload[1:5]
    if enable > 1 or mode > 3:
        return False
    if key_a == key_b:
        return key_a == 0 and enable == 0
    return key_a != 0 and key_b != 0

A stored-slot SET reuses 02:21’s own page writer and CRC commit, and writes through to live RAM if that slot is active. Before a live change the handler releases any pair-2 key that’s currently reported, so reconfiguring can’t leave a key stuck. The firmware doesn’t reject a pair-2 key that’s also a pair-1 key. There was no room. The host has to refuse that.

Testing before hardware

My first harness stubbed the report function with an instant return. S4 and S5 passed it. Then I ran every stage against stock with the real report mapper and compared calls, report buffers, pair-1 state and the registers the stock code needs afterwards. That run blocked the images on real defects:

  • S5 broke stock pair 1 with every new feature off. It reused r0, which the stock path still needed, and sent a release with the wrong key id.
  • S5’s depth takeover kept a pointer in r3 across a call that’s allowed to clobber it, then stored through it. In emulation that was a write to address 0x1. On the keyboard I’d expect a fault, and a fault wipes the profile region.
  • With pair 1 disabled, modes 1 to 3 silently behaved as mode 0.
  • A retriggered key could lose its reported flag without a release, which leaves it stuck down.

The stub now behaves like the worst legal callee:

def on_call(uc, address, size, data):
    calls.append(tuple(uc.reg_read(register) for register in CLOBBERED[:3]))
    for index, register in enumerate(CLOBBERED):
        uc.reg_write(register, POISON | index)
    flags = uc.reg_read(arm.UC_ARM_REG_APSR_NZCV)
    uc.reg_write(arm.UC_ARM_REG_APSR_NZCV, ~flags & 0xF0000000)
    uc.reg_write(arm.UC_ARM_REG_PC, uc.reg_read(arm.UC_ARM_REG_LR))

After the repairs the differential records zero unexpected differences: LED output over 2,048 ticks, macro playback, a 29-event Snap Tap sequence, and the 177,152-command matrix in 22 configurations. Unless pair 2 is enabled with exactly 1, S6 must equal stock. The command itself was fuzzed with 2,583 requests per run, at every declared size from 0 to 80, checking after each one that an invalid request changed nothing.

The tools needed checking too. Keystone mis-encoded some wide branches to absolute addresses without raising an error. Now every external branch is encoded independently and every decoded target is checked against its intended label.

Flashing it and testing on hardware

Once the bootloader recovery path was proven and the emulator harness was green, I moved to the board. In mid-November I flashed S0, ran the official 2.01.00 update so both chips were on matching firmware, then flashed S1, S2, and S6, verifying each image’s hash first. Each stage passed its dormant checks with the new features off: normal typing, lighting, all six onboard profiles, and reconnecting my host tool. S1 booting confirmed the bootloader accepts a modified main image.

Flashing itself wasn’t completely smooth: read-back verification mismatched in a few chunks on early attempts, so S2 verified cleanly on its fifth session and S6 on its second. My tool didn’t log which addresses mismatched, so I don’t know whether they clustered in patched ranges.

Ten days later I exercised the new command. 02:A2 returned 1F 04 96 00 for every slot, matching the template-tail prediction from emulation, and those records stayed disabled. I configured W/S as pair 2 in live RAM and tested all four modes (0–3): each read back cleanly and behaved as designed alongside A/D on pair 1. Writing pair 2 to flash slot 1 survived a replug and followed that slot across profile switches; disabling and restoring it worked the same way. No profile wipe occurred across any of those sessions, meaning nothing hit the HardFault handler.

Scope and remaining gaps

The patch runs daily on my keyboard, with a few edges still only exercised in emulation:

  • Invalid-request rejection (status 03) hasn’t been sent on hardware, since my host tool refuses to construct malformed requests.
  • Hardware testing covered W/S on live RAM and slot 1 with pair 1 active; pair 2 with pair 1 disabled, live edits while keys are held, overlapping pairs, and stored writes to slots 2–6 haven’t been run on the board yet.
  • Boot isn’t emulated end-to-end, the flash page writer is modelled in tests, the bootloader binary itself hasn’t been dumped, and the exact LPC55xx part number is still unconfirmed.
  • Every hook and address here is specific to firmware 2.01.00.

From a single hardcoded pair to two pairs and four SOCD modes in 1,300 bytes of reclaimed template space—running on hardware, surviving replugs, and keeping every onboard profile intact.