SQL injection inserts malicious SQL commands into application input to access or manipulate a database, while cross-site scripting (XSS) injects malicious client-side code into web content so that it executes in another user's browser. Both exploit insufficient input handling, but they attack different components.
The Reasoning and Mechanism
A web application often accepts data through login forms, search boxes, URLs, or cookies. If this input is treated as executable code rather than untrusted data, an attacker may alter the application's intended behaviour.
For SQL injection, suppose a server constructs a query by joining strings:
SELECT * FROM users
WHERE username = 'input' AND password = 'input';
An attacker may enter SQL syntax that changes the query's logic. This can enable authentication bypass, unauthorized reading or modification of records, or database deletion. The main defence is parameterized queries, also called prepared statements, which keep SQL instructions separate from supplied values.
In XSS, an attacker supplies malicious JavaScript that a website returns or stores without safe handling. When another user loads the affected page, the browser executes the script under that website's security context. It may steal session data, modify page content, or perform actions as the user.
| Feature | SQL injection | Cross-site scripting |
|---|---|---|
| Primary target | Server-side database | User's browser and session |
| Injected content | SQL commands | Usually JavaScript or HTML |
| Possible impact | Data disclosure, modification, or deletion | Session theft, impersonation, or page manipulation |
| Key controls | Parameterized queries, least privilege, server-side validation | Context-aware output encoding, sanitization, Content Security Policy |
The common misconception is that input validation alone completely prevents both attacks. Validation helps, but SQL injection primarily requires parameterized queries, while XSS requires output encoding appropriate to where the data appears.
Exam Technique
For A2.4 Network security, distinguish the target, mechanism, consequence, and prevention of each attack. If asked to explain, connect the cause to the effect rather than merely naming a control.