Skip to content

About

Binary Ninja plugin that decodes encrypted or encoded strings using cipher/encoding/decompression recipes (XOR, RC4, AES, ChaCha20, TEA, Base64, zlib...), with XOR key brute-forcing and decryptor call-site decoding

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

String Decoder

A Binary Ninja plugin that decodes encrypted or encoded strings. You describe the decoder as a recipe (a chain of cipher, encoding and decompression steps, or a small per-byte program), point it at a selection, an address or a string-decryption function, and String Decoder decodes the bytes, scores how much the result looks like a real string, and writes the plaintext back: comments, tags, optional names and patches, and the decoded text inline in decompiled code. When the key is unknown, the brute-force commands search it.

Everything that decodes, parses or scores is pure Python (standard library only) under string_decoder/core/ and has no Binary Ninja dependency. Only bn_adapter.py and plugin.py talk to Binary Ninja.

Quick start

A typical session with a sample whose strings are decrypted by a function decrypt_str(buf, len):

  1. Find the decryptor. Look for a function called with pointers to unreadable data, for example decrypt_str(&data_404010, 0x12).
  2. Find the key. Select the encrypted bytes of one string and run Brute force > Brute-force selection... (or Brute-force strings passed to this function... inside the decryptor, which scores every key on all strings at once and is much more reliable). If the bytes are Base64 or hex first, put base64_decode or hex_decode into "Recipe before the searched step". Pick the best candidate in the follow-up question to decode it right away or to save it as a profile.
  3. Decode every call. Put the cursor inside the decryptor and run Decode all calls to this function..., or put it on a call of the decryptor anywhere and run Decode all calls to the called function.... Enter the recipe (or choose the profile), the pointer argument (0 = first) and, if the decryptor takes one, the length argument.
  4. Check the report. It lists every call with links to the string, the call site and the caller, the decoded text, its score and what was written ("Annotated"). Choose "Annotate: Preview only" first if you want to try a recipe without touching the database.
  5. Later, after more analysis found new calls, run Re-run bound decoders. To undo, use Binary Ninja's Undo (one step per command) or Clear decoder annotations....

Commands

All commands are under Plugins > String Decoder and in the context menu.

Command Context What it does
Decode selection... selection Decodes the selected bytes with a recipe or a saved profile; the report also shows the full output and a hex dump.
Decode selection as table... selection Decodes every string of a selected table: NUL- or UTF-16-separated strings (with plain or encrypted separators), fixed-size records, or arrays of pointers, {pointer, length}, {length, pointer} or {offset, length} records.
Decode string at address... address Locates the encoded string at the address (see string layouts) and decodes it. On an instruction that refers to data, or on a pointer variable, the referenced string is offered first.
Decode all calls to the called function... address With the cursor on a call of a decryptor: decodes the string passed to every call of that decryptor.
Decode all calls to this function... function Run inside the decryptor: for every call of it, takes the pointer argument (and optionally the length argument), reads the string and decodes it.
Decode table lookups of this function... function Run inside an index-based decryptor such as get_string(17): the constant index argument selects the entry of a string table.
Re-run bound decoders any Decodes the calls of every decryptor decoded before again, with the same settings (stored in the database).
Brute force\Brute-force selection... selection Searches the key of simple ciphers for the selected bytes.
Brute force\Brute-force string at address... address The same for the string at an address (located with a string layout).
Brute force\Brute-force strings passed to this function... function Searches one key that decodes all strings passed to the decryptor, ranked by their mean or lowest score.
Results\Show last results any Shows the results of the last decode run of this binary again.
Results\Export decoded strings... any Writes the last results (addresses, call sites, function, recipe, score, full text, output bytes) to JSON or, for a name ending in .csv, CSV.
Results\Save decoded bytes to file... any Saves the full decoded bytes of one of the last results.
Profiles\Save recipe as profile... any Stores a recipe, a score threshold and a description under a name (asks before replacing a profile with the same name).
Profiles\Show profiles any Lists the saved profiles.
Profiles\Delete profile... any Deletes a saved profile.
Profiles\Import profiles... any Merges profiles from a JSON file into the saved ones (same-name profiles are replaced).
Profiles\Export profiles... any Writes the saved profiles to a JSON file.
List recipe steps any Shows every recipe step with its parameters.
Clear decoder annotations... any After asking, removes the comment lines, highlights, tags, names and data types String Decoder added. Patched bytes stay patched (use Undo).

The decode dialogs offer the saved profiles and a recipe field (a chosen profile wins over the field; a profile's stored string settings win over the dialog's). The recipe, layout, terminator and call arguments you used last are remembered for each binary. Every decode dialog has an Annotate choice: Plausible results only (the default, from the setting stringDecoder.onlyPlausible), All successful results, or Preview only (write nothing). When patching is enabled you are asked before any byte is overwritten.

With the UI running, results are shown in a Markdown report: links to the string, the call site and the caller, score, plausibility, encoding, what was written for each result ("Annotated"), the escaped text and warnings (truncated strings, calls through thunks or wrappers, stack strings). A summary says how many comments, tags, highlights, names and patches were written and how many results were not annotated and why. Without the UI the plain-text listing is logged. Problems are shown in a message box ("... failed: reason. Details are in the log."), the details go to the String Decoder log.

What is written

  • Comments: [decoded] "text" at the string's address and, for call sites, at the call (L"..." for UTF-16LE, Lbe"..." for UTF-16BE, b"..." with \xNN escapes for undecodable bytes), at most stringDecoder.commentLength characters. Existing comment lines are kept; an older [decoded] line is replaced.
  • Tags of type "Decoded string" at strings and call sites (setting stringDecoder.addTags), so the Tags view lists every decoded string.
  • Decompiled code: with stringDecoder.inlineStrings, a string recognizer shows the decoded text (as decoded:"...") wherever HLIL uses the encoded string's address, and the affected functions are reanalyzed after decoding.
  • Names (optional, stringDecoder.nameStrings): a str_<text> symbol and a sized data variable (char[n]/wchar16[n] after patching, otherwise uint8_t[n]); user-defined names and types are never replaced. The size is that of the encoded string itself - for byte-wise, stream and block ciphers the decoded string and its terminator (whole blocks), the same bytes a patch writes - not the bytes read after it, so the type and the inline string never cover the encrypted strings that follow.
  • Highlights of decoded call sites (optional).
  • Patches (optional, stringDecoder.patchBytes): the encoded bytes are overwritten with the decoded bytes. For byte-wise and stream ciphers only the decoded string and its terminator are written (whole blocks for block ciphers), so encrypted strings that follow stay intact. For recipes that change the length (encodings, slices, decompression) the whole encoded string is replaced (padded with NUL bytes), and nothing is patched when the decoded string ended before the decoded data did, or is longer than the encoded one. The report lists the patched ranges.

All writes of one command happen in a single undoable transaction. What was written is recorded in the database (metadata string_decoder.annotations), which is what Clear decoder annotations... uses. The last results (with the full text) are stored too (string_decoder.results), as are the decoded strings shown in decompiled code (string_decoder.decoded) and the decryptors decoded at call sites (string_decoder.bindings).

Decoded strings come from untrusted binaries, so comments, tags, reports and inline strings escape control and format characters (including bidirectional overrides), reports escape Markdown and HTML characters, and CSV exports defuse cells that a spreadsheet would run as a formula.

Settings

Key Default Meaning
stringDecoder.defaultRecipe empty Recipe pre-filled when the binary has no last-used recipe.
stringDecoder.scoreThreshold 0.5 Results scoring above this (0 to 1) are plausible. Profiles carry their own threshold.
stringDecoder.stringLayout cstring Default layout for strings located by address.
stringDecoder.terminator auto Default cut of the decoded output: auto, none, nul or wnul.
stringDecoder.maxLength 4096 Most bytes read for one string (1 to 1048576); also caps length arguments.
stringDecoder.addComments true Write comments.
stringDecoder.commentLength 200 Longest decoded text in a comment (16 to 4096).
stringDecoder.onlyPlausible true Default of the Annotate choice: plausible results only.
stringDecoder.skipTruncated false Do not annotate strings that had no terminator within the maximum length.
stringDecoder.highlightCallSites false Highlight decoded call sites in green.
stringDecoder.addTags true Tag decoded strings and call sites.
stringDecoder.nameStrings false Define str_<text> symbols and sized data variables.
stringDecoder.inlineStrings true Show decoded text in decompiled code (when turned off, the string recognizer is not registered at the next start).
stringDecoder.patchBytes false Overwrite encoded bytes with decoded bytes (asks first).
stringDecoder.followWrappers true Decode the calls of wrapper functions that pass their parameter on to the decryptor.
stringDecoder.bruteForceFamilies xor_single, add_sub, rol_byte, not, xor_index, xor_chain, xor_multi, xor_rol, rol_xor Families pre-filled in the brute-force dialogs.
stringDecoder.bruteForceTop 10 Number of brute-force candidates (1 to 100).
stringDecoder.bruteForceMaxKeyLength 16 Longest repeating key xor_multi tries (2 to 64).

Invalid setting values are ignored with a warning in the log.

Recipes

A recipe is a |-separated chain of steps, applied left to right:

xor_single(0x55) | base64_decode(alphabet=urlsafe) | rc4(key="secret", drop=256)
  • A step is name or name(arguments). Arguments are positional (in the order listed below) or name=value; positional ones come first.
  • Integers: decimal, 0x..., 0o..., 0b..., optionally negative. Decimal literals with a leading zero are rejected.
  • Byte strings: hex:0102ff, or a quoted string ("..." or '...'), which means its UTF-8 bytes. Escapes: \\ \" \' \n \r \t \0 \xHH.
  • Words: add, sub, big, little, true, false, alphabet names such as std, urlsafe, hex, zbase32, bitcoin, and none.
  • Key derivations compute byte parameters when the recipe is parsed: md5(...), sha1(...), sha256(...), sha384(...), sha512(...), cryptderivekey(hash, secret, length[, rc4|aes|3des]) (Windows CryptDeriveKey, including the 0x36/0x5C expansion used for AES and 3DES with MD5/SHA-1) and pbkdf2(hash, password, salt, iterations, length). Example: rc4(key=cryptderivekey(sha1, "secret", 16)).
  • References:
    • @0x401000:16 - 16 bytes read from the binary at that address (for keys and IVs stored in the sample);
    • data[0:16], data[-4:] - bytes taken from the step's own input and removed from it, for an IV, nonce or per-string key stored next to the ciphertext: aes_cbc_decrypt(key=hex:..., iv=data[0:16]) | pkcs7_unpad;
    • $arg2 (an integer parameter) and @$arg2:$arg3 / @$arg3:12 (bytes at the address passed in an argument) - values of the call's arguments, resolved separately for every call when decoding call sites: decrypt(buf, len, key) is decoded with xor_single(key=$arg2), rc4_str(p, n, keyptr, keylen) with rc4(key=@$arg2:$arg3).
Step Parameters (defaults) Description
xor_single key (0..255) XOR every byte with one key byte
xor_multi key (1..65536 bytes), offset=0 XOR with a repeating key; offset is the key position of the first byte
xor_rolling init, step (0..255) XOR byte i with (init + i * step) mod 256
xor_index offset=0 XOR byte i with (i + offset) mod 256
xor_chain_decrypt init=0 plain[i] = data[i] ^ data[i-1], with data[-1] = init
xor_chain_encrypt init=0 out[i] = data[i] ^ out[i-1]
xor_word key, width=4 (1/2/4/8), step=0, endian=little XOR with a word key that grows by step per word
add_sub key (0..255), op (add / sub) add or subtract a constant from every byte, mod 256
add_multi key (bytes), op=add, offset=0 add or subtract a repeating multi-byte key
rol_byte n (0..7) rotate every byte left
ror_byte n (0..7) rotate every byte right
not - bitwise NOT of every byte
reverse - reverse the byte order
slice start=0, end=none keep data[start:end] (Python slice semantics)
stride start=0, step=2 keep data[start::step], for example to drop interleaved bytes
rc4 key (1..256 bytes), drop=0 (up to 1048576) RC4; drop discards that many keystream bytes first
aes_ecb_decrypt / aes_ecb_encrypt key (16/24/32 bytes) AES-ECB, whole 16-byte blocks, no padding
aes_cbc_decrypt / aes_cbc_encrypt key, iv (16 bytes) AES-CBC, whole blocks, no padding
aes_cfb_decrypt / aes_cfb_encrypt key, iv, segment=128 (8 or 128) AES-CFB8 / CFB128, any length
aes_ofb key, iv AES-OFB, any length
aes_ctr key, nonce=hex: (0..16 bytes), counter=0, counter_endian=big AES-CTR, see below
chacha20 key (32 bytes), nonce (12, 8 or 24 bytes), counter=0, rounds=20 ChaCha20, XChaCha20 (24-byte nonce), ChaCha12/ChaCha8
salsa20 key (32 or 16 bytes), nonce (8 or 24 bytes), counter=0, rounds=20 Salsa20, XSalsa20 (24-byte nonce)
tea_decrypt / tea_encrypt key (16 bytes), rounds=32, delta=0x9e3779b9, endian=big, mode=ecb, iv, tail=error TEA in ECB or CBC mode
xtea_decrypt / xtea_encrypt as TEA XTEA in ECB or CBC mode
xxtea_decrypt / xxtea_encrypt key (16 bytes), rounds=0 (= 6 + 52/words), delta, endian=little XXTEA (Corrected Block TEA), the whole data as one block
base64_decode / base64_encode alphabet=std, pad="=" Base64 with any 64-character alphabet
base32_decode / base32_encode alphabet=std, pad="=" Base32 with any 32-character alphabet
base58_decode / base58_encode alphabet=bitcoin (flickr, ripple or 58 characters) Base58
base62_decode / base62_encode alphabet=std (inverted or 62 characters) Base62 as a big number
base85_decode / base85_encode - Base85 (RFC 1924 alphabet, as git and Python's b85)
ascii85_decode / ascii85_encode adobe=false (encode) Ascii85, with or without <~ ~>
z85_decode / z85_encode - Z85 (ZeroMQ)
base91_decode / base91_encode - basE91
hex_decode / hex_encode lenient=false (decode) hexadecimal text; lenient ignores 0x/\x prefixes and `, : ; - .
utf16_narrow / utf16_widen endian=little, strict=true UTF-16 code units to bytes and back (Base64 or hex stored as wchar_t)
unescape style=auto (percent, c, js) resolve %XX, \n \xHH \ooo and \uXXXX \u{...} escapes
zlib_decompress / zlib_compress format=auto (zlib, gzip, raw) Deflate; auto (decompress only) reads zlib and gzip by their headers and falls back to raw deflate (.NET DeflateStream, PHP gzdeflate)
lzma_decompress format=auto (xz, alone) LZMA / xz
bz2_decompress - bzip2
lznt1_decompress - LZNT1 (RtlDecompressBuffer)
pkcs7_unpad / pkcs7_pad block_size=16 PKCS#7 padding (1..255)
dsl program, key=hex: custom per-byte program, see below

Details:

  • AES-CTR: counter block j is nonce || (counter + j), the counter in counter_endian byte order in the remaining 16 - len(nonce) bytes and wrapping inside them. A 16-byte nonce is a complete initial counter block to which counter is added; all 128 bits are then incremented.
  • ChaCha20: a 12-byte nonce uses the RFC 8439 layout (32-bit block counter); an 8-byte nonce the original layout (64-bit counter); a 24-byte nonce is XChaCha20 (HChaCha20 subkey). rounds counts single rounds (20, 12 or 8). Data that would overflow the counter is rejected.
  • TEA/XTEA: rounds counts cycles as in the reference code; endian is the byte order of the key and data words (little for most x86 code, big for the usual published test vectors). tail=plain leaves a partial last block unchanged instead of failing.
  • Base64/Base32 decoding ignores ASCII whitespace and trailing NUL bytes; padding is optional, but if present it must be complete. Alphabets must be distinct printable ASCII characters and the padding character (or none, pad="") must not be in the alphabet.
  • Decompression stops at 16 MiB of output (no decompression bombs).
  • Block modes do not pad or unpad by themselves; add pkcs7_unpad after a decryption that needs it.

Most steps have an inverse (for example aes_cbc_decrypt and aes_cbc_encrypt), which the tests use to check that encrypting and then decrypting returns the input.

Per-byte programs (dsl step)

for each byte b: b = b ^ 0x55; b = (b - i) & 0xFF
  • Statements before the for each byte NAME: header run once; statements after it run for every input byte. Without a header the whole program is the per-byte part and the byte is b. The final value of the byte variable, masked to 8 bits, is the output byte.
  • Statements are separated by ; or new lines; # starts a comment:
    • assignments (=, +=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>=), also to mem[expr], a writable array of 65536 64-bit values kept from byte to byte;
    • if expr { ... } else { ... } (else if works);
    • repeat COUNT { ... } and repeat COUNT as k { ... } with a constant count (0..65536);
    • emit(expr) appends one more output byte and skip drops the current byte's output (both only after the header), so one input byte may give no, one or several output bytes.
  • Operators follow C precedence: unary - ~ ! +, * / %, + -, << >>, < <= > >=, == !=, &, ^, |. All values are unsigned 64-bit; arithmetic wraps, shifts by 64 or more give 0, comparisons give 0 or 1, division or modulo by zero is an error.
  • Read-only names: i (index), n (length), prev_in (previous input byte) and prev_out (last output byte), klen; arrays key[j] (the step's key, indexed modulo its length), data[j] (the input) and mem[j]. Other names are variables; they must be assigned before they are read and keep their values from byte to byte.
  • Functions: rol8 ror8 rol16 ror16 rol32 ror32 rol64 ror64 min max select, the arithmetic shifts sar8 sar16 sar32 sar64, the sign extensions sext8 sext16 sext32 and the signed comparisons slt sle sgt sge; select(c, a, b) evaluates only the chosen operand.
  • Literals: decimal, 0x, 0o, 0b, and character literals such as 'A' or '\x41'.

An RC4 variant with a custom key schedule, for example, fits in a few lines:

repeat 256 as k { mem[k] = k }
j = 0
repeat 256 as k { j = (j + mem[k] + key[k]) & 0xFF; t = mem[k]; mem[k] = mem[j]; mem[j] = t }
x = 0; y = 0
for each byte b:
  x = (x + 1) & 0xFF; y = (y + mem[x]) & 0xFF
  t = mem[x]; mem[x] = mem[y]; mem[y] = t
  b = b ^ mem[(mem[x] + mem[y]) & 0xFF]

Programs are tokenised, parsed and compiled into Python closures; nothing is passed to eval or exec. Source length (16384 characters), tokens (4096), nesting depth (48), statements (256) and variables (64) are limited. repeat counts are constants and if costs its dearer branch, so the cost of a run is known before it starts; runs needing more than 20,000,000 steps are rejected, and the output is limited to 16 MiB.

Plausibility score

Each result gets a score from 0 to 1. Trailing NUL bytes are ignored; UTF-16 text (little- or big-endian, mostly ASCII-range, or with its other characters from one writing system - Cyrillic, Greek, Arabic and other scripts of one Unicode block, Chinese and Japanese with Kanji and Kana mixed, or Korean Hangul) and UTF-8 text are decoded first. The score is the cube of the share of printable characters, times a mix of the share of letters and digits and a language credit: mostly how typical the character transitions are under a character bigram model trained on a built-in corpus of the strings programs hide (English messages, API, DLL, path, registry, URL, HTTP and command-line strings), plus English letter-frequency fit (Lewand's table) and the share of the 50 most common English bigrams (Norvig's counts). Chinese, Japanese and Korean text is rated by its share of common characters (the first-level Hanzi of GB 2312, the first-level Kanji of JIS X 0208, the frequent characters of Big5, the Hangul syllables of KS X 1001 and all Kana) and gains confidence with every character (two common characters score about 0.59, five or more about 0.9); letters of another non-Latin script get a fixed share of the credit. The score is reduced for transitions that read worse than typical strings, unknown words, characters repeating at a fixed distance (the trace of a wrong key byte on a constant column such as the zero high bytes of UTF-16), high byte entropy in long strings, control characters, a high density or variety of punctuation, unbalanced brackets, runs of very few distinct characters, the rarely used characters ~, ^, ` and |, many upper-case letters, upper-case letters wedged between a lower-case letter and a digit or symbol, digits scattered through words (hex strings are exempt from these), words mixing scripts, very short strings and non-ASCII UTF-8; UTF-16 Chinese, Japanese and Korean ranks a little below equally good Latin text. Known words (with CamelCase and lower-case identifiers split into words) and typical string tokens raise it: URL schemes, Windows paths and environment variables, registry roots, file extensions, module and API names, printf format specifiers, IPv4 addresses and words such as Mozilla or cmd.exe.

Text that a wrong single-byte key makes of ASCII UTF-16 - every unit sharing one byte, the other bytes reading as ASCII text under it - is not taken for Chinese, Cyrillic or another script, and 8-bit ASCII text is not read as UTF-16. UTF-16 Chinese and Japanese text whose every byte is below 0x80 (what ASCII text XOR an ASCII key gives) loses confidence with every ideograph from the third on, down to 0.4 times the score from six: only about one common ideograph in three has two such bytes. Some short strings are inherently ambiguous: Hiragana-only UTF-16 text whose every byte is printable ASCII is read as the 8-bit text it also is.

This is a heuristic. In the tests, known API names, paths, URLs, format strings, UTF-16 text and Cyrillic, Greek, Arabic, Chinese, Japanese and Korean text in UTF-16 and UTF-8 score above 0.5; random byte strings of 16 bytes and longer score below 0.5; at most 1% of the outputs of random wrong multi-byte XOR keys look plausible; the near misses a key search produces score below the true plaintext; and for single-byte XOR the right key gets the best score for the tested examples. Random byte strings shorter than 16 bytes are occasionally rated plausible (at most 5% of 4-byte strings and 0.2% of 8-byte strings in the tests), and short strings can be outranked by wrong keys that keep them printable, so the brute-force report lists several candidates.

Brute force

Family Keys tried
xor_single 1..255
add_sub subtract 1..255 (equivalent to every addition)
rol_byte 1..7 bits
not 1
xor_index offsets 0..255
xor_chain xor_chain_decrypt with init 0..255
xor_multi repeating XOR keys of 2 to stringDecoder.bruteForceMaxKeyLength bytes, solved (see below)
xor_rol / rol_xor XOR 1..255 combined with rotate 1..7 (1,785 keys each)
xor_add / add_xor XOR 1..255 combined with subtract 1..255 (65,025 keys each; slow)
xor_rolling init 0..255 x step 2..255 (65,024 keys; slow)

The brute-force dialogs choose the families (comma-separated), a recipe to run before the searched step (for example base64_decode) and one to run after it (for example pkcs7_unpad), the terminator and the number of candidates. Candidates are scored on the first 256 bytes, mostly unprintable outputs are skipped, duplicate outputs are dropped, and the best ones are decoded in full and scored again. With the auto terminator each candidate is scored both cut at a NUL byte and at a NUL UTF-16 unit, and the better cut counts, so XOR-encrypted UTF-16 strings are found.

xor_multi does not enumerate keys. For each key length it splits the data into columns that share a key byte and solves the key under two plaintext models: 8-bit text, and UTF-16LE text whose every second byte is zero (those bytes reveal their key bytes directly, so wide strings are solved as reliably as narrow ones). Each column keeps the key bytes that make it look most like text, and a dynamic program over the cycle of columns picks the combination with the most likely character transitions, so neighbouring key bytes are solved together. The best keys are scored, and the most promising ones - the best ranked and those of the two key lengths with the highest index of coincidence (Friedman's test) - are refined by the best single key-byte change while the score improves. A key length needs at least four encrypted bytes per key byte (a UTF-16 column with a high byte needs two), otherwise any key fits: a 12-byte API name under a 4-byte key, or a 40-byte string under a 9-byte key, has too few bytes per key byte to tell the key apart from others that also give text, and needs a crib (a known plaintext longer than the key fixes it whatever the length).

A longer key fits noise better, the more so the fewer bytes each key byte decodes, so xor_multi candidates are ranked by their score minus a penalty of 0.05 x fitted key bytes squared / decoded bytes. Key bytes the output pins down by itself - under zero UTF-16 high bytes, under a known plaintext, or decoding an encrypted terminator - are not fitted. The report shows the penalty and the value candidates are ranked by, so a candidate can rank above one with a higher score.

A known plaintext ("crib") is entered as text, encoded as UTF-8 or as UTF-16LE (for wide strings; the "Known plaintext encoding" choice), or as hex:... bytes. At a given byte offset it fixes key bytes directly; at an unknown offset it is searched when it is longer than the key. "Each string ends with an encrypted NUL byte" fixes the key byte of the last position. On an address inside a function with no single data reference, the bytes searched are the instruction's own; the report says so.

Brute-force strings passed to this function... reads the string of every call (as the decode command would) and scores each key on all of them, ranked by the mean or the lowest score; the key then has to make every string readable, which is far more reliable than one short string.

After the report, a question offers to decode and annotate with one of the best candidates or to save it as a profile (together with the string settings of the run). A candidate picked for one string is annotated even when it scores at or below the threshold, since it was chosen explicitly; a key picked for all calls of a decryptor asks first which results to annotate (plausible only, all, or preview). The search can be cancelled from the task bar; the report then shows the best candidates found so far.

String layouts and terminators

Layout Encoded string stored as
fixed exactly the given number of bytes
cstring bytes up to a NUL byte
wstring 16-bit units up to a NUL unit (aligned)
prefix8, prefix16le, prefix16be, prefix32le, prefix32be a length prefix, then the bytes
prefix32le_before the bytes, with a 32-bit length in the 4 bytes before the address (Delphi AnsiString)
delphi UTF-16, with a 32-bit character count before the address (Delphi UnicodeString)

Length prefixes and length arguments are multiplied by the length unit (2 for wchar_t counts, 4 for 32-bit units) and the length adjustment is added (for counts that include or exclude the terminator). A cstring or wstring that has no terminator within the maximum length is decoded with a "may be truncated" warning (and skipped with stringDecoder.skipTruncated).

The terminator cuts the decoded output, which handles strings whose terminator is encrypted with the text: nul at the first NUL byte, wnul at the first aligned NUL unit, none keeps everything, and auto (the default) cuts UTF-16 text at a NUL unit and other text at a NUL byte; for the wstring and delphi layouts auto always means wnul.

Call sites

For every call of the decryptor, String Decoder looks at the pointer argument (0 = first argument) with Binary Ninja's Function.get_parameter_at and, when that has no answer, the MLIL call: constant values and pointers, constant data, imported addresses, a single possible value, stack addresses and parameters of the caller. Calls through thunks (functions that only jump to the decryptor) count as calls of the decryptor. When a call inside a wrapper function passes the wrapper's own parameter, the calls of the wrapper are decoded instead (setting stringDecoder.followWrappers, two levels deep). When the argument points to a stack buffer filled by constant stores before the call (stack strings), the bytes are rebuilt from those MLIL stores (only a call-site comment is written, as the string has no address). The pointer argument choice also handles an argument that points to a pointer to the string, or to a {pointer, length} record. Calls whose arguments cannot be resolved are listed in the report as failed, with the reason.

Decode table lookups of this function... handles decryptors such as get_string(17) that look the string up in a table: the constant index argument selects the entry of a table of pointers, {pointer, length}, {length, pointer} or {offset, length} records (offsets count from the blob address), fixed-size records, or NUL / UTF-16 separated strings (separators in the encoded data, or encrypted with the text, in which case the whole blob is decoded first).

Every successful run stores the decryptor's settings in the database; Re-run bound decoders repeats them for all decryptors, for example after analysis found new calls.

Profiles

Profiles are stored in <Binary Ninja user directory>/string-decoder/profiles.json:

{
  "format": "string-decoder-profiles",
  "version": 2,
  "profiles": [
    {
      "name": "xor 55",
      "description": "single-byte XOR",
      "scoring_threshold": 0.6,
      "cipher_config": [{"name": "xor_single", "key": 85}],
      "layout": "cstring",
      "pointer_index": 0,
      "length_index": 1
    }
  ]
}

cipher_config lists the steps; byte parameters are hex strings, references keep their text form ("$arg2", "@0x401000:16", "data[0:16]") and every parameter is written out. The optional keys layout, terminator, max_length, pointer_index, length_index, length_unit, length_delta and indirect (none, pointer, ptr_len) say how the strings are stored and passed; a profile with them needs no further input when decoding call sites. Version 1 files are still read, and files are written as version 1 when no profile uses the new keys. Files are written atomically and read strictly: at most 4 MiB, nesting depth 32, 1024 profiles, number literals of 64 characters; duplicate keys, unknown keys, NaN/Infinity, duplicate names and invalid steps are rejected. A damaged profiles file is never overwritten; the profile commands report the error and the decode dialogs say that the saved profiles could not be read and continue with the recipe field.

Limits and performance

  • Pipeline data is limited to 16 MiB, recipes to 32 steps and 65536 characters, a selection read to 16 MiB and one string to 1 MiB; call-site decoding handles at most 100,000 call sites, string tables at most 100,000 entries (blobs of 1 MiB), Base58/Base62 64 KiB, and brute force 1 MiB of input.
  • The ciphers are pure Python. Measured with CPython 3.14 on the development machine, AES, ChaCha20 and TEA/XTEA run at roughly 0.5 to 1 MiB/s, RC4 at about 11 MiB/s and the example DSL program at about 2.5 MiB/s; XOR and Base64 are much faster. A brute force of the default families takes about 0.05 to 0.3 seconds for a short string, xor_multi about 0.1 to 1 second (a few seconds for the strings of 20 calls scored together); xor_add, add_xor and xor_rolling take seconds.
  • Malformed input (encoded text, recipes, programs, profiles, string layouts, tables) raises the plugin's own ParseError/CipherError, never IndexError, struct.error, RecursionError or MemoryError; every parser is fuzzed with 2,000 or more seeded inputs in the tests.

Verification

python -m pytest runs the test suite against a stand-in binaryninja package in tests/fake_binaryninja, so no Binary Ninja installation or licence is needed. It includes:

  • known-answer tests: RC4 (RFC 6229), AES S-box, key expansion and ciphers (FIPS-197 Appendices A to C), AES-CBC, CFB8, CFB128, OFB and CTR (NIST SP 800-38A), ChaCha20 (RFC 8439), ChaCha8/12 (draft-strombergson-chacha-test-vectors), HChaCha20 (draft-irtf-cfrg-xchacha), XChaCha20, Salsa20 and XSalsa20 (cross-checked with PyCryptodome and libsodium), TEA and XTEA (Bouncy Castle and Linux testmgr.h), XXTEA (published vectors), Base64/Base32/Base16 (RFC 4648), Base58, Z85 and basE91 reference examples, CryptDeriveKey and LZNT1 vectors produced by Windows itself, PBKDF2 (RFC 6070);
  • round trips: encrypt-then-decrypt for random pipelines, recipe format/parse, DSL source unparse/parse, profiles save/load, string layouts write/read, encodings;
  • differential tests: Base64/Base32/Base85 against Python's base64 module, an RC4 written in the DSL against rc4, and compiled DSL programs against an independent reference evaluator;
  • regression tests from the audit: brute force of an XOR-encrypted UTF-16 string, multi-byte XOR recovery on 8-bit and UTF-16 strings (alone and jointly), the true plaintext outscoring every output the solver chose, Chinese, Japanese and Korean scoring, patching and data types that keep the next encrypted string intact, near-miss outputs of wrong keys;
  • seeded fuzzing (2,000 or more inputs each) of every parser;
  • tests of the adapter and of every command against the fake API;
  • checks of the manifest, of the entry point loaded under a random package name, and static checks of the engineering rules (standard-library-only core, relative imports, no eval/exec, no network or subprocess modules, Python 3.10 syntax).

When a local Binary Ninja installation is found, tests/test_api_conformance.py also checks the API members the plugin uses, and the stand-in's signatures and enum values, against its Python sources (set BN_INSTALL_DIR to point at one; otherwise the module is skipped).

Requires Binary Ninja build 10601 or newer. Python 3.10, 3.11, 3.12 and 3.13 are supported (the tests also pass on 3.14).

License

MIT, Copyright (c) 2026 Kazuma Matsumoto. See LICENSE.

About

Binary Ninja plugin that decodes encrypted or encoded strings using cipher/encoding/decompression recipes (XOR, RC4, AES, ChaCha20, TEA, Base64, zlib...), with XOR key brute-forcing and decryptor call-site decoding

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages