bindec: decode anything with bytes in it, written in pure KingCobra
I wrote bindec, a tool that turns bytes, or text that looks like bytes, into something a human can read. It decodes executables, packet captures, WebAssembly modules, nested archives, images, serialization formats and yo
I wrote bindec, a tool that turns bytes, or text that looks like bytes, into something a human can read. It decodes executables, packet captures, WebAssembly modules, nested archives, images, serialization formats and your own protocols into one uniform, annotated tree. It is written entirely in KingCobra, my programming language, and needs nothing beyond the stock interpreter.
Repo: https://github.com/DivyanshuSinha136/bindec
Three questions about any blob of bytes
bindec answers three questions:
- What is it? Magic-number and structure-based detection, with a confidence score and the reason.
- What is inside it? A field-by-field tree where every node carries its offset, length, value and meaning.
- What changed? Structural diffs between two files, recursive unpacking of nested archives, and byte-level diffs that stay fast on multi-gigabyte inputs.
Try it
bindec is plain KingCobra source. All you need is the kingcobra interpreter on your PATH:
# Linux / macOS
./bindec detect tests/fixture.pcap
# Windows (cmd or PowerShell)
bindec.cmd detect tests\fixture.pcap
# any platform, without the launchers
kingcobra run src/main.kc detect tests/fixture.pcap
tests/fixture.pcap: pcap (confidence 90%; pcap global header magic; 1.3 KiB)
entropy of first 64 KiB: 4.60 bits/byte (text or code)
If the interpreter lives elsewhere, point to it with KINGCOBRA=/path/to/kingcobra. The repo includes the fixtures that the examples below use, so you can reproduce every one.
What it decodes
| Area | Formats |
|---|---|
| Executables | ELF32/64, PE32/PE32+, Mach-O (thin and fat), WebAssembly |
| Network | PCAP (little and big endian, Β΅s and ns), PCAPNG |
| Containers | ZIP, GZIP, TAR, SQLite (and recursive nesting of the first three) |
| Images and audio | PNG, GIF, BMP, JPEG, WAV |
| Serialization | Protocol Buffers, MessagePack, ASN.1 DER/BER, PEM |
| Code | x86-64 (Intel syntax), ARM64 (LLVM syntax), WebAssembly instructions |
| Custom | JSON schemas, textual encodings (bin, hex, oct, dec, base64) |
A few of these deserve a closer look:
- Executables. Headers, segments, sections, symbols, imports and exports, and dynamic entries. Mach-O covers thin 32/64-bit files in both endiannesses and fat/universal binaries, with load commands, dylibs, rpath, UUID, build version, entry point and dyld info.
-
WebAssembly. Every section, imports and exports, element and data segments, the
name,producersandtarget_featurescustom sections, and a function-body disassembler. - PCAP and PCAPNG. Ethernet, 802.1Q, Linux cooked, ARP, IPv4 and IPv6, TCP, UDP, ICMP and ICMPv6, DNS with name compression, plus HTTP and TLS recognition. Checksums are verified, and protocol, flow and DNS statistics are summarised.
- Recursive archives. ZIP, TAR and GZIP inside each other, to any depth, entirely in memory. A DEFLATE decoder written in KingCobra verifies every CRC-32.
- Forensics toolbox. Strings (ASCII and UTF-16LE), a per-block entropy map, a binwalk-style signature scan, single-byte and repeating-key XOR recovery, and integrity checks for PNG, ZIP, GZIP and SQLite.
Examples
Decode a packet capture
./bindec decode tests/fixture.pcap --packets 3 --depth 2 --no-offsets
# pcap -- pcap global header magic -- 15 packets, 93 nodes
PCAP (little-endian, microsecond timestamps)
header
magic = 0xa1b2c3d4
snaplen = 65535
linktype = 1 (Ethernet)
summary = 15 (packets, 1.1 KiB, 3.000 s)
first_packet = "2023-11-14 22:13:20 UTC"
protocols = 6
flows = 4
dns_names = 2 (www.example.com, host.local)
packets = 15
packet[0] (β¦ 192.168.1.10 > 192.168.1.1 ARP who-has 192.168.1.1 tell 192.168.1.10)
packet[1] (β¦ 192.168.1.1 > 192.168.1.10 ARP 192.168.1.1 is-at 02:00:00:00:00:02)
packet[2] (β¦ 192.168.1.10:53211 > 192.168.1.1:53 DNS query www.example.com)
Disassemble ARM64 and x86-64
./bindec disasm tests/fixture_arm64.macho --max 4 # architecture comes from the Mach-O header
./bindec disasm tests/fixture_fat.macho --slice x86_64 # pick a slice of a universal binary
./bindec disasm firmware.bin --arch arm64 --addr 0x8000 # raw bytes
; Mach-O __text, 4 instructions, AArch64 (LLVM syntax)
00000000: ff c3 00 d1 sub sp, sp, #0x30
00000004: f4 4f 01 a9 stp x20, x19, [sp, #0x10]
00000008: fd 7b 02 a9 stp x29, x30, [sp, #0x20]
0000000c: fd 83 00 91 add x29, sp, #0x20
Unknown encodings degrade to .inst or db, never to a wrong answer.
Inspect WebAssembly
./bindec decode tests/fixture_mod.wasm --depth 1 --no-offsets
./bindec disasm tests/fixture_mod.wasm --func add
func[2] $add (i32, i32) -> (i32) ; body 0x17a, 0 locals
00017a: local.get 1
00017c: local.get 0
00017e: i32.add
00017f: end
Unpack nested archives safely
./bindec archive tests/fixture_nested.zip --nest 4 --no-offsets
Archive tree (recursive inspection)
summary = 11 (nodes, max depth 4, 14.5 KiB unpacked)
formats = 8 (zip, text, gzip, tar, wasm, pcap, png, unknown)
warnings = 3
(input) = 2084 (zip, 4 entries)
bundle.tar.gz = 1571 (gzip, CRC ok | deflate, CRC ok)
(decompressed) = 10240 (tar, 4 entries)
module.wasm = 769 (wasm)
capture.pcap = 1359 (pcap)
nested/inner.zip = 352 (zip, 2 entries)
link (symlink -> ../../etc/passwd)
!! link target escapes the extraction root: ../../etc/passwd
../evil.txt = 1 (text, entropy 0.00 | deflate, CRC ok)
!! suspicious entry name: path traversal (..)
Nothing is ever written to disk. You can tune the limits with --nest, --max-entries and --max-total.
Diff two binaries
./bindec diff old.wasm new.wasm # structural
./bindec diff a.macho b.macho --ignore uuid,timestamp # skip volatile fields
./bindec diff a.bin b.bin --raw # byte ranges, fast on huge files
# old.wasm vs new.wasm (wasm)
~ memory/memory[0] 2 (min 2 pages (64 KiB each)) -> 4 (min 4 pages (64 KiB each))
~ memory/memory[0]/limits 2 (min 2) -> 4 (min 4)
~ data/data[0]/bytes 07 00 00 00 |....| -> 09 00 00 00 |....|
-- 3 changed, 0 added, 0 removed, 0 moved (offset only), 95 identical
The markers are ~ for changed, + for added, - for removed and > for moved (with --show-moved). Offset-only changes are hidden by default, because a growing section shifts everything after it.
Decode text that looks like bytes
./bindec text "01001000 01100101 01101100 01101100 01101111"
./bindec text --solve "10110111 10011010 10010011" # try every bit order, inversion and word size
input: bin, 40 bits -> 5 bytes hex: 48 65 6c 6c 6f
encoding: utf8 (score 1.02, 0 errors)
Hello
Decode your own protocol
schema decodes a custom format from a declarative JSON file: integers, floats, strings, varints, enums, bit-fields, scaling, counted and length-prefixed arrays, nested structs, conditionals, seeks, expect magics and CRC-32 checks.
{ "name": "Packet", "endian": "be", "fields": [
{ "name": "magic", "type": "str", "size": 4, "expect": "PKT1" },
{ "name": "flags", "type": "u8", "bits": [ {"name":"urgent","bit":0}, {"name":"prio","bit":1,"width":3} ] },
{ "name": "count", "type": "u16" },
{ "name": "items", "type": "struct", "ref": "Item", "count": "count" },
{ "name": "plen", "type": "u8" },
{ "name": "payload","type": "bytes", "size": "plen" },
{ "name": "crc", "type": "u32", "check": "crc32", "over": "payload" } ],
"structs": { "Item": { "fields": [ { "name": "id", "type": "u16" }, { "name": "name", "type": "pstr" } ] } } }
./bindec schema examples/packet.bin --schema examples/packet.schema.json
Every command that produces a tree also accepts --json, so the output can go straight into other tools.
One tree for every format
The design decision that keeps the code small is that every decoder is a single decode(stream, opts) function that returns the same node shape:
{ name, off, len, val, note, fmt, kids[] }
The text renderer, the JSON renderer, the diff engine and the archive walker all work on that shape, so they work on every format without knowing any of them. That is also why diff can compare two WebAssembly modules, two Mach-O files or two packet captures with the same code. Adding a format takes one decode(s) function that returns a tree, plus one line in detect.kc.
src/
βββ main.kc CLI: argument parsing, command dispatch, large-file loading
βββ detect.kc format registry + magic/structure detection + decoder dispatch
βββ tree.kc decode-tree builder, renderers (text/JSON), search, shift
βββ util.kc hex/time/IP helpers, checksums, entropy
βββ elf.kc pe.kc macho.kc wasm.kc executables and modules
βββ pcap.kc PCAP / PCAPNG + packet dissectors
βββ media.kc container.kc wire.kc images, containers, serialization
βββ x86.kc arm64.kc neon.kc disassemblers
βββ inflate.kc archive.kc DEFLATE, recursive archive walker
βββ diff.kc analyze.kc schema.kc textcodec.kc
Checked against independent tools
A decoder that is only tested against itself proves very little, so the decoders are checked against independent oracles:
| Component | Oracle | Result |
|---|---|---|
| ARM64 disassembler |
llvm-objdump on clang output, -O0 to -O3 |
100 % identical (about 1,100 instructions) |
| ARM64 (random words) |
llvm-objdump on 24,000 scalar and NEON words |
0 mismatches, and unsupported encodings print .inst
|
| x86-64 disassembler | GNU objdump -M intel on /bin/ls
|
10,271 of 10,276 identical (the rest are slice-edge artefacts) |
| WebAssembly |
llvm-objdump on a linked module |
instruction-for-instruction identical, and every function body ends exactly on its end
|
| DEFLATE and gzip | Python zlib at levels 0, 1, 6, 9 and random data |
byte-for-byte identical, CRC-32 verified |
| Whole project | kingcobra test tests/bindec_test.kc |
64 passed, 0 failed |
Decoding is also defensive: truncated or corrupt input produces !! warning nodes, never a crash, and the test suite truncates every fixture to prove it.
Safe to point at untrusted files
bindec is built to inspect files you don't trust:
- Read-only. It never writes to the inspected file and never extracts archives to disk.
- Bounded. Nesting depth, entry count, total unpacked size, per-entry size and DEFLATE output are all capped, which guards against decompression bombs.
-
Honest about danger. Entry names containing
.., absolute paths and drive letters, and links that escape the extraction root, are flagged. - No code execution. Input is parsed, never evaluated.
Large files
Inputs above 64 MiB (or anything with --mmap) are streamed through file-backed streams instead of being loaded into memory. detect, scan, entropy, hexdump, diff --raw and the executable and PCAP decoders run in constant memory. On a 161 MB file, a signature scan took 3.6 s, a raw diff 1.0 s and a sampled entropy map 0.3 s.
Honest limits
-
x86-64: no VEX/EVEX (AVX) and no 16-bit or 32-bit modes. ARM64: no SVE, MTE, PAC or RCPC (these print as
.inst). - Archives: ZIP64, encrypted entries, and 7z, RAR, xz, bzip2 and zstd are reported but not unpacked. Archive inspection keeps the unpacked data in memory, with a default cap of 64 MiB.
- WebAssembly: the component model and most SIMD mnemonics are not decoded, although SIMD immediates are still consumed correctly.
- PCAP: link types other than Ethernet, 802.1Q, Linux cooked, loopback and raw IP are listed but not dissected, and there is no TCP stream reassembly.
-
stringsscans the first 8 MiB. Page further with--offset.
Get it
- bindec: https://github.com/DivyanshuSinha136/bindec
- KingCobra: https://github.com/DivyanshuSinha136/KingCobra
- Learn the language: https://dev.to/divyanshusinha136/learn-kingcobra-in-30-minutes-a-hands-on-tutorial-53eh
MIT licensed. If it gets a file wrong, or you want a format added, open an issue. A bug report with the file that triggers it (or its first few hundred bytes) is the most useful thing you can send. A star helps other people find it.
Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes β full credit and traffic to the original publisher.