Перейти к основному содержимому
Crackmes, Keygenning & Constraint Solving with Z3
Урок 10 из 13

Crackmes, Keygenning & Constraint Solving with Z3

Extract input validation constraints from decompiled binaries and model them with Python Z3 BitVec variables to solve multi-equation crackmes and build keygens.

Продвинутый 34 мин Реверс-инжиниринг
Этого урока пока нет на выбранном языке — показана версия на другом языке. Перевод готовится.
Только в разрешённой среде — Описанные здесь приёмы применяются только в учебных лабораториях и в системах, которые принадлежат вам или на которые есть письменное разрешение.

Цели обучения

  • Distinguish between binary patching, single-input solving, and building a general keygen
  • Translate compiler-generated validation branches from Ghidra decompilation into formal equations
  • Model fixed-width integer arithmetic, bitwise operations, and ASCII bounds using Python Z3 BitVec
  • Identify common solver pitfalls such as signedness mismatches and missing input-domain constraints

Рекомендуется заранее: Assembly Basics: x86/x64 & ARM Control FlowStatic Analysis & Decompilation with Ghidra & IDA ConceptsDynamic Analysis & Debugging (GDB, ltrace, x64dbg)

#Why this matters

Modern binaries and reverse-engineering challenges rarely compare user input against a plaintext string stored in .rodata. Instead, validation routines run input bytes through chains of additions, XOR operations, shifts, and modular arithmetic before checking whether every condition holds. Trying to invert twenty coupled byte equations by hand is slow and error-prone, and brute-forcing even an 8-character ASCII key spans more than $10^{15}$ combinations.

Satisfiability Modulo Theories (SMT) solvers such as Z3 automate that inversion. Once you read the validation logic in Ghidra or a debugger, you express each branch as a constraint in Python and let the solver search for an assignment that satisfies all rules simultaneously. On the defensive side, seeing how quickly an SMT solver collapses complex arithmetic checks demonstrates why client-side equation validators cannot protect software licenses or secrets.

#From crackmes to keygens

A crackme is a benign practice program built specifically to test reverse-engineering skills. When analyzing a validator in a lab, you generally choose among three strategies depending on the goal:

Approach How it works Limitations
Binary patching Flip a conditional jump (JZ to JNZ) or force a return value Alters the executable; fails file integrity checks or remote verification
Single-input solving Find one input that satisfies every branch condition Solves one CTF challenge instance without describing the full valid space
Keygenning Capture the exact invariant and generate arbitrary valid inputs Requires understanding every branch, character constraint, and checksum

Patching changes the program rather than understanding its logic. Building a keygen proves you understand the underlying rules completely because your generator produces fresh inputs that pass the unmodified binary.

  1. DecompileInspect check_serial in Ghidra
  2. ExtractList length, range, and math rules
  3. ModelBuild BitVec constraints in Python Z3
  4. VerifyCheck sat status and test on lab binary

#Reading validation constraints in decompiled code

When you open a validator in Ghidra, compiler optimizations often disguise simple byte checks. A strlen loop may inline into repne scasb, division by a constant may appear as multiplication by a large magic number, and signed versus unsigned comparisons decide which x86 jump instruction (jl versus jb) is emitted.

Consider a clean four-character lab validator as shown in a decompiler:

c
int check_serial(const char *s) {
    if (strlen(s) != 4) return 0;
    uint8_t a = (uint8_t)s[0];
    uint8_t b = (uint8_t)s[1];
    uint8_t c = (uint8_t)s[2];
    uint8_t d = (uint8_t)s[3];

    if (a < 'A' || a > 'Z') return 0;
    if ((a ^ b) != 0x17) return 0;
    if ((uint32_t)(b + c) != 0x8f) return 0;
    if ((int32_t)(c * 2 - d) != 0x45) return 0;
    return ((a + b + c + d) % 5) == 0;
}

Before writing a solver script, list every implicit and explicit requirement in that function:

  1. Exact length: the input has 4 bytes with no embedded null byte (0x00), because strlen stops at the first zero.
  2. Domain bounds: byte a must lie in 'A'..'Z' (0x41..0x5a), and if you enter the serial via a terminal or fgets, bytes b, c, and d must also be printable ASCII (0x20..0x7e) without newlines (0x0a).
  3. Bit-width promotion: a ^ b operates on 8-bit values, while b + c and c * 2 - d are promoted to 32-bit integers before the comparison.

#Modeling bit-accurate constraints with Z3

Z3 provides two main numeric types for reverse engineering: Int and BitVec. Unbounded mathematical Int variables do not wrap at 8, 32, or 64 bits and do not support bitwise operators such as ^, &, |, <<, or >>. For binary analysis, almost always choose BitVec.

A BitVec('b0', 8) models an 8-bit byte with exact modulo-$2^8$ wrap-around. When a C expression widens a uint8_t to uint32_t before adding or multiplying, use z3.ZeroExt(24, byte_var) so that intermediate arithmetic does not overflow at 8 bits prematurely. Likewise, use z3.SignExt(24, byte_var) if the decompiled code loads a signed char (movsx).

python
import z3

s = z3.Solver()
raw = [z3.BitVec(f"b{i}", 8) for i in range(4)]

# Keep all characters within printable ASCII for terminal input
for ch in raw:
    s.add(z3.UGE(ch, 0x20), z3.ULE(ch, 0x7E))

# Explicit uppercase bound on raw[0]
s.add(z3.UGE(raw[0], ord("A")), z3.ULE(raw[0], ord("Z")))

# Widen to 32 bits to match C integer promotion rules
a, b, c, d = [z3.ZeroExt(24, ch) for ch in raw]

s.add((a ^ b) == 0x17)
s.add((b + c) == 0x8F)
s.add((c * 2 - d) == 0x45)
s.add(z3.URem(a + b + c + d, 5) == 0)

if s.check() == z3.sat:
    model = s.model()
    candidate = bytes(model[ch].as_long() for ch in raw)
    print("Status: sat, bytes generated:", len(candidate))

Notice two critical details in this script:

  • z3.UGE, z3.ULE, and z3.URem: Python's <, <=, %, and / operators on BitVec perform signed comparisons and signed division/remainder. Whenever C code uses uint8_t or uint32_t (unsigned comparisons such as jb/ja), use Z3's unsigned helpers (ULT, ULE, UGT, UGE, UDiv, URem).
  • Enumerating solutions for a keygen: If you want to check whether multiple valid keys exist, add a blocking clause s.add(z3.Or([ch != model[ch] for ch in raw])) inside a loop and re-run s.check(). If a second model exists, you can inspect the mathematical relationship across solutions and turn it into a fast generator without needing Z3 at runtime.
Checking solver satisfiability in the lab environment
$ python3 solve_serial.py
Status: sat, bytes generated: 4
$ ./lab_validator "$(python3 -c 'import solve_serial; ...')"
Access granted

#Common mistakes and defensive lessons

Analysts new to constraint solving frequently lose time to subtle modeling bugs rather than solver limits:

  • Using Int instead of BitVec: Int ignores 32-bit overflow and breaks bitwise XOR/masking checks, causing unsat or bogus solutions that fail in the real binary.
  • Forgetting signedness: Writing ch >= 0x20 on an 8-bit BitVec treats values 0x80..0xFF as negative numbers in Python, rejecting or accepting the wrong range. Always use z3.UGE / z3.ULE for unsigned bytes.
  • Omitting input-domain constraints: Without printable ASCII bounds or null-byte exclusions, Z3 often picks 0x00 or control characters that argv or fgets truncates.
  • Trying to symbolize the whole binary: Translating libc functions or I/O wrappers into constraints causes state explosion. Isolate only the pure validation routine.

From a defender's perspective, obfuscating arithmetic equations or adding extra XOR layers does not create cryptographic security. Any offline validator whose verification logic resides entirely inside the binary can be decompiled and inverted by an SMT solver. Whenever an application must enforce licensing, privilege boundaries, or challenge-response authentication, validate tokens on a trusted server or verify asymmetric signatures using a public key embedded in the binary.

#Summary

  • Crackmes train structural and mathematical analysis, whereas keygens capture the full input invariant rather than patching out checks.
  • Ghidra decompilation exposes length guards, byte promotions, and bitwise/arithmetic relations that map directly to formal constraints.
  • Use BitVec with ZeroExt/SignExt, explicit ASCII domain bounds, and unsigned operators (UGE, ULE, URem) to match compiled CPU behavior.
  • Client-side equation checks are invertible by SMT solvers; real authorization belongs on the server or behind asymmetric signatures.

Проверка знаний

Войдите, чтобы проходить тест, завершать уроки и сохранять прогресс. Войти в систему

Практика: проверьте свои знания