CPP
We have this program's source code, but it uses a strange DRM solution. Can you crack it?
We are provided with the following 6234-line source code:
cpp.c
76KB
Binary
cpp.c
Essentially, the flag is checked through a bunch of #define and #ifdef statements in the source code. Compiling the code gives the following output:
The way it works is that you define your flag here:
1
#if __INCLUDE_LEVEL__ == 0
2
// Please type the flag:
3
#define FLAG_0 CHAR_C
4
#define FLAG_1 CHAR_T
5
#define FLAG_2 CHAR_F
6
#define FLAG_3 CHAR_LBRACE
7
#define FLAG_4 CHAR_w
8
#define FLAG_5 CHAR_r
9
#define FLAG_6 CHAR_i
10
#define FLAG_7 CHAR_t
11
#define FLAG_8 CHAR_e
12
#define FLAG_9 CHAR_UNDERSCORE
13
#define FLAG_10 CHAR_f
14
#define FLAG_11 CHAR_l
15
#define FLAG_12 CHAR_a
16
#define FLAG_13 CHAR_g
17
#define FLAG_14 CHAR_UNDERSCORE
18
#define FLAG_15 CHAR_h
19
#define FLAG_16 CHAR_e
20
#define FLAG_17 CHAR_r
21
#define FLAG_18 CHAR_e
22
#define FLAG_19 CHAR_UNDERSCORE
23
#define FLAG_20 CHAR_p
24
#define FLAG_21 CHAR_l
25
#define FLAG_22 CHAR_e
26
#define FLAG_23 CHAR_a
27
#define FLAG_24 CHAR_s
28
#define FLAG_25 CHAR_e
29
#define FLAG_26 CHAR_RBRACE
Copied!
and the following preprocessor directives determine whether the flag is valid.

Analysis (Part 1)

Looking through the code, here are some findings. First, the ROM_x_y macros represent the bits of each flag character.
ROM_x_y is the
yy
-th bit of the flag character
Fxβˆ’128F_{x-128}
, where
xx
is in binary.
1
#if FLAG_0 & (1<<0)
2
#define ROM_10000000_0 1
3
#else
4
#define ROM_10000000_0 0
5
#endif
6
​
7
...
8
​
9
#if FLAG_1 & (1<<0)
10
#define ROM_10000001_0 1
11
#else
12
#define ROM_10000001_0 0
13
#endif
14
​
15
...
Copied!
Next,
  • LD(x, y) means ROM_ ## x ## _ ## y (concatenate)
  • l means l7 ## l6 ## l5 ## l4 ## l3 ## l2 ## l1 ## l0 (concatenate)
1
#define _LD(x, y) ROM_ ## x ## _ ## y
2
#define LD(x, y) _LD(x, y)
3
#define _MA(l0, l1, l2, l3, l4, l5, l6, l7) l7 ## l6 ## l5 ## l4 ## l3 ## l2 ## l1 ## l0
4
#define MA(l0, l1, l2, l3, l4, l5, l6, l7) _MA(l0, l1, l2, l3, l4, l5, l6, l7)
5
#define l MA(l0, l1, l2, l3, l4, l5, l6, l7)
Copied!
Subsequently, LD(l, y) is used to check whether the flag characters are valid. The first example of this is after if S == 34 (line 4229).
First, the bits l0 to l7 are set, where lx is the x-th bit. Together, l7 l6 ... l0 form the x (flag index) in ROM_x_y.
1
#ifdef B0
2
#define l0 1
3
#else
4
#define l0 0
5
#endif
6
​
7
...
8
​
9
#ifdef B7
10
#define l7 1
11
#else
12
#define l7 0
13
#endif
Copied!
Then, LD(l, y) is used to check the y-th bit of the flag character.
1
#if LD(l, 0)
2
#define A0
3
#else
4
#undef A0
5
#endif
6
​
7
...
8
​
9
#if LD(l, 7)
10
#define A7
11
#else
12
#undef A7
13
#endif
Copied!
Finally, note that all of this only happens when __INCLUDE_LEVEL__ > 12. Before that, it recursively includes itself. Note the definition of the pre-defined __INCLUDE_LEVEL__ macro:
This macro expands to a decimal integer constant that represents the depth of nesting in include files. The value of this macro is incremented on every β€˜#include’ directive and decremented at the end of every included file. It starts out at 0, its value within the base file specified on the command line.
The following else statement corresponds to the previous if __INCLUDE_LEVEL__ > 12 which, if passed, checks the flag.
1
#else
2
#if S != -1
3
#include "cpp.c"
4
#endif
5
#if S != -1
6
#include "cpp.c"
7
#endif
8
#endif
Copied!
Before the __INCLUDE_LEVEL__ goes to 13, it recursively includes itself.

Converting to Python Code

In an attempt to make the code more readable and to analyse the checking of the flag, I wrote a script to convert the preprocessor directives to Python code.
1
with open("cpp.c", 'r') as infile, open("converted.py", 'w') as outfile:
2
line = infile.readline()[:-1]
3
4
curr_indent = 0
5
6
while line != '#include <stdio.h>':
7
8
if line.startswith('//'):
9
line = infile.readline()[:-1]
10
continue
11
12
if line.startswith('#define'):
13
line_data = line.split()
14
if len(line_data) == 3:
15
outfile.write(f"{curr_indent * ' '}{line_data[1]} = {line_data[2]}\n")
16
17
else:
18
outfile.write(f"{curr_indent * ' '}{line_data[1]} = None\n")
19
20
elif line.startswith('#ifdef'):
21
outfile.write(f"{curr_indent * ' '}if '{line.split()[1]}' in locals() or '{line.split()[1]}' in globals():\n")
22
curr_indent += 4
23
24
elif line.startswith('#ifndef'):
25
outfile.write(f"{curr_indent * ' '}if '{line.split()[1]}' not in locals() and '{line.split()[1]}' not in globals():\n")
26
curr_indent += 4
27
28
elif line.startswith('#undef'):
29
outfile.write(f"{curr_indent * ' '}if '{line.split()[1]}' in locals() or '{line.split()[1]}' in globals():\n")
30
outfile.write(f"{(curr_indent + 4) * ' '}del {line.split()[1]}\n")
31
32
elif line.startswith('#if'):
33
outfile.write(f"{curr_indent * ' '}{line[1:]}:\n")
34
curr_indent += 4
35
36
elif line.startswith('#else'):
37
outfile.write(f"{(curr_indent - 4) * ' '}else:\n")
38
39
elif line.startswith('#endif'):
40
curr_indent -= 4
41
42
elif line.startswith('#error'):
43
outfile.write(f"{curr_indent * ' '}print({' '.join(line.split()[1:])})\n")
44
45
else:
46
print(line)
47
48
line = infile.readline()[:-1]
Copied!
The result is something like this:
1
S = 0
2
​
3
if INCLUDE_LEVEL > 12:
4
​
5
if S == 0:
6
if 'S' in locals() or 'S' in globals():
7
del S
8
S = 1
9
if 'S' in locals() or 'S' in globals():
10
del S
11
S = 24
12
if S == 1:
13
if 'S' in locals() or 'S' in globals():
14
del S
15
S = 2
16
if 'R0' in locals() or 'R0' in globals():
17
if 'R0' in locals() or 'R0' in globals():
18
del R0
19
else:
20
R0 = None
21
if 'R1' in locals() or 'R1' in globals():
22
if 'R1' in locals() or 'R1' in globals():
23
del R1
24
25
...
26
​
27
else:
28
if S != -1:
29
INCLUDE_LEVEL += 1
30
exec(open('include.py').read())
31
INCLUDE_LEVEL -= 1
32
if S != -1:
33
INCLUDE_LEVEL+= 1
34
exec(open('include.py').read())
35
INCLUDE_LEVEL -= 1
Copied!
This is Python code that performs the same checking functionality as the preprocessor directives. This works by replacing ifdef and ifndef with checking whether the variable exists, which is basically the same thing!
For LD(x, y), we can define the following function which accepts l as an array of [l7, l6, ..., l0]:
1
def LD(l, n):
2
return eval(f"ROM_{''.join([str(x) for x in l])}_{n}")
Copied!

Analysis (Part 2)

After some dynamic analysis, I found that the code essentially checks each character of the flag one by one, starting from index 0. The value of S follows a predictable sequence for the checking of the first few characters, then goes to S = 56 before the program says INVALID_FLAG.
Let's inspect this part of the code then.
1
if S == 56:
2
print(S)
3
if 'S' in locals() or 'S' in globals():
4
del S
5
S = 57
6
if 'Q0' not in locals() and 'Q0' not in globals():
7
if 'Q1' not in locals() and 'Q1' not in globals():
8
if 'Q2' not in locals() and 'Q2' not in globals():
9
if 'Q3' not in locals() and 'Q3' not in globals():
10
if 'Q4' not in locals() and 'Q4' not in globals():
11
if 'Q5' not in locals() and 'Q5' not in globals():
12
if 'Q6' not in locals() and 'Q6' not in globals():
13
if 'Q7' not in locals() and 'Q7' not in globals():
14
if 'S' in locals() or 'S' in globals():
15
del S
16
S = 58
17
if S == 57:
18
if 'S' in locals() or 'S' in globals():
19
del S
20
S = 58
21
print("INVALID_FLAG")
22
if S == 58:
23
if 'S' in locals() or 'S' in globals():
24
del S
25
S = 59
26
if 'S' in locals() or 'S' in globals():
27
del S
28
S = -1
Copied!
At S = 56, if any of Q0 to Q7 is defined, then S is set to 57, and this results in INVALID_FLAG. However, if all of Q0 to Q7 is not defined, then it skips this part of the code and jumps to S = 58.

Solving

This knowledge greatly reduces the time complexity of a bruteforce solution. The idea is that when any of Q0 to Q7 is set, we can conclude that the last-checked character is wrong. Previously, we would have no way of knowing whether each individual character is correct, only that the flag as a whole is wrong.
The following solver script implements this, albeit in a very hacked-together kind of way. Since LD(l, n) is called for each bit in each flag character, we know that the i-th character is wrong if by the i+1-th character, any of Q0 to Q7 is set. This is then handled by the driver code by moving on to the next possible i-th character.
1
import string
2
from io import StringIO
3
from contextlib import redirect_stdout
4
​
5
CHAR_a = 97
6
​
7
...
8
​
9
CHAR_UNDERSCORE = 95
10
​
11
FLAG_0 = CHAR_C
12
​
13
...
14
​
15
FLAG_26 = CHAR_RBRACE
16
​
17
result = ''
18
​
19
for i in range(27):
20
def LD(l, n):
21
global i
22
if f"ROM_{''.join([str(x) for x in l])}_{n}" == f"ROM_{bin(i + 128 + 1)[2:]}_0":
23
if 'Q0' in locals() or 'Q0' in globals() or \
24
'Q1' in locals() or 'Q1' in globals() or \
25
'Q2' in locals() or 'Q2' in globals() or \
26
'Q3' in locals() or 'Q3' in globals() or \
27
'Q4' in locals() or 'Q4' in globals() or \
28
'Q5' in locals() or 'Q5' in globals() or \
29
'Q6' in locals() or 'Q6' in globals() or \
30
'Q7' in locals() or 'Q7' in globals():
31
raise Exception
32
​
33
print(f"ROM_{''.join([str(x) for x in l])}_{n}", eval(f"ROM_{''.join([str(x) for x in l])}_{n}"))
34
return eval(f"ROM_{''.join([str(x) for x in l])}_{n}")
35
​
36
f = StringIO()
37
​
38
for char in string.ascii_letters + string.digits + "_{}":
39
print(f"Trying FLAG_{i} = {char}...")
40
exec(f"FLAG_{i} = ord(char)")
41
​
42
try:
43
with redirect_stdout(f):
44
exec(open('converted.py').read())
45
46
except:
47
continue
48
49
else:
50
break
51
​
52
print(char, "works!")
53
​
54
result += char
55
​
56
print('FLAG:', result)
Copied!
This gives us the flag relatively quickly: CTF{pr3pr0cess0r_pr0fe5sor}
Last modified 4mo ago