TExcelTAD
Home › Reverse Engineering & Binary Analysis › A Crackme on the Course's Own Toy: Find the Check, Then Fix It

A Crackme on the Course's Own Toy: Find the Check, Then Fix It

A crackme is a small program written to be reverse engineered: it asks for a key, and the exercise is to find out what it accepts. CTFs and training sites use them because they combine everything in this course in one small target. Here the crackmes are the course's own toys, written in this lesson, and the exercise doesn't stop at "found it": the second half is the developer's side, how the check should have been written, because the lesson of every crackme is the same: a secret hidden in a program you give away is not a secret.

Scope. Both binaries are compiled from the source printed below, in your sandbox. The techniques are for your own programs and authorised assessments; using them to bypass the licence checks of software you don't own is a breach of its licence and, in many countries, of anti-circumvention law (introduction).

Level 1: a hard-coded key

The session writes the toy, compiles it, and then plays the analyst who only has the binary. Four tools, four ways to the same answer.

bash · try it yourself
cat > crackme1.c <<'SRC'
#include <stdio.h>
#include <string.h>
static int check_key(const char *k) { return strcmp(k, "TAD-LAB-4242") == 0; }
int main(int argc, char **argv) {
    if (argc < 2) { puts("usage: crackme1 KEY"); return 2; }
    if (check_key(argv[1])) { puts("access granted"); return 0; }
    puts("wrong key");
    return 1;
}
SRC
gcc -O1 crackme1.c -o crackme1 && strip crackme1
echo "== 1. strings: anything that looks like a key?"
strings -n 8 crackme1 | grep -E '^[A-Z0-9-]{8,}
  


echo "== 2. ltrace: what is the input compared with?"
ltrace -e strcmp ./crackme1 guess 2>&1 | grep strcmp
echo "== 3. objdump: the comparison in main (strcmp's second argument comes from .rodata)"
objdump -d -M intel --no-show-raw-insn crackme1 | grep -B3 'call.*<strcmp@plt>' | sed 's/^ *//'
objdump -s -j .rodata crackme1 | grep -i 'TAD'
echo "== 4. gdb: stop at that call and read both arguments"
call=$(objdump -d crackme1 | awk '/call.*<strcmp@plt>/{sub(":", "", $1); print $1}')
entry=$(readelf -h crackme1 | awk '/Entry/{print $4}')
main=$(objdump -d -M intel --start-address=$entry crackme1 | grep -m1 'lea *rdi' | grep -oP '# \K[0-9a-f]+')
echo "main at 0x$main, strcmp call at 0x$call (offset $((0x$call - 0x$main)) into main)"
gdb -q -batch -ex 'set breakpoint pending on' -ex 'break __libc_start_main' -ex 'run guess' -ex "tbreak *(\$rdi + $((0x$call - 0x$main)))" \
    -ex 'continue' -ex 'x/s $rdi' -ex 'x/s $rsi' ./crackme1 2>&1 | grep -E '^0x' | sed -E 's/^0x[0-9a-f]+:/ADDR:/'
echo "== confirm"
./crackme1 TAD-LAB-4242
== 1. strings: anything that looks like a key?
TAD-LAB-4242
== 2. ltrace: what is the input compared with?
crackme1->strcmp("guess", "TAD-LAB-4242")        = 19
== 3. objdump: the comparison in main (strcmp's second argument comes from .rodata)
1171:	jle    119e <strcmp@plt+0x12e>
1173:	mov    rdi,QWORD PTR [rsi+0x8]
1177:	lea    rsi,[rip+0xe9a]        # 2018 <strcmp@plt+0xfa8>
117e:	call   1070 <strcmp@plt>
 2010 6d653120 4b455900 5441442d 4c41422d  me1 KEY.TAD-LAB-
== 4. gdb: stop at that call and read both arguments
main at 0x1169, strcmp call at 0x117e (offset 21 into main)
ADDR:	"guess"
ADDR:	"TAD-LAB-4242"
== confirm
access granted

Every route leads to TAD-LAB-4242, and the first one took a single command. In the objdump route, the lea rsi, [rip+0xe9a] just before the call points to 0x2018, and the .rodata dump shows the key starting there, right after the usage message. The gdb route stops at the call itself rather than at strcmp. Because the binary is a stripped PIE, the call's run-time address is unknown before the program runs; the session takes main's address from the first argument of __libc_start_main (as in Decompilers) and adds the call's offset into main from the objdump listing. Breaking on strcmp directly is a poor choice: glibc's strcmp is an IFUNC (resolved at load time to a CPU-specific variant such as __strcmp_avx2), so a breakpoint on the name may land in the resolver or in another copy, and the dynamic loader compares names while it loads the program; stopping at the program's own call avoids all of that. At the call, x/s $rdi is the input and x/s $rsi the constant.

Level 2: the key is encoded

The author's next attempt hides the key: it is stored XOR-ed with 0x5A, and the check decodes each input character instead of calling strcmp. strings and ltrace now find nothing, so the analyst reads the code.

bash · try it yourself
python3 -c "print('static const unsigned char enc[12] = {' + ','.join(hex(b ^ 0x5A) for b in b'TAD-LAB-4242') + '};')" > enc.h
cat > crackme2.c <<'SRC'
#include <stdio.h>
#include <string.h>
#include "enc.h"
static int check_key(const char *k) {
    if (strlen(k) != sizeof enc) return 0;
    for (size_t i = 0; i < sizeof enc; i++)
        if (((unsigned char)k[i] ^ 0x5A) != enc[i]) return 0;
    return 1;
}
int main(int argc, char **argv) {
    if (argc < 2) { puts("usage: crackme2 KEY"); return 2; }
    puts(check_key(argv[1]) ? "access granted" : "wrong key");
    return 0;
}
SRC
gcc -O1 crackme2.c -o crackme2
echo "== strings and ltrace find nothing useful"
strings -n 8 crackme2 | grep -cE '^[A-Z0-9-]{8,}
  


ltrace -e strcmp ./crackme2 guess 2>&1 | grep -c strcmp
echo "== the loop: a length check, then XOR with 0x5a against a table"
objdump -d -M intel --no-show-raw-insn crackme2 | grep -E 'cmp +rax,0xc|xor +.*0x5a|movzx|lea +rcx,\[rip' | sed 's/^ *//' | head -5
echo "== the table at the address in the lea, and its decoding"
addr=$(nm crackme2 | awk '$3=="enc"{print $1}')
readelf -SW crackme2 | awk '$2==".rodata"{print "rodata: address 0x"$4", file offset 0x"$5}'
python3 - "$addr" <<'PY'
import sys
off = int(sys.argv[1], 16)          # .rodata's address equals its file offset in this PIE (checked above)
table = open("crackme2", "rb").read()[off:off + 12]
print("table:  ", table.hex(" "))
print("decoded:", bytes(b ^ 0x5A for b in table).decode())
PY
./crackme2 TAD-LAB-4242
== strings and ltrace find nothing useful
0
0
== the loop: a length check, then XOR with 0x5a against a table
1186:	cmp    rax,0xc
1191:	lea    rcx,[rip+0xea0]        # 2038 <enc>
1198:	movzx  edx,BYTE PTR [rbx+rax*1]
119c:	xor    edx,0x5a
11a8:	cmp    rax,0xc
== the table at the address in the lea, and its decoding
rodata: address 0x0000000000002000, file offset 0x002000
table:   0e 1b 1e 77 16 1b 18 77 6e 68 6e 68
decoded: TAD-LAB-4242
access granted

The encoding cost the analyst three more commands: the disassembly shows the length test against 12 (0xc), a xor with 0x5a, and a load from a table whose address the lea gives; reading 12 bytes there and XOR-ing them back yields the key. Encrypting the key properly (AES instead of XOR) wouldn't help either: the decryption key would have to be in the program too, and a breakpoint after decryption reads the plaintext from memory.

How such checks are detected in a review

  • Constants compared with input: a strcmp, memcmp or byte loop whose second operand is in .rodata; any secret-looking string in strings; an XOR loop over a small table next to a comparison.
  • A single branch decides everything: the check returns 0 or 1 and main branches on it, so patching one jne into je (or test eax, eax into xor eax, eax; inc eax) also "solves" the crackme without knowing the key. That is why client-side checks are called bypassable: the key isn't even needed.
  • Automated secret scanners (in CI, and the strings/entropy checks of Strings and Entropy) catch the level-1 case before release.

The fix: don't hard-code secrets, don't trust the client

There are two honest designs, depending on what the check protects.

  1. Decide on the server. If the feature or data lives on a server, the server checks the user's entitlement on every request. Patching the client gains nothing, because the client never had the data. This is the only design that resists a determined user.
  2. Signed licences when the program must work offline. The vendor signs a licence file (user, expiry, features) with a private key that never leaves the vendor; the program contains only the public key and verifies the signature. Reverse engineering the program reveals nothing that lets anyone make a new valid licence. (A user can still patch the verification out of their own copy; signing makes licences unforgeable, not the program unmodifiable, which is why design 1 is preferred where it fits.)

The example implements design 2 with Ed25519 (fixed seed for stable output; a real vendor key is random and kept in an HSM). It shows that the verifier holds only 32 public bytes, and what happens to an edited or forged licence.

python · try it yourself
import hashlib, base64
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey, Ed25519PublicKey
from cryptography.hazmat.primitives import serialization
from cryptography.exceptions import InvalidSignature

# --- vendor side (never shipped) ---
vendor_key = Ed25519PrivateKey.from_private_bytes(hashlib.sha256(b"lab-only vendor seed").digest())
def issue(text: str) -> str:
    return text + "|" + base64.b64encode(vendor_key.sign(text.encode())).decode()

# --- what ships inside the program: only the public key ---
PUBLIC = vendor_key.public_key().public_bytes(serialization.Encoding.Raw, serialization.PublicFormat.Raw)
print(f"public key embedded in the program: {len(PUBLIC)} bytes, {PUBLIC.hex()[:16]}...")

def check_licence(lic: str) -> str:
    text, _, sig = lic.rpartition("|")
    try:
        Ed25519PublicKey.from_public_bytes(PUBLIC).verify(base64.b64decode(sig), text.encode())
    except (InvalidSignature, ValueError):
        return "REJECTED (bad signature)"
    fields = dict(f.split("=", 1) for f in text.split(";"))
    if fields["exp"] < "2026-11-23":          # a fixed 'today' keeps the example stable
        return f"REJECTED (expired {fields['exp']})"
    return f"ok: user={fields['user']} features={fields['features']}"

good = issue("user=alice;exp=2027-06-30;features=basic")
old = issue("user=bob;exp=2025-01-31;features=basic")
edited = good.replace("features=basic", "features=pro")          # user edits their own licence
forged_key = Ed25519PrivateKey.from_private_bytes(bytes(32))
forged = "user=mallory;exp=2099-01-01;features=pro|" + base64.b64encode(
    forged_key.sign(b"user=mallory;exp=2099-01-01;features=pro")).decode()
for name, lic in [("alice", good), ("bob (old)", old), ("alice edited", edited), ("self-signed", forged)]:
    print(f"{name:<13} {check_licence(lic)}")
public key embedded in the program: 32 bytes, 78ab2ac7a7d65b8a...
alice         ok: user=alice features=basic
bob (old)     REJECTED (expired 2025-01-31)
alice edited  REJECTED (bad signature)
self-signed   REJECTED (bad signature)

Only the licence the vendor issued and that is still valid passes. Editing a field breaks the signature, and a licence signed with any other key fails, because the program knows only the vendor's public key. Running strings on such a program finds 32 bytes of public key, which are public by design.

Pitfalls

  • "Encrypting" the key in the client (XOR, AES, custom ciphers) only moves the secret one step further; the decryption key ships too.
  • Comparing hashes of the key (sha256(input) == stored) hides the key from strings but not from brute force if keys are short or structured, and the comparison branch is still patchable.
  • Leaving a debug bypass (if (getenv("DEV_UNLOCK"))) in release builds: strings finds the variable name in seconds.
  • Checking the licence once at start-up and storing "licensed = 1" in a global: one watchpoint or patch away from bypassed.

Practice

1. In level 1, name two ways to get "access granted" without knowing the key at all.

Patch the conditional jump after check_key (for example the je/jne on its result), or make check_key return 1 (in gdb: break at its return and set $rax = 1; in the file: replace its body by mov eax, 1; ret). Both work only on your own copy, which is the point: client-side checks protect nothing on a machine the user controls.

2. In level 2, how would you find the key if the binary were stripped and the table had no symbol?

Follow the lea reg, [rip+...] in the comparison loop: objdump's comment gives the table's address; dump 12 bytes from .rodata there. Or break in gdb at the xor and read the table through the register holding its address.

3. Why does the signed-licence design hold even though the public key is in the program?

Verifying needs only the public key; creating a valid signature needs the private key, which never leaves the vendor. Knowing the public key doesn't help forge signatures (that is the security property of Ed25519).

Test yourself

Which command found the level-1 key fastest?

  1. gdb
  2. strings
  3. objdump
  4. checksec

Why did XOR-encoding the key in level 2 not protect it?

  1. XOR is reversible and the key 0x5A and the table are both in the program
  2. Because strings decodes XOR
  3. Because ltrace shows XOR
  4. It did protect it

What does the program contain in the signed-licence design?

  1. The vendor's private key
  2. Only the vendor's public key
  3. A list of valid licences
  4. The user's password

What is the most robust place to enforce a paid feature?

  1. An obfuscated client check
  2. A server that checks entitlement on every request for data or services it provides
  3. An anti-debugging trick
  4. A packed binary