software-engineer-blog logoSoftware Engineer Blog

Module 12 · Security

Unit 48 of 49

Unit 48 · Module 12 · Security

The attacks worth knowing: injection, XSS, CSRF and CORS

Four names people mix up constantly, each with a different attacker and a different fix.

Unit 48 of the free 49-unit computer-science course, in security. 3 interview questions answered in full and a short self-check.

Nothing published yet

This unit is part of the course map but has no episode or article of its own yet. The units around it do — see what is already published.

Interview questions this unit unlocks

Asked out loud, answered out loud. Read the answer, then say it in your own words.

What actually prevents SQL injection?

Parameterised queries. The statement and the data travel to the database separately, so the driver never has to decide where a value ends and syntax begins — which is precisely the ambiguity injection exploits. Escaping is a fragile imitation of that, because it depends on getting every character class and encoding right in a language you do not control. The same rule generalises: never build a command out of string concatenation with untrusted input.

Where it still bites in an ORM: raw fragments, dynamic ORDER BY, and table names — none of which can be bound as parameters, so they need an allowlist.

What is the difference between XSS and CSRF?

XSS is your site running an attacker's script — the attacker gets to act as the user *inside* your origin, so they can read the DOM, the tokens and anything the user can see. CSRF is another site causing the user's browser to make an authenticated request to yours; the attacker never sees the response, they only cause the side effect. XSS is stopped by escaping output and a content security policy; CSRF by SameSite cookies and a token the other origin cannot read.

The ordering that matters: XSS defeats every CSRF defence, because a script in your origin can read the token. Fix XSS first.

What attack does CORS actually stop?

None, on its own — CORS is a relaxation, not a defence. The browser's same-origin policy already stops a page reading a response from another origin, and CORS is the mechanism by which a server opts to allow it. So `Access-Control-Allow-Origin: *` on a public API is fine, and the same header on an API that authenticates with cookies is the mistake, because combined with credentials it hands any site the ability to read authenticated responses.

The clarifying fact: CORS never blocked the request from being sent. It blocks the caller from reading the answer, which is why it is no substitute for authorisation on the endpoint.

Self-check — 3 questions

Answer alone, at 2am, with no interviewer in the room.

Part of Everything You Need to Know About Computer Science.