Skip to content
notes.vinhnq.com

Search

SecurityMid22 min read

Web attacks and the OWASP Top 10: MITM, SQL injection, XSS, CSRF, DDoS

Review 24 cards
On this page

Backend security series: 1. Encoding, hashing, encryption and signatures · 2. Storing passwords and encrypting personal data · 3. Web attacks and the OWASP Top 10 · 4. Authentication: sessions, cookies and JWT · 5. Authorization, SSO and OAuth2

Most web vulnerabilities come from code that trusts the wrong thing: that input is just data (SQL injection, XSS), that a cookie means the user sent the request on purpose (CSRF), that nobody sits on the wire (MITM), that traffic always looks normal (DDoS). After this post you can explain how these five attacks work and how to stop them, map the OWASP Top 10 to Spring Security 6, and review a vulnerable controller. Read part 1 first for HMAC and TLS (the JDBC code ran on JDK 21 against H2; the Spring Security 6 configuration wasn’t run inside a real application).

1. Man-in-the-middle

Key idea: TLS stops a man-in-the-middle as long as the client validates the certificate. Between two backends the real question is “who is calling me, and was the content changed by a proxy?”: use mTLS or signed requests, plus replay protection.

1.1. How it works and how far HTTPS gets you

An attacker sits in the middle (public Wi-Fi, poisoned DNS, a proxy) and reads or changes traffic. The slides claim that between two backends “HTTPS is not safe at all”; that’s overstated. The real risks:

  • Code that turns off certificate validation.
  • TLS terminated in the middle: a load balancer or gateway decrypts and forwards.
  • TLS only authenticates the server; it doesn’t know who the client is.

1.2. Between two backends: mTLS or signed requests

  • mTLS (mutual TLS — the client presents a certificate too).
  • Request signing: an HMAC or digital signature over a canonical string (method, path, timestamp, nonce, body), as VNPay-style payment gateways do (the VNPay integration post).

1.3. Replay protection

A replay is capturing a valid request and sending it again unchanged; a signature doesn’t stop it. The slides suggest a “request id”; that’s not enough, because the server would have to remember every id forever.

The standard approach, signing both:

  • Timestamp: reject requests outside a window (5 minutes).
  • Nonce (a number used once): you only remember nonces seen within that window.
mTLS vs request signing, the verify method and its four test cases
String verify(String method, String path, long ts, String nonce, String body, String signature) throws Exception {
    Instant now = clock.instant();
    if (Duration.between(Instant.ofEpochSecond(ts), now).abs().compareTo(window) > 0) return "REJECT: stale timestamp";
    String expected = hmacHex(key, method + "\n" + path + "\n" + ts + "\n" + nonce + "\n" + body);
    if (!MessageDigest.isEqual(expected.getBytes(US_ASCII), signature.getBytes(US_ASCII))) return "REJECT: bad signature";
    seenNonces.values().removeIf(t -> t.isBefore(now.minus(window.multipliedBy(2))));
    if (seenNonces.putIfAbsent(nonce, now) != null) return "REJECT: replayed nonce";
    return "ACCEPT";
}

Test run: the first request is ACCEPT, the resend replayed nonce, a changed amount bad signature, a resend 10 minutes later stale timestamp. With several instances the nonce store moves to Redis: SET nonce 1 NX EX 600.

2. SQL injection

Key idea: data mixed into the SQL string gets read by the parser as code. The main defense is bound parameters; where binding isn’t possible (column names, ORDER BY), use an allowlist.

2.1. How it works

The slide example is a login screen that concatenates username and password into the SQL. Enter the username ' OR 1=1 --:

  • the quote closes the string;
  • OR 1=1 is always true;
  • -- comments out the password check.

On H2 with 4 users: concatenation counts 4 rows (login succeeds), PreparedStatement counts 0. Attackers also use UNION SELECT to read other tables, and blind injection to extract data bit by bit through response timing.

2.2. The main defense: keep code and data apart

PreparedStatement sends the SQL with ? placeholders and the values separately: the database parses the statement first, and values are only data. Like a printed form: whatever you write in the blanks can’t change the form itself.

  • Already bound: JdbcTemplate with ?, NamedParameterJdbcTemplate, JPQL :param, the Criteria API, derived queries.
  • Still injectable when you concatenate into JPQL, native queries, ORDER BY or column names, including values read back from the DB.
  • Extra layers: a least-privilege DB account, no raw SQL errors in responses.
static final Map<String, String> SORTABLE = Map.of("name", "username", "created", "created_at");

static String orderBy(String sort, String dir) {
    String column = SORTABLE.get(sort);
    if (column == null) throw new IllegalArgumentException("unsupported sort: " + sort);
    return " ORDER BY " + column + ("desc".equalsIgnoreCase(dir) ? " DESC" : " ASC");
}
Extra layers and hard-to-spot injection: second-order, LIKE, ORDER BY

Extra layers:

  • Allowlist input validation (Bean Validation), only as defense in depth.
  • A least-privilege DB account: no DDL, no superuser, migrations under a different account.
  • Never return raw SQL errors to the client (error handling in Spring Boot).
  • Bind values read from the DB too (second-order, just below).

Probing through ORDER BY (the hole in the section 8 case study): put CASE WHEN (SELECT substr(password_hash,1,1) FROM users ...) = '$' THEN author ELSE body END into sort and you can extract data one character at a time through the result order.

3. XSS (cross-site scripting)

Key idea: XSS is injection into the browser: a trusted page returns the attacker’s script. The main defense is context-aware encoding on output; CSP is the second line.

3.1. How it works

Three variants:

  • Stored: saved in the DB and shown to everyone. The most dangerous.
  • Reflected: sits in a URL parameter and is echoed into the page.
  • DOM-based: client-side JavaScript writes data into innerHTML.

The slides say the goal is stealing the session cookie. That undersells it: the script runs with the origin’s privileges, can do anything the user can do, and can read tokens in localStorage.

3.2. The main defense: context-aware encoding on output

Don’t “filter dangerous characters on input”: at input time you don’t know whether the data will land in HTML, JavaScript or a URL.

Context Example Encoding
HTML body <p>${comment}</p> < → &lt;, & → &amp;, quotes → entities
JavaScript <script>var x = '${v}'</script> avoid entirely, pass data via data-* or JSON
URL <a href="${url}"> URLEncoder for values, forbid the javascript: scheme
  • Thymeleaf’s th:text escapes by default, th:utext doesn’t. React escapes everything except dangerouslySetInnerHTML.
  • User-authored HTML must go through an allowlist-based sanitizer (OWASP Java HTML Sanitizer, jsoup Safelist).
  • Uploads are an attack channel too: an HTML/SVG file served from your origin is XSS, and the client’s filename pasted into a path is path traversal; magic-byte checks, generated names and safe serving are in file upload in Spring MVC.

3.3. Content Security Policy

CSP (Content Security Policy) is a header telling the browser which scripts may run. The slides describe it as a list of allowed URLs: the old style. Use a strict CSP based on nonces:

Content-Security-Policy: script-src 'nonce-R4nd0mPerResponse' 'strict-dynamic'; object-src 'none'; base-uri 'none'; frame-ancestors 'none'

Each response gets a fresh nonce, in the header and in the nonce attribute of legitimate <script> tags; an injected script has no nonce, so it doesn’t run.

4. CSRF (cross-site request forgery)

Key idea: the browser attaches cookies to every request to a domain, whichever page created the request; CSRF exploits that. The main defense is a CSRF token, with SameSite as an extra layer.

4.1. How it works

sequenceDiagram
    actor V as Victim
    participant E as Malicious page
    participant B as bank.example
    V->>B: Log in, receive session cookie
    V->>E: Open a link from an email
    E-->>V: Page with a hidden auto-submitting form
    V->>B: POST /transfer with the cookie
    B-->>V: Transfer succeeded
  • The attacker can’t read the response; they only need a request with a side effect.
  • It only works when authentication rides on something the browser sends by itself (cookies, Basic auth); an Authorization: Bearer header attached by JavaScript can’t be forged from another page.

4.2. Defenses

  • GET never changes state (the slides call this “stateless GET”): if GET /delete?id=5 deletes data, an <img> tag is enough.
  • SameSite cookies: Lax (Chrome’s default) doesn’t send the cookie on cross-site POSTs; Strict blocks it even on a clicked link.
  • CSRF tokens: tied to the session (synchronizer token), or stored in a cookie and echoed in a header (double-submit). The malicious page can’t read it.
  • Extra layers: check the Origin header; re-prompt for the password/OTP on sensitive actions (from the slides).

4.3. Spring Security 6 and CSRF

CSRF is on by default for POST, PUT, PATCH and DELETE. Since version 6 the token is loaded lazily and masked with XOR (against BREACH), so the SPA setup differs from version 5. In server-rendered forms Thymeleaf’s th:action adds the hidden token for you; a custom login page with CSRF is built in form login with Spring Security.

SameSite vs CSRF tokens, and the CSRF setup for an SPA
@Bean
SecurityFilterChain web(HttpSecurity http) throws Exception {
    return http
        .csrf(csrf -> csrf
            .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()) // SPA reads the cookie, sends X-XSRF-TOKEN
            .csrfTokenRequestHandler(new CsrfTokenRequestAttributeHandler()))   // no XOR masking
        .build();
}

Because the token is lazy, the SPA needs an initial request (for example GET /api/csrf taking a CsrfToken parameter) to make Spring issue the cookie.

5. DDoS and rate limiting

Key idea: DDoS uses a botnet (hijacked PCs, phones, IoT cameras) to send traffic from thousands of IPs. The slides are right: you can only mitigate it; the network layer goes to a provider, the application layer is yours.

Layer Attack Who handles it
Network (L3/L4) floods, amplification, Gbps to Tbps scrubbing (Cloudflare, AWS Shield); blackhole routing takes the service fully offline
Application (L7) legitimate-looking HTTP at expensive endpoints (search, export, login) the backend

L7 defenses:

  • CDN caching for public content.
  • Rate limiting in Nginx (limit_req) and in the app (Bucket4j, Resilience4j, Redis), token bucket or sliding window, answering 429 with Retry-After (five algorithms compared and a token bucket on Redis in the rate limiting post).
  • Caps on everything the client controls: body size, page size, search string length.
  • Login endpoint: rate-limit before hashing the password, since each hash costs ~100 ms of CPU on purpose.
  • Timeouts and bulkheads (splitting resources into separate compartments) so a hammered endpoint can’t eat every thread (web and REST APIs).
The login endpoint as a cheap DoS target; rate limiting per IP or per user

6. The OWASP Top 10 mapped to Java/Spring

Key idea: the OWASP Top 10 ranks ten common web risk categories; the slides don’t name it, but interviews ask about it constantly. The 2021 edition opens with Broken Access Control, Cryptographic Failures, Injection.

A memory hook for Spring: A01 ownership checks, A03 bound parameters, A05 don’t expose actuator, A06 dependency scanning in CI, A10 host allowlists. A common access-control bug is mass assignment: binding the request straight onto the entity, so a client that adds role=ADMIN gets it written; the form-DTO fix is in form binding and validation in Spring MVC.

The full OWASP Top 10 (2021) with Java/Spring controls
Item (2021) Controls in Java/Spring
A01 Broken Access Control Deny by default, @PreAuthorize, ownership checks in the service layer (part 5)
A02 Cryptographic Failures TLS everywhere, AES-GCM, bcrypt/Argon2 (part 2)
A03 Injection Bound parameters, identifier allowlists, output encoding
A04 Insecure Design Threat modeling, business limits (transfer caps, attempt counts)
A05 Security Misconfiguration Don’t expose /actuator, no stack traces in responses, security headers
A06 Vulnerable and Outdated Components Dependabot/Renovate, OWASP Dependency-Check or Trivy in CI
A07 Identification and Authentication Failures Rate limiting, MFA, new session id after login (part 4)
A08 Software and Data Integrity Failures No Java serialization of untrusted data, signed artifacts
A09 Security Logging and Monitoring Failures Log authentication events and access denials, alert, never log secrets
A10 Server-Side Request Forgery Allowlist target hosts, block internal IPs after DNS resolution

The 2025 edition is out: as far as I know, Broken Access Control is still first (now absorbing SSRF) and the software supply chain gets its own item; check owasp.org before quoting it.

7. Spring Security 6: a baseline configuration

Key idea: Spring Security 6 (Spring Boot 3) removed WebSecurityConfigurerAdapter; you configure a SecurityFilterChain bean with the lambda DSL. The defaults are already fairly safe, so the main job is not turning them off.

On by default: CSRF, nosniff, X-Frame-Options: DENY, Cache-Control: no-store, HSTS over HTTPS, a new session id after login. You add: deny by default (the first matching rule wins), CSP, HSTS for subdomains.

The full SecurityFilterChain configuration
@Configuration
@EnableMethodSecurity
class SecurityConfig {
    @Bean
    SecurityFilterChain app(HttpSecurity http) throws Exception {
        return http
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/", "/login", "/css/**", "/actuator/health").permitAll()
                .requestMatchers("/admin/**").hasRole("ADMIN")
                .requestMatchers("/api/**").authenticated()
                .anyRequest().denyAll())                                   // deny by default
            .headers(h -> h
                .contentSecurityPolicy(csp -> csp.policyDirectives(
                    "default-src 'self'; object-src 'none'; base-uri 'none'; frame-ancestors 'none'"))
                .httpStrictTransportSecurity(hsts -> hsts.includeSubDomains(true).maxAgeInSeconds(31_536_000))
                .frameOptions(f -> f.deny()))
            .formLogin(Customizer.withDefaults())
            .build();
    }
}

8. Case study: reviewing a controller with three vulnerabilities

Key idea: one small controller holds SQL injection, stored XSS and CSRF at once, and together they make a self-spreading XSS worm. The root cause: removing or bypassing a protection.

A comments page, logged in through formLogin (session cookie):

@GetMapping("/products/{id}/comments")
String list(@PathVariable long id, @RequestParam(defaultValue = "created_at") String sort, Model model) {
    model.addAttribute("comments", jdbc.queryForList(
        "SELECT author, body FROM comment WHERE product_id = " + id + " ORDER BY " + sort));
    return "comments";            // the template prints body with th:utext to keep line breaks
}
// SecurityConfig: http.csrf(c -> c.disable()) "because the AJAX form got a 403"
Vulnerability Why Fix
SQL injection through sort pasted straight into ORDER BY, can extract password_hash character by character allowlist (newest, oldest, anything else is a 400), id bound with ?
Stored XSS th:utext: a <script> runs for every viewer, admins included th:text + CSS white-space: pre-line
CSRF session cookie with CSRF off: an outside page posts comments as the victim CSRF back on, token in an X-CSRF-TOKEN header

Also add a CSP nonce and @Size(max = 2000).

Exercises

Exercise 1: A safe user search endpoint

Task (paraphrased): find users by a substring of the username, sortable by name or creation date in either direction, using JDBC; it must resist injection in both the filter and the sort, and handle user-typed % and _ correctly.

Solution to exercise 1
static String escapeLike(String s) {
    return s.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_");
}

static List<String> search(Connection c, String term, String sort, String dir) throws SQLException {
    String sql = "SELECT username FROM users WHERE username LIKE ? ESCAPE '\\'" + orderBy(sort, dir);
    List<String> out = new ArrayList<>();
    try (PreparedStatement ps = c.prepareStatement(sql)) {
        ps.setString(1, "%" + escapeLike(term) + "%");
        try (ResultSet rs = ps.executeQuery()) { while (rs.next()) out.add(rs.getString(1)); }
    }
    return out;
}

Run on H2: search("an", "name", "desc") returns [anh, an_nguyen]; search("_", ...) returns [an_nguyen]; sort = "username; DROP TABLE users" is rejected (the controller answers 400). A senior would also cap the length of term and add a LIMIT.

Exercise 2: Replay protection for a partner API

Task: a partner calls POST /partner/orders with an HMAC signature; a captured request must not be replayable, and modified or stale requests must be rejected.

Solution to exercise 2

The solution is the verify method in section 1.3; the four cases produce exactly ACCEPT, replayed nonce, bad signature and stale timestamp. In production, give each partner its own key with a key_id header so keys can be rotated without downtime.

Remember

  • Explain why a signature doesn’t stop replay, and the check order timestamp → signature → nonce.
  • Point out where SQL injection survives even with PreparedStatement everywhere.
  • Tell XSS from CSRF, and explain why HttpOnly doesn’t stop XSS.
  • Know when it’s OK to disable CSRF.
  • List the DDoS defense layers at L3/L4 and L7, and why the login endpoint is a cheap target.

Interview questions

Junior

What is SQL injection and what’s the main defense?

User input concatenated into SQL gets interpreted by the database as code; the main defense is parameterization.

For example ' OR 1=1 -- bypasses a login. With PreparedStatement or named parameters in JPA, the statement is parsed first and values are only data. Extras: an allowlist for sort columns and a least-privilege DB account.

How is XSS different from CSRF?

XSS runs the attacker’s script inside a trusted page; CSRF tricks the browser into sending a request with side effects using cookies it attaches automatically.

XSS can read and do anything the user can; CSRF can’t read the response. XSS is stopped by output encoding and CSP, CSRF by tokens and SameSite. With XSS present, CSRF tokens are useless because the script can read them.

Why shouldn’t GET change data?

Because GET is the easiest request to forge and the least protected.

An <img src="/delete?id=5"> on any page is enough for CSRF, SameSite=Lax still sends cookies on top-level GET navigation, Spring Security doesn’t require a CSRF token for GET, and GET parameters end up in logs.

Mid

We use PreparedStatement everywhere. Where can SQL injection still happen?

Wherever binding isn’t possible, and in data read from the DB and concatenated again.

ORDER BY, column or table names built from input; concatenated JPQL or native queries; dynamic SQL inside stored procedures; and second-order injection, where data read from the DB is concatenated into another query. The fix: allowlist identifiers and bind every value regardless of its source.

When is it OK to disable CSRF in Spring Security?

Only when the browser sends no credentials by itself.

That means only an Authorization: Bearer header the client attaches, no session cookie, no token in a cookie. With formLogin or a JWT in a cookie, keep CSRF; for an SPA use CookieCsrfTokenRepository and send the token in a header.

What is CSP and how do you configure it effectively?

A header telling the browser where scripts may come from, the second line of defense against XSS; use a nonce-based strict CSP.

Domain allowlists are easy to bypass, so use script-src 'nonce-...' 'strict-dynamic', object-src 'none', base-uri 'none', and frame-ancestors against clickjacking. Roll it out in Report-Only mode first.

Senior

How do you protect a webhook or partner API against replay?

Sign a timestamp and a nonce, reject stale timestamps and nonces already seen in the window; a signature alone doesn’t prevent replay.

Remember nonces for the window with an atomic operation (Redis SET NX EX), and verify the signature before recording the nonce. At the business level, add idempotency keyed on the transaction id.

How would you design DDoS protection for a public API?

L3/L4 goes to a scrubbing provider or a large CDN; L7 is handled with several layers of limits.

For L7: cache public content; rate-limit per IP at the edge and per user/API key in the app; cap body size and page size; make expensive endpoints asynchronous with quotas; use timeouts and bulkheads; autoscale with a ceiling; and have a 429-rate dashboard plus an emergency runbook.

You’re reviewing a PR that disables CSRF, sets CORS to * and adds th:utext. What do you say?

Reject it: each line removes a protection, and together they make a self-spreading XSS worm.

CSRF can only be disabled for a pure bearer-token API. CORS * opens the API to every origin; it needs an explicit origin list. th:utext on user data is stored XSS. I’d also propose security tests in CI and static analysis rules that block these patterns.

What’s in the OWASP Top 10 2021 and how do you apply it to a Spring project?

Ten risk categories led by Broken Access Control; you apply it through concrete controls, and use ASVS when you need checkable requirements.

The list: Broken Access Control, Cryptographic Failures, Injection, Insecure Design, Security Misconfiguration, Vulnerable Components, Authentication Failures, Integrity Failures, Logging and Monitoring Failures, SSRF. Applying it: deny by default with ownership checks, bound parameters, dependency scanning in CI, no exposed actuator, security event logging, and host allowlists for user-supplied URLs.

Useful phrases for interviews

  • “The root cause of injection is data being interpreted as code, so the fix is to keep them apart with bound parameters.”
  • “Identifiers can’t be bound, so sort columns go through an allowlist and anything else is a 400.”
  • “We encode on output, according to the context, rather than trying to filter dangerous characters on input.”
  • “CSP is our second line of defense; we use a nonce-based policy rather than a domain allowlist.”
  • “CSRF only matters when the browser sends credentials by itself, which is why a pure bearer-token API can turn it off.”
  • “SameSite is a useful extra layer, but the CSRF token stays our main defense.”
  • “A signature proves who sent the request, not that it’s the first time; for that we add a timestamp and a nonce.”
  • “You can’t prevent a DDoS, you can only absorb and shed it: scrubbing at L3/L4, caching and rate limits at L7.”
  • “The OWASP Top 10 is for awareness; when we need verifiable requirements we use ASVS.”

Notes based on the Advanced Backend course (Ronin Engineer), rewritten in my own words.