Skip to content

Guess mode

For decoding multiple layers of codecs, codext features a guess mode relying on an Artificial Intelligence algorithm, the Breadth-First tree Search (BFS). For many cases, the default parameters are sufficient for guess-decoding things. But it may require parameters tuning.


Parameters

BFS stops when a given condition, in the form of a function applied to the decoded string at the current depth, is met. It returns two results: the decoded string and a tuple with the related encoding names in order of application.

The following parameters are tunable:

  • stop_func: can be a function or a regular expression to be matched (automatically converted to a function that uses the re module) ; by default, checks if all input characters are printable.
  • min_depth: the minimum depth for the tree search (allows to avoid a bit of overhead while checking the current decoded output at a depth with the stop function when we are sure it should not be the right result) ; by default 0.
  • max_depth: the maximum depth for the tree search ; by default 5.
  • include: the categories, codecs or encodings to be considered, as a single name, a list of names or a dictionary of lists of names per depth (from 0, -1 meaning any depth) ; by default, None, meaning all of them (very slow). A codec name (e.g. vigenere) selects the encodings tried by default for this codec (e.g. vigenere-key, vigenere-password and vigenere-secret), while an encoding name selects only itself, even when it is not tried by default (e.g. vigenere-rainbow, for a known key).
  • exclude: the categories, codecs or encodings not to be considered, in the same formats ; by default, None, meaning none of them.
  • found: a list or tuple of currently found encodings that can be used to save time if the first decoding steps are known ; by default, an empty tuple.
  • timeout: the maximum duration of the search, in seconds ; by default, None, meaning no limit.
  • max_nodes: the maximum number of expanded candidates, each expansion decoding a candidate with every considered encoding ; by default, None, meaning no limit.
  • beam: the number of best-ranked decodings of each candidate that are kept for the next depth ; by default, None, meaning all of them.
  • layers: a list of the first layers of encoding, in decoding order, each being an encoding name (a fixed layer, decoded with this encoding only, whatever its score), None (a guessed layer, among the included encodings) or a list of category, codec or encoding names (a guessed layer, among these encodings only) ; by default, None. The maximum depth is then at least the number of layers, the layers beyond them being guessed, and the solutions are only searched once every fixed layer is decoded (e.g. with [None, "base64"] and max_depth=3: a guessed layer, then Base64, then optionally another guessed layer). An unknown encoding raises a LookupError.

When the timeout or max_nodes bound is reached, the search stops and returns the results found so far. The search decodes and ranks each candidate only once, level by level, and expands a decoded output only once even when several chains of encodings lead to it (the best-ranked chain is kept).

The result is a dictionary of the decoded strings by tuple of encodings, in order of application.

A simple example for a 1-stage base64-encoded string:

>>> codext.guess("VGhpcyBpcyBhIHRlc3Q=")
{('base64',): 'This is a test'}

An example of a 2-stages base64- then base62-encoded string:

>>> codext.guess("CJG3Ix8bVcSRMLOqwDUg28aDsT7")
{('chaocipher',): 'NGH3Hb8tYyJWGEEseSOq28aTtS7'}

In the second example, we can see that the given encoded string is not decoded as expected. This is the case because the (default) stop condition is too broad and stops if all the characters of the output are printable. If we have a prior knowledge on what we should expect, we can input a simple string or a regex:

Default stop function

:::python
>>> codext.stopfunc.default.__name__
'...'

The output depends on whether you have a language detection backend library installed ; see section Natural Language Detection. If no such library is installed, the default function is "text".

>>> codext.guess("CJG3Ix8bVcSRMLOqwDUg28aDsT7", "test")
{('base62', 'base64'): 'This is a test'}

In this example, the string "test" is converted to a function that uses this string as regular expression. Instead of a string, we can also pass a function. For this purpose, standard stop functions are predefined. So, we can for instance use stopfunc.lang_en to stop when we find something that is English. Note that working this way gives lots of false positives if the text is very short like in the example case. That's why the include argument is used to only consider baseX codecs. This is also demonstrated in the next examples.

>>> codext.stopfunc._reload_lang("langdetect")
>>> codext.guess("CJG3Ix8bVcSRMLOqwDUg28aDsT7", codext.stopfunc.lang_en, include="base")
{('base62', 'base64'): 'This is a test'}

If we know the first encoding, we can set this in the found parameter to save time:

>>> codext.guess("CJG3Ix8bVcSRMLOqwDUg28aDsT7", "test", found=["base62"])
{('base62', 'base64'): 'This is a test'}

If we are sure that only base (which is a valid category) encodings are used, we can restrict the tree search using the include parameter to save time, or even give the encodings to be considered at each depth, while the exclude parameter removes some of them:

>>> codext.guess("CJG3Ix8bVcSRMLOqwDUg28aDsT7", "test", include="base")
{('base62', 'base64'): 'This is a test'}
>>> codext.guess("CJG3Ix8bVcSRMLOqwDUg28aDsT7", "test", include={0: ["base62"], 1: ["base64"]})
{('base62', 'base64'): 'This is a test'}
>>> codext.guess("CJG3Ix8bVcSRMLOqwDUg28aDsT7", "test", include="base", exclude="base62")
{}

When some layers are known but not the others, they can be set with the layers parameter, the other layers being guessed:

>>> codext.guess("CJG3Ix8bVcSRMLOqwDUg28aDsT7", "test", layers=[None, "base64"])
{('base62', 'base64'): 'This is a test'}
>>> codext.guess("CJG3Ix8bVcSRMLOqwDUg28aDsT7", "test", layers=[["base"], "base64"])
{('base62', 'base64'): 'This is a test'}

Another example of 2-stages encoded string:

>>> codext.guess("LSAuLi4uIC4uIC4uLiAvIC4uIC4uLiAvIC4tIC8gLSAuIC4uLiAt", "test")
{('base64', 'morse'): 'this is a test'}
>>> codext.guess("LSAuLi4uIC4uIC4uLiAvIC4uIC4uLiAvIC4tIC8gLSAuIC4uLiAt", "test", include=["base", "language"])
{('base64', 'morse'): 'this is a test'}

With the CLI tool, these parameters are given with the -i/--include and -e/--exclude options, the names being possibly prefixed with a depth (e.g. codext guess -i 0:base62 1:base64), while the bounds of the search are given with the -t/--timeout, -n/--max-nodes and -b/--beam options.

When multiple results are expected, stop and show arguments can be used respectively to avoid stopping while finding a result and to display the intermediate result.

Computation time

Note that, in the very last examples, the first call takes much longer than the second one but requires no knowledge about the possible categories of encodings.


Available Stop Functions

A few stop functions are predefined in the stopfunc submodule.

>>> import codext
>>> dir(codext.stopfunc)
['LANG_BACKEND', 'LANG_BACKENDS', ..., '_reload_lang', 'default', 'flag', ..., 'printables', 'regex', 'text', 'text_strict']

Currently, the following stop functions are provided:

  • flag: searches for the pattern "[Ff][Ll1][Aa4@][Gg9]" (either UTF-8 or UTF-16) or checks that the whole output has the shape of a flag (e.g. demo{z1gzag_f3nce}, see below)
  • lang_**: checks if the given lang is detected (note that it first checks if all characters are text ; see text hereafter)
  • printables: checks that every output character is in the set of printables
  • regex(pattern): takes one argument, the regular expression, for checking a string against the given pattern
  • text: checks for printables and an entropy less than 4.6 (empirically determined)
  • text_strict: checks for text and a textness of at least 0.5, hence rejects encoded-looking strings (e.g. Base64) that text accepts ; as the search then goes deeper, it is best used with a bound (e.g. timeout=60), while flags are better found with flag

A stop function can be used as the second argument of the guess function or as a keyword-argument, as shown in the following examples:

>>> codext.guess("...", codext.stopfunc.text)
[...]
>>> codext.guess("...", [...], stop_func=codext.stopfunc.text)
[...]

When a string is given, it is automatically converted to a regex stop function.

>>> s = codext.encode("pattern testing", "leetspeak")
>>> s
'p4773rn 73571n9'
>>> stop_func = codext.stopfunc.regex("p[a4@][t7]{2}[e3]rn")
>>> stop_func(s)
True
>>> codext.guess(s, stop_func)
[...]

Additionally, a simple stop function is predefined for CTF players, matching various declinations of the word flag or an output that has, as a whole, the shape of a flag: a prefix of letters or digits (holding at least two letters, e.g. CTF, picoCTF or demo), then braces around words separated by underscores, hyphens or dots, mostly made of letters once their leetspeak characters are replaced (e.g. z1gzag for zigzag) and consistently cased (lowercase, uppercase, capitalized or camel case), or of digits. This rejects e.g. a hash between braces, and a usual prefix that is still substituted (e.g. synt{...}, the ROT13 of flag{...}). Alternatively, a pattern can always be used when flags have a particular format.

>>> codext.stopfunc.flag("test string")
False
>>> codext.stopfunc.flag("test f1@9")
True
>>> codext.stopfunc.flag("demo{z1gzag_f3nce}")
True
>>> codext.stopfunc.regex(r"^CTF\{.*?\}$")("CTF{098f6bcd4621d373cade4e832627b4f6}")
True

The particular type of stop function lang_** is explained in the next section.


Natural Language Detection

As in many cases, we are trying to decode inputs to readable text, it is necessary to narrow the scope while searching for valid decoded outputs. As matching printables and even text (as defined here before as printables with an entropy of less than 4.6) is too broad for many cases, it may be very useful to apply natural language detection. In codext, this is done by relying on Natural Language Processing (NLP) backend libraries, loaded only if they were separately installed.

Currently, the following backends are supported, in order of precedence (this order was empirically determined by testing):

  • langid: Standalone Language Identification (LangID) tool.
  • langdetect: Port of Nakatani Shuyo's language-detection library (version from 03/03/2014) to Python.
  • pycld2: Python bindings for the Compact Langauge Detect 2 (CLD2).
  • cld3: Python bindings to the Compact Language Detector v3 (CLD3).
  • textblob: Python (2 and 3) library for processing textual data.

The way NLP is used is to check that these libraries exist and to take the first one by default. This sets up the stopfunc.default for the guess mode. This behavior aims to keep language detection as optional and to avoid multiple specific requirements having the same purpose.

While loaded, the default backend can be switched to another one by using the _reload_lang function:

>>> codext.stopfunc._reload_lang("pycld2")  # this loads pycld2 and attaches lang_** functions to the stopfunc submodule
>>> codext.stopfunc._reload_lang()          # this unloads any loaded backend

Each time a backend is loaded, it gets lang_** stop functions attached to the stopfunc submodule for each supported language.


Ranking Heuristic

At each step of the search, the candidate encodings are decoded and ranked with a score, the best ones being tried first. The score combines characteristics of the input compared to those expected by each codec (length of its charset, padding, whole quanta for the bases whose N is a power of 2, e.g. 4 characters for Base64, rate of printable characters, expansion factor and entropy, the padding being left out of these characteristics) and a characteristic of the decoded output: how much it looks like a text.

This "textness" depends on the script of the letters. For Latin letters, it is mainly given by the rate of common bigrams among the pairs of successive letters (around 70% for English texts, against around 15% for random letters ; most of these bigrams are also common in other Latin-script languages such as French, German, Spanish or Italian), weighted by the rate of printable characters, the rate of letters and spaces (at least 60% in a text), the number of distinct letters, the length of the words, the rate of tokens that are words or numbers (unlike e.g. a keyboard shift of an encoded string) the changes from a lowercase to an uppercase letter inside a word (rare in a text, they reveal e.g. a rotation of a text such as gsThe quick ... lazy do, and do not count as common bigrams) and the function words such as "the", "et" or "und" (a reversed text, which holds the same bigrams, holds reversed function words such as "eht" instead). For a short text (less than 64 letters), whose few bigrams can be matched by a wrong substitution of its letters (e.g. Ileeb Tbyem, a shift of Svool Dliow, itself the Atbash of Hello World), the frequency of its trigrams in English texts also weighs, all the more as the text is short, but only when they are rare (other languages and texts with uncommon words, e.g. The quick brown fox jumps over the lazy dog, still hold enough common trigrams). The rate of clean words also applies to a single word (e.g. unlike OU@NA@]C@RIeHReL@RXG), and the braces of a flag separate words (e.g. flag{this_is_a_flag}). As the few words of a flag, often in leetspeak, rate low, an output that has the shape of a flag (see the flag stop function) is rated at least 0.6, hence accepted by text_strict and favoured by the ranking ; its content is not rated, as its few letters cannot be told apart from a shift of them. For other scripts (e.g. Cyrillic, Greek, Arabic or CJK), it only relies on language-independent features: the rate of letters of the dominant script, the rate of letters, spaces and punctuation, and the length of the words (for the scripts that separate words with spaces). As these features cannot distinguish a text from a substitution of its characters, the outputs of such codecs are only rated from Latin letters. A bonus is given when the output looks like a text (textness above 0.5) and more than the input, which favours the right decoding over transformations that never fail (e.g. keyboard shifts) without favouring wrong decodings in a chain of encodings. Codecs whose decoding loses information but whose encoding of the output must give the input back (e.g. uppercase, lowercase, capitalize and title) are only considered for an input that they can produce, e.g. not for a mixed-case input as HeLLo WorLD (whose decodings by uppercase and lowercase would otherwise rank first, as they look like texts). Codecs that only substitute characters (e.g. rot, xor, kbshift) also get a penalty when their output looks less like a text than their input. For these codecs, the textness of the input and of the output is also weighted by how well their letters follow the letter frequencies of a text, compared with the other shifts of these letters and, for the output, with the shifts of the letters of the input, as for cracking a Caesar cipher. This tells a short text from a wrong shift of its letters that happens to hold more common bigrams (e.g. Owilha patp bkn w Ywaown Yeldan. against Sample text for a Caesar Cipher.), without penalising a text with uncommon letters, which is still the best-distributed of its shifts.

Work in progress

This part shall still be improved with better features and/or using machine learning. In particular, the default stop function (text) accepts any printable output with a low entropy, hence possibly an intermediate result of a chain of encodings ; text_strict avoids this at the cost of a deeper, hence longer, search.

Strength Evaluation

While the guess mode tries to reverse an unknown chain of codecs, the strength feature does the opposite: given a chain, it estimates how hard that chain is to reverse. It rates resistance to codext's own guessing heuristic and to casual recognition - not cryptographic strength.

It encodes a sample through the chain, then walks the true decoding path and, at each layer, uses the ranking heuristic (see above) to measure how high the correct codec is ranked. A layer ranked first is an obvious give-away ; a deeply-ranked or non-surfaced ("blind") layer, e.g. one whose codec opts out of guessing, cannot be greedily followed. It also flags an output that still looks like a text (a disguise) and a lossy chain (e.g. a hash) whose plaintext cannot be recovered at all.

The result is a score from 0 (trivially reversible) to 100 (resists the guesser) with a letter grade, the per-layer ranks and notes pointing at the weakest layer:

>>> codext.strength(["base64"])
{'chain': ['base64'], 'reversible': True, 'length': 1, 'score': 12, 'grade': 'F', 'blind_layers': 0,
 'worst_rank': 1, 'disguised': False, 'correct_ranks': [1],
 'notes': ['every layer is ranked first by the guesser: trivially peelable']}
>>> codext.strength(["gzip", "xor-173", "base64"])["grade"]
'C'

A compatible sample is chosen automatically ; a specific one can be given with the sample keyword-argument. The include/exclude arguments scope the codecs the guesser may use, exactly like for the guess mode. With the CLI tool, the chain is given as arguments and the sample is read from stdin or a file (a default is used otherwise): codext strength base64 gzip.

Not cryptographic strength

This measures resistance to codext's guessing/ranking and to casual inspection, not cryptographic security. The per-layer ranking is used on purpose instead of the full recursive guess, which is combinatorially expensive on some chains.

Chain Composition

The compose feature builds a strong chain of codecs from the answers to a few assessment questions, available as codext.compose.questions:

Question Choices Default
input: what will be encoded text, binary (any data) text
alphabet: characters the output may contain any, printable, alphanumeric, letters printable
expansion: how many times larger the output may be 2, 5, 20, any 5
layers: number of layers 2 to 5 3
disguise: whether the output shall look like text no, yes no
key: secret key for a keyed layer (letters only, at least 4) free none

The chain is built layer by layer: at each layer, codecs are tried in a random order on a few samples (as text and as bytes), keeping those that round-trip exactly on all of them and meet the constraints, preferably of a category not used yet (e.g. not two substitutions of bytes, which compose into a single one). Among these candidates, the one that the ranking heuristic ranks the lowest on its own output is selected, one that it does not surface at all being the best (e.g. a code page such as cp500, which the guesser never tries). When a key is given, a keyed cipher (autoclave, beaufort, columnar, porta, vernam or vigenere) with this key is inserted at a random layer, which the guesser cannot follow without the key. The chain is finally rated with the strength evaluation:

>>> r = codext.compose({'alphabet': "alphanumeric", 'key': "mysecret"}, seed=42)
>>> r['chain'], r['score'], r['grade'], r['expansion']
(['vernam-mysecret', 'binhex', 'octal'], 100, 'A', 4.81)
>>> codext.decode(codext.encode("A secret message", r['chain'][0]), r['chain'][0])
'A secret message'

The chain is drawn at random, so that it cannot be predicted from the answers, unless a seed is given (a same seed gives a same chain for a same set of available codecs, which depends on the version of codext and on the installed optional dependencies). The sample argument adds an input the chain must work with, on which the ranking, the expansion and the strength are then measured ; it should be representative of the inputs, as the guesser misses some codecs on short ones. The include/exclude arguments select the categories, codecs or encodings that may be used in the chain (by default, all but the lossy ones, i.e. checksums and hashes), while candidates sets the number of codecs compared at each layer (more is stronger but slower).

With the CLI tool, codext compose asks the questions that are not answered with an option (-b/--binary, -a/--alphabet, -x/--expansion, -l/--layers, -d/--disguise, -k/--key, the key being asked without echo), unless -n/--non-interactive is given or a sample is piped. It prints the chain with its strength and the commands to encode and decode with it, and -m NAME/--macro NAME saves it as a macro:

$ codext compose -a alphanumeric -k mysecret -s 42 -n -m mychain
chain: vernam-mysecret · binhex · octal
strength: 100/100  (A)
  layer ranks : [None, None, None]
  blind layers: 3 / 3
  expansion   : x4.81
  disguised   : True
  note        : layers the guesser cannot follow: vernam-mysecret, binhex, octal
  note        : the output still looks like text, which may evade casual notice
  note        : the chain holds the secret key ('vernam-mysecret') ; keep it secret
encode with: codext encode vernam-mysecret binhex octal
decode with: codext decode octal binhex vernam-mysecret
saved as macro 'mychain': codext encode mychain / codext decode mychain
$ echo -n "A secret message" | codext encode mychain | codext decode mychain
A secret message

Secret key

The key is part of the name of the keyed encoding (e.g. vernam-mysecret), hence of the chain: keep the chain secret, and note that a macro stores it in plain text in ~/.codext-macros.json.