TExcelTAD
Home › Reverse Engineering & Binary Analysis › Mini Project: Analyse a Toy Binary End to End

Mini Project: Analyse a Toy Binary End to End

This project is the whole course on one target. You receive a stripped program, labsync, described by its "vendor" as "a file-integrity checker: it verifies a data file against a CRC in its configuration and logs the result". Your job is an end-to-end analysis as a professional would do it for an audit: triage, file format and protections, imports and strings, function discovery, control flow of the core function, behaviour in the lab, and a written report that says whether the description is complete and what the risks are.

Scope. labsync is the course's own toy. The session builds it from the source below and runs it only inside your sandbox, against files it creates; its one network attempt goes to 127.0.0.1, where nothing listens. For the full challenge, don't read the C source before you have written your report: treat the cat > labsync.c block as the "delivery" and look only at the analysis output.

Step 0 to 5: the analysis session

The session builds the target, prepares a configuration and a data file (as the vendor's documentation says), and then runs the analysis steps in order. Each step's output is labelled.

bash · try it yourself
cat > labsync.c <<'SRC'
#include <arpa/inet.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>
static const char API_TOKEN[] = "lab-token-7f3a91";
static const unsigned char HOST_ENC[] = {0x2, 0x1, 0x4, 0x1d, 0x3, 0x1d, 0x3, 0x1d, 0x2};
__attribute__((noinline)) static uint32_t crc32_buf(const unsigned char *p, size_t n) {
    uint32_t c = 0xFFFFFFFFu;
    for (size_t i = 0; i < n; i++) {
        c ^= p[i];
        for (int k = 0; k < 8; k++) c = (c >> 1) ^ (0xEDB88320u & -(c & 1));
    }
    return ~c;
}
__attribute__((noinline)) static int read_config(const char *path, char *data, size_t dlen, uint32_t *crc) {
    char line[128];
    FILE *f = fopen(path, "r");
    if (!f) return -1;
    while (fgets(line, sizeof line, f)) {
        line[strcspn(line, "\n")] = 0;
        if (strncmp(line, "data=", 5) == 0) snprintf(data, dlen, "%s", line + 5);
        else if (strncmp(line, "crc=", 4) == 0) *crc = (uint32_t)strtoul(line + 4, NULL, 16);
    }
    fclose(f);
    return 0;
}
__attribute__((noinline)) static int check_file(const char *path, uint32_t expected) {
    unsigned char buf[4096];
    FILE *f = fopen(path, "rb");
    if (!f) return 0;
    size_t n = fread(buf, 1, sizeof buf, f);
    fclose(f);
    return crc32_buf(buf, n) == expected;
}
__attribute__((noinline)) static void report(int ok) {
    FILE *log = fopen("labsync.log", "a");
    if (!log) return;
    fprintf(log, "status=%s\n", ok ? "ok" : "MISMATCH");
    fclose(log);
}
__attribute__((noinline)) static int phone_home(int ok) {
    char host[sizeof HOST_ENC + 1];
    for (size_t i = 0; i < sizeof HOST_ENC; i++) host[i] = (char)(HOST_ENC[i] ^ 0x33);
    host[sizeof HOST_ENC] = 0;
    int s = socket(AF_INET, SOCK_STREAM, 0);
    struct sockaddr_in a = { .sin_family = AF_INET, .sin_port = htons(8099) };
    inet_pton(AF_INET, host, &a.sin_addr);
    if (connect(s, (struct sockaddr *)&a, sizeof a) != 0) { close(s); return -1; }
    char msg[64];
    int len = snprintf(msg, sizeof msg, "token=%s status=%d\n", API_TOKEN, ok);
    send(s, msg, (size_t)len, 0);
    close(s);
    return 0;
}
int main(int argc, char **argv) {
    char data[64] = "";
    uint32_t expected = 0;
    if (read_config(argc > 1 ? argv[1] : "labsync.conf", data, sizeof data, &expected) != 0) {
        fputs("labsync: no config\n", stderr);
        return 2;
    }
    int ok = check_file(data, expected);
    report(ok);
    phone_home(ok);
    printf("labsync: %s %s\n", data, ok ? "ok" : "MISMATCH");
    return ok ? 0 : 1;
}
SRC
gcc -O1 labsync.c -o labsync && strip labsync && rm labsync.c
head -c 3000 /dev/zero | tr '\0' 'A' > payload.bin
printf 'data=payload.bin\ncrc=%08x\n' "$(python3 -c "import zlib; print(zlib.crc32(open('payload.bin','rb').read()))")" > labsync.conf

echo "== 1 triage"
file -b labsync | cut -d, -f1-2,4
echo "sha256 $(sha256sum labsync | cut -c1-16)...  size $(stat -c %s labsync)"
checksec --output=csv --file=labsync | cut -d, -f1-4
echo "== 2 imports"
nm -D labsync | awk '$1=="U"{print $2}' | sed 's/@.*//' | grep -v '^__' | sort | tr '\n' ' '; echo
echo "== 2 strings (interesting ones)"
strings -n 6 labsync | grep -E 'lab|token|status|MISMATCH|conf|%'
echo "== 3 functions (.eh_frame FDEs inside .text) and main's calls"
readelf --debug-dump=frames labsync | grep -oP 'pc=\K\S+' | while IFS=. read -r a _ b; do
  [ $((0x$a)) -ge $((0x1280)) ] && printf '  0x%x  %4d bytes\n' $((0x$a)) $((0x$b - 0x$a)); done
entry=$(readelf -h labsync | awk '/Entry/{print $4}')
main=$(objdump -d -M intel --start-address=$entry labsync | grep -m1 'lea *rdi' | grep -oP '# \K[0-9a-f]+')
echo "  entry $entry, main 0x$main; calls in main:"
objdump -d -M intel --no-show-raw-insn --start-address=0x$main labsync | grep -m8 'call' | sed -E 's/^ *([0-9a-f]+):\s+call\s+([0-9a-f]+) <(.*)>/    at 0x\1 -> 0x\2 \3/'
echo "== 4 the function at 0x1369, and a constant in the one at 0x15e0"
objdump -d -M intel --no-show-raw-insn --start-address=0x1369 --stop-address=0x13ae labsync | grep -E '^\s+[0-9a-f]+:' | sed 's/^ *//'
objdump -d -M intel --no-show-raw-insn --start-address=0x15e0 --stop-address=0x1700 labsync | grep -E 'xor +edx,0x33' | sed 's/^ *//'
echo "== 5 behaviour in the sandbox"
strace -o trace.txt -e trace=openat,read,write,connect ./labsync; echo "exit code: $?"
grep -vE 'ld.so|libc.so|832\)' trace.txt
cat labsync.log
== 1 triage
ELF 64-bit LSB pie executable, x86-64, dynamically linked
sha256 8bf44794d786b33d...  size 14472
Full RELRO,Canary found,NX enabled,PIE enabled
== 2 imports
close connect fclose fgets fopen fread fwrite inet_pton send snprintf socket strcspn strncmp strtoul
== 2 strings (interesting ones)
MISMATCH
labsync.log
status=%s
token=%s status=%d
labsync.conf
labsync: no config
labsync: %s %s
lab-token-7f3a91
== 3 functions (.eh_frame FDEs inside .text) and main's calls
  0x1280    38 bytes
  0x1369    69 bytes
  0x13ae   305 bytes
  0x14df   162 bytes
  0x1581    95 bytes
  0x15e0   288 bytes
  0x1700   295 bytes
  entry 0x1280, main 0x1700; calls in main:
    at 0x178a -> 0x13ae socket@plt+0x13e
    at 0x179c -> 0x14df socket@plt+0x26f
    at 0x17a5 -> 0x1581 socket@plt+0x311
    at 0x17ac -> 0x15e0 socket@plt+0x370
    at 0x17db -> 0x1210 __printf_chk@plt
    at 0x1816 -> 0x1250 fwrite@plt
    at 0x1822 -> 0x11a0 __stack_chk_fail@plt
== 4 the function at 0x1369, and a constant in the one at 0x15e0
1369:	test   rsi,rsi
136c:	je     13a6 <socket@plt+0x136>
136e:	mov    r8,rdi
1371:	add    rsi,rdi
1374:	mov    eax,0xffffffff
1379:	jmp    1384 <socket@plt+0x114>
137b:	add    r8,0x1
137f:	cmp    r8,rsi
1382:	je     13ab <socket@plt+0x13b>
1384:	movzx  edx,BYTE PTR [r8]
1388:	xor    eax,edx
138a:	mov    edx,0x8
138f:	mov    ecx,eax
1391:	shr    ecx,1
1393:	and    eax,0x1
1396:	neg    eax
1398:	and    eax,0xedb88320
139d:	xor    eax,ecx
139f:	sub    edx,0x1
13a2:	jne    138f <socket@plt+0x11f>
13a4:	jmp    137b <socket@plt+0x10b>
13a6:	mov    eax,0xffffffff
13ab:	not    eax
13ad:	ret
1608:	xor    edx,0x33
== 5 behaviour in the sandbox
labsync: payload.bin ok
exit code: 0
openat(AT_FDCWD, "labsync.conf", O_RDONLY) = 3
read(3, "data=payload.bin\ncrc=93aaf669\n", 4096) = 30
read(3, "", 4096)                       = 0
openat(AT_FDCWD, "payload.bin", O_RDONLY) = 3
read(3, "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"..., 4096) = 3000
read(3, "", 4096)                       = 0
openat(AT_FDCWD, "labsync.log", O_WRONLY|O_CREAT|O_APPEND, 0666) = 3
write(3, "status=ok\n", 10)             = 10
connect(3, {sa_family=AF_INET, sin_port=htons(8099), sin_addr=inet_addr("127.0.0.1")}, 16) = -1 ECONNREFUSED (Connection refused)
write(1, "labsync: payload.bin ok\n", 24) = 24
+++ exited with 0 +++
status=ok

Step 4b: the control-flow graph of the core function

The listing of the function at 0x1369 is pasted into the CFG builder from Recovering Control Flow (condensed here).

python · try it yourself
import re
import networkx as nx

LISTING = """\
1369:	test   rsi,rsi
136c:	je     13a6
136e:	mov    r8,rdi
1371:	add    rsi,rdi
1374:	mov    eax,0xffffffff
1379:	jmp    1384
137b:	add    r8,0x1
137f:	cmp    r8,rsi
1382:	je     13ab
1384:	movzx  edx,BYTE PTR [r8]
1388:	xor    eax,edx
138a:	mov    edx,0x8
138f:	mov    ecx,eax
1391:	shr    ecx,1
1393:	and    eax,0x1
1396:	neg    eax
1398:	and    eax,0xedb88320
139d:	xor    eax,ecx
139f:	sub    edx,0x1
13a2:	jne    138f
13a4:	jmp    137b
13a6:	mov    eax,0xffffffff
13ab:	not    eax
13ad:	ret"""

insns = [(int(a, 16), *(t.split(None, 1) + [""])[:2]) for a, t in (l.split(":", 1) for l in LISTING.splitlines())]
tgt = lambda ops: int(ops, 16) if re.fullmatch(r"[0-9a-f]+", ops.strip()) else None
leaders = {insns[0][0]}
for k, (a, m, ops) in enumerate(insns):
    if m.startswith("j") or m == "ret":
        if tgt(ops) is not None: leaders.add(tgt(ops))
        if k + 1 < len(insns): leaders.add(insns[k + 1][0])
starts = sorted(leaders)
block_of = {}
for a, m, ops in insns:
    cur = a if a in leaders else cur
    block_of.setdefault(cur, []).append((a, m, ops))
G = nx.DiGraph()
for i, b in enumerate(starts):
    G.add_node(b)
    a, m, ops = block_of[b][-1]
    nxt = starts[i + 1] if i + 1 < len(starts) else None
    if m.startswith("j"):
        G.add_edge(b, tgt(ops))
        if m != "jmp" and nxt: G.add_edge(b, nxt)
    elif m != "ret" and nxt:
        G.add_edge(b, nxt)
idom = nx.immediate_dominators(G, starts[0])
def dom(d, b):
    while b != d and idom[b] != b: b = idom[b]
    return b == d
print(f"{G.number_of_nodes()} blocks, {G.number_of_edges()} edges, M = {G.number_of_edges() - G.number_of_nodes() + 2}")
for b, h in G.edges:
    if dom(h, b):
        print(f"loop: back edge {b:#x} -> {h:#x}")
consts = sorted({o.split(",")[1] for _, m, o in insns if "," in o and o.split(",")[1].startswith("0x")})
print("constants:", consts)
8 blocks, 10 edges, M = 4
loop: back edge 0x137b -> 0x1384
loop: back edge 0x138f -> 0x138f
constants: ['0x1', '0x8', '0xedb88320', '0xffffffff']

Step 6: the report

Write the report before opening the model answer. The template is the one from What Reverse Engineering Is For, extended for an audit.

text
ANALYSIS REPORT: <file name>
Analyst / date / scope:      <who, when, what was authorised, lab environment>
Sample:                      SHA-256, size, file type, architecture
Summary (3 sentences):       what it is, what it does, the main risks

1. Triage and format         type, linking, protections (PIE, NX, canary, RELRO), stripped?
2. Capabilities              imports grouped by capability; interesting strings
3. Structure                 functions found (address, size, role), call graph from main
4. Core logic                key functions explained with evidence (addresses, listing lines, CFG)
5. Behaviour (lab)           files read/written, processes, network attempts, with the trace lines
6. Findings                  each: title, severity, evidence, impact, recommendation
7. Indicators                hashes, file names, strings, network destinations
8. Comparison with the vendor description
9. Limitations               what was not analysed and why
Model answer (abridged)

Scope: labsync, the course's toy, analysed in the sandbox (no network; one connection attempt to 127.0.0.1:8099 refused).

Summary. labsync is a 64-bit PIE for x86-64 Linux, stripped, with full hardening. It does what the vendor says (reads labsync.conf, computes a CRC-32 of the data file, compares it with the configured value, appends status=ok or status=MISMATCH to labsync.log), and one undocumented thing: after each run it connects to TCP port 8099 on a host whose address is stored XOR-encoded, and would send a hard-coded API token with the result.

  1. Triage: ELF 64-bit PIE, dynamically linked, stripped; Full RELRO, canary, NX, PIE.
  2. Capabilities: file I/O (fopen, fgets, fread, fwrite, fclose, plus the fortified __fprintf_chk and __printf_chk that the session's filter on __ names hides), configuration parsing (strncmp, strcspn, strtoul, snprintf), network client (socket, inet_pton, connect, send). Strings: labsync.conf, labsync.log, status=%s, MISMATCH, token=%s status=%d, lab-token-7f3a91.
  3. Structure: six functions in .text after _start (from .eh_frame): 0x1369 (69 bytes), 0x13ae (305), 0x14df (162), 0x1581 (95), 0x15e0 (288), main at 0x1700. main calls 0x13ae (reads the configuration: fopen + fgets loop with strncmp on data= and crc=), 0x14df (opens and reads the data file, calls 0x1369), 0x1581 (appends the status line to the log), 0x15e0 (network), then printf.
  4. Core logic: 0x1369 is CRC-32: two nested loops (inner loop of 8 iterations, mov edx, 0x8 ... sub edx, 1 / jne), initial value 0xffffffff, final not, and the reflected polynomial 0xedb88320 (the CFG step shows 2 back edges, M = 4). Confirmed: the configured crc= (computed with zlib.crc32) matched and the program reported ok. 0x15e0 decodes a 9-byte table with xor edx, 0x33 into a host string, passes it to inet_pton, and connects to port 8099 (htons(8099)).
  5. Behaviour: openat("labsync.conf"), read of the two lines, openat("payload.bin"), read 3000 bytes, openat("labsync.log", O_APPEND), write("status=ok\n"), connect(127.0.0.1:8099) = -1 ECONNREFUSED, then the summary on stdout; exit code 0.
  6. Findings:
    • High: undocumented network transmission. The tool contacts a remote service after every run and, if the connection succeeds, sends token=<API token> status=<result>. Not in the description. Recommendation: vendor must document or remove it; block egress until clarified.
    • High: hard-coded credential. lab-token-7f3a91 is in the binary's strings and would be sent in cleartext (plain TCP). Anyone with the file has the token. Recommendation: per-installation credentials from a protected configuration, TLS, rotate the token.
    • Medium: obfuscated destination. The host address is XOR-encoded, which hides it from string searches; benign software rarely needs this. Recommendation: ask the vendor why.
    • Low: weak integrity check. CRC-32 detects accidental corruption, not tampering: anyone can craft a file with any chosen CRC. Recommendation: use SHA-256 with the expected hash in a protected or signed configuration, or a signature (Code Signing).
    • Info: reads only the first 4096 bytes of the data file (fread(..., 4096)), so changes after that offset go unnoticed (from the code; the trace's 4096-byte read requests are consistent with it, but 4096 is also stdio's buffer size, so the trace alone doesn't prove it).
  7. Indicators: file names labsync.conf, labsync.log; string lab-token-7f3a91; TCP 8099 to the decoded host (127.0.0.1 in this build).
  8. Versus the description: accurate for the integrity check; incomplete (network transmission of a credential), and the integrity method is weaker than "integrity checker" suggests.
  9. Limitations: no successful network exchange observed (no listener in the sandbox); only one configuration tested; behaviour with files over 4096 bytes inferred from the code, not tested.

Going further

  • Add a listener on 127.0.0.1:8099 in the session (ncat -l 127.0.0.1 8099 > received.txt &, then a bounded wait before running labsync) and confirm exactly what is sent. The message only travels inside your sandbox.
  • Write a YARA rule for the sample from your indicators (the token string, the XOR loop's bytes), in the style of Recognising Library Code.
  • Rewrite the program's integrity check with SHA-256 and a signed configuration, and show that your fixed version passes your own review.

Test yourself

Which finding was NOT visible from the vendor's description?

  1. It reads labsync.conf
  2. It computes a CRC-32
  3. It connects to TCP port 8099 and would send a hard-coded token
  4. It writes labsync.log

Which evidence identified the function at 0x1369 as CRC-32?

  1. Its name
  2. The constant 0xedb88320, the 8-iteration inner loop, the initial 0xffffffff and the final not, confirmed by matching zlib.crc32
  3. Its size
  4. It is called by main

Why is CRC-32 a weak choice for an integrity checker against tampering?

  1. It is slow
  2. It is not cryptographic: anyone can construct a file with a chosen CRC
  3. It needs a key
  4. It only works on text

How was the network destination hidden from strings?

  1. It wasn't in the program
  2. It was stored XOR-encoded with 0x33 and decoded at run time
  3. It was compressed
  4. It was in the overlay