C
Security/Attacks/Lesson 02

Web Attacks — OWASP Top 10 + XSS · CSRF · SQL Injection

45 min·theory

Web Attacks — OWASP Top 10 + XSS · CSRF · SQL Injection

🎯 What you'll be able to do after this lesson

After completing this lesson, you'll be able to confidently do the following three things.

  • ✅ Memorize the Top 5 of the OWASP Top 10
  • ✅ Defense code patterns for SQL Injection · XSS · CSRF
  • ✅ Use PreparedStatement / DOMPurify / SameSite

Keep these learning objectives as a checklist — close the lesson once you can answer all of them.

OWASP Top 10 (2021) — The Most Dangerous Web Vulnerabilities

In a nutshell: OWASP = a non-profit security organization. The Top 10 is a list of the most common web vulnerability categories. A staple in interviews.

RankCategoryMeaning
A01Broken Access ControlMissing authorization checks → access to other users' data
A02Cryptographic FailuresPlaintext communication · weak hashes · key exposure
A03InjectionSQL · NoSQL · Command · LDAP injection
A04Insecure DesignSecurity flaws at the design stage
A05Security MisconfigurationDefault passwords · debug mode · exposed admin pages
A06Vulnerable ComponentsOutdated libraries · unpatched CVEs
A07Auth FailuresBrute-force attacks · session fixation
A08Software & Data IntegrityUnverified updates · compromised CI/CD
A09Logging FailuresUnable to detect intrusion traces
A10SSRFServer makes external requests → accesses internal network

> 💡 A01, A03, and A07 occur most frequently. You'll encounter them 100% of the time in your first code review after joining a company.

XSS · CSRF · SQL Injection — The 3 Most Common Attacks

XSS (Cross-Site Scripting) — Injecting malicious scripts

TypeExample
Stored<script>steal()</script> saved to DB → executed for every page visitor
ReflectedURL parameter ?q=<script> → reflected in response → executed on click
DOM-basedJS directly sets location.hash etc. to innerHTML

4 XSS defenses:
1. Output escaping<&lt; (handled by default in React · Vue)
2. CSP (Content-Security-Policy) — allow only trusted scripts
3. httpOnly cookies — no access to session tokens from JS
4. Use textContent instead of innerHTML


CSRF (Cross-Site Request Forgery) — Another site makes requests using your credentials

  • Example: evil.com page includes <img src="bank.com/transfer?to=hacker&amt=999">
  • Browser automatically attaches bank.com cookies → transfer goes through

CSRF defenses:

  • CSRF token — random token in the form; server verifies it. Provided by default in Spring Security
  • SameSite cookieSameSite=Lax/Strict — no cookies sent from external domains
  • Origin/Referer validation — verify the request origin

SQL Injection — User input becomes part of a SQL query

  • ❌ Vulnerable: "SELECT * FROM users WHERE id='" + input + "'"
  • Input: 1' OR '1'='1 → returns all rows
  • Input: 1'; DROP TABLE users; -- → deletes the table

Defenses:

  • Parameterized Query (Prepared Statement):
python
cursor.execute("SELECT * FROM users WHERE id = %s", (user_id,))
  • Use an ORM (SQLAlchemy · Hibernate · Prisma) — automatic escaping
  • Input whitelist — accept only well-defined formats like numbers or UUIDs

> ⚠️ 'Just escape the ' and you're safe' is a common misconception. Always use parameterized queries.

💻 📌 Attack Defense Code Examples (Spring + Node)
// === Spring Security — CSRF + XSS + Headers ===
@Configuration
public class SecurityConfig {
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        return http
            // CSRF — Spring Security enabled by default
            .csrf(csrf -> csrf.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()))
            // Security Headers
            .headers(h -> h
                .contentSecurityPolicy(csp -> csp.policyDirectives("default-src 'self'"))
                .frameOptions(f -> f.deny())              // Clickjacking Defense
                .xssProtection(xss -> xss.disable())      // Modern browsers recommend CSP
                .httpStrictTransportSecurity(hsts -> hsts.maxAgeInSeconds(31536000))
            )
            // Cookie Security
            .sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
            .build();
    }
}

// === Parameterized Query — Spring JPA ===
// ❌ Vulnerable (never): 
// @Query("SELECT u FROM User u WHERE u.name = '" + name + "'")
// ✅ Safe:
public interface UserRepo extends JpaRepository<User, Long> {
    @Query("SELECT u FROM User u WHERE u.name = :name")
    Optional<User> findByName(@Param("name") String name);
}

// ─────────────────────────────────────────────────
// Node.js (Express) Example
// ─────────────────────────────────────────────────
/*
const helmet = require('helmet');
const csrf = require('csurf');

app.use(helmet());                 // Automatic security headers
app.use(csrf({ cookie: true }));   // Automatic CSRF token validation
app.use(express.json({ limit: '10kb' }));   // Payload limit

// XSS - React escapes by default. Only dangerouslySetInnerHTML needs caution

// SQL Injection - pg parameterized
const result = await pool.query(
  'SELECT * FROM users WHERE id = $1',     // $1 placeholder
  [userId]                                  // Value
);

// Cookies
app.use(session({
  cookie: { httpOnly: true, secure: true, sameSite: 'lax' }
}));
*/

🤖 Try asking AI like this

Once you understand the concepts in this lesson, you can give AI specific instructions. Instead of a vague 'fix this,' you can make vocabulary-driven requests — that's where token savings start.

  • 'Check this code for SQL Injection / XSS / CSRF vulnerabilities'
  • 'Strengthen this input validation using a whitelist approach'

Why this reduces tokens

Without the concepts, even after receiving an AI response you have to ask 'What does that mean?' again. Those follow-up questions consume tokens. Learn the concepts once, and the conversation ends in a single round.

Web Attacks — OWASP Top 10 + XSS·CSRF·SQL Injection - Security