QA Interview Hub · Knowledge base · Quizzes · Українська

Penetration Testing

Client side: XSS, CSRF, CORS, clickjacking

XSS: reflected, stored and DOM

XSS is an injection of HTML or JavaScript that runs in the browser in the site's origin and acts on behalf of the user. There are reflected (from the request), stored (from the database) and DOM-based (an unsafe insertion in client-side JS) kinds. Protection is output encoding by context and safe APIs such as textContent; CSP is only a second line. HttpOnly does not remove XSS.

Pentest · Client side

A comment with a script tag runs for every visitor. Why does the browser trust that code?

Someone left text that looks like a script tag in a comment under an article, and now everyone who opens the page runs foreign code. The browser does not tell a developer’s script from a script on the page: everything that came from this site has the rights of this site. The lesson covers three kinds of XSS, the input context that changes the payload, and what really protects.

Mechanism. XSS (cross-site scripting) is an injection into HTML or JavaScript in the user’s browser. The script runs in the site’s origin, so it can read the page, send requests on behalf of the user with his cookies, change the interface (forge a login form), capture typed input. HttpOnly stops a script from reading the cookie, but it still sends requests on behalf of the user.

Three kinds of XSS: where the script comes from

Reflected: the server returns input at oncelinkresponsebrowserStored: input sits in the databaseformdatabasevisitorsDOM: the server never sees the fragmentURL with #page JSinnerHTML
Figure 1. Red marks where the script runs. In the DOM variant the server takes no part at all.
  • Reflected. A value from the request (?q=…) goes straight into the response. The attack is a link the victim has to open;
  • Stored. The value lies in the database (a comment, a profile name, a file name) and runs for everyone who sees the page. More dangerous: the victim needs to click nothing;
  • DOM-based. The unsafe insertion is done by JavaScript on the client: from a source (location.hash, document.referrer, postMessage) into a sink (innerHTML, document.write, eval). The part after # is not sent to the server, so server logs and a WAF do not see it.

Input context. What works depends on where the value ended up in the response. So a test starts with a harmless marker and looks at the source or the DOM to see how it was encoded:

<!-- 1. HTML body -->
<p>Hello, <img src=x onerror=alert(document.domain)></p>

<!-- 2. attribute -->
<input value="" autofocus onfocus=alert(1) x="">

<!-- 3. JavaScript string -->
<script>var q = '';alert(1);//';</script>

<!-- 4. URL attribute -->
<a href="javascript:alert(1)">profile</a>

These are textbook examples for a test environment or a lab. Each context needs its own encoding: in HTML text escape < and &, in an attribute quotes as well, in a JS string quotes and the backslash, in a URL check the scheme (https:, not javascript:). There is no single "one function".

A DOM XSS example. A page shows a greeting from the address:

// before
el.innerHTML = "Hello, " + decodeURIComponent(location.hash.slice(1));

// after
el.textContent = "Hello, " + decodeURIComponent(location.hash.slice(1));

textContent inserts text, not markup, so tags lose their force. If markup is really needed (an editor), it is passed through a sanitization library with an allowlist (for example, DOMPurify), not a home-made regular expression.

A real case. On 4 October 2005 Samy Kamkar released code on MySpace from his profile that added him as a friend, appended "but most of all, samy is my hero" to the profile, and copied itself onto the profile of everyone who opened an infected one. MySpace allowed part of HTML and CSS; the code bypassed the filters. In about 20 hours over a million profiles were infected and the site had to be taken down for a while. Kamkar pleaded guilty in 2007 and received probation and community service. On its own it was a "prank", but the self-propagating stored XSS showed that a foreign script in a page acts on behalf of every viewer.

What protects.

  • Output encoding by context and safe APIs (textContent, attributes through the DOM, template engines with auto-escaping). Frameworks (React, Angular, Vue) escape text by default; the risk is where they are bypassed: dangerouslySetInnerHTML, v-html, href with a user-supplied value;
  • CSP as a second line (next lesson). It does not fix the flaw, it makes execution harder;
  • Input validation helps but is not the main thing: the name "O’Brien" or a comment about <script> must be allowed, so protection is applied on output.

How QA checks it. On an authorized environment or in a lab (PortSwigger Web Security Academy, OWASP Juice Shop with DOM XSS in search, DVWA). Enter a unique marker with the characters "'<> into every field that is displayed later: profile, comments, file names, address, the Referer and User-Agent headers an admin sees. Look at how the marker is encoded in the source and the DOM. alert(document.domain) is enough as proof, without stealing sessions. "Blind" XSS (firing later in an admin panel) is tested only with a controlled test callback and by agreement.

Common mistakes.

  • Filtering only the script tag: img onerror, svg onload, attribute events work;
  • Encoding for HTML and inserting into a JavaScript string: this context needs different escaping;
  • Believing that HttpOnly or HTTPS eliminates XSS: they only limit part of the consequences.

Check yourself

The parameter ?name= lands in <input value="…">. Is escaping < and > enough?

Answer

No. In an attribute a quote is enough to close the value and add an event handler (" onfocus=alert(1) x="). For this context quotes and the ampersand are escaped and the attribute value is always quoted.

Why do a WAF and server logs not see DOM XSS taken from location.hash?

Answer

The browser does not send the part after # to the server: client-side JavaScript reads and inserts it. So the client code (sinks like innerHTML) has to be fixed and detection happens on the browser side.

In an interview. Junior: XSS is a foreign script in a page. Reflected comes from the request, stored sits in the database, the DOM variant arises in client JS. The defence is output encoding by context and safe APIs. Middle/Senior: I start with a marker and look at the context it landed in, and make the proof alert(document.domain). Separately I check DOM sinks, dangerouslySetInnerHTML and links with input; I treat CSP as a second layer, not a fix.

CSP: a second line of defence against XSS and skimmer scripts

CSP is a response header with which the server tells the browser where scripts may be loaded and run from and where the page may send data. It is a second line against XSS and skimmers, not a replacement for output encoding. A strict policy relies on a nonce or hashes; 'unsafe-inline' without them removes the main protection. It is rolled out through Report-Only first, then switched to blocking.

Pentest · Client side

The XSS is already in the page, yet the browser refuses to run the script. Who stopped it?

After a test the console shows: Refused to execute inline script because it violates the following Content Security Policy directive. That was CSP (Content-Security-Policy): a response header in which the server tells the browser which sources may run scripts, load images, connect and embed the page. The lesson explains what it gives, what it does not, and how QA checks it.

Mechanism. The browser checks every load and execution against the policy. If <script>alert(1)</script> got into the page and the policy does not allow inline scripts, it will not run. A strict policy uses a nonce (a one-time random value the server generates for every response) or hashes:

Content-Security-Policy:
  default-src 'self';
  script-src 'nonce-r4nd0m' 'strict-dynamic';
  object-src 'none';
  base-uri 'self';
  frame-ancestors 'none'
<script nonce="r4nd0m" src="/app.js"></script>
<!-- injected: no nonce, so it is blocked -->

The site’s script has the nonce, so it runs, while the attacker’s injected one does not know it. base-uri stops the base address from being replaced, object-src 'none' turns off legacy plugins, frame-ancestors controls who may embed the page (see the clickjacking lesson).

The same injected script

No CSP

The browser runs any script from the page. An XSS flaw at once gives the attacker code in the site’s origin.

Strict CSP

A script without a nonce is blocked, the console says "Refused to execute…". The flaw stays, but exploitation is harder.

Figure 1. CSP does not fix XSS: it reduces what can be done.

How it is rolled out. Turning on a strict header at once is risky: inline handlers and third-party widgets break. So first Content-Security-Policy-Report-Only: the browser blocks nothing but sends violation reports to the endpoint named in report-to (defined by the Reporting-Endpoints header; for browsers without support the deprecated report-uri is added). After a few days the reports show what still has to be allowed or rewritten, and then the policy is switched to enforcing mode.

Limits.

  • 'unsafe-inline' and 'unsafe-eval' in script-src remove the main protection (except when the same directive has a nonce or hash: browsers then ignore 'unsafe-inline', and it is kept only for old browsers);
  • A long allowlist of domains (script-src https://cdn.example) is unreliable: an allowed domain may host a script that runs foreign code (JSONP, old libraries);
  • CSP does not cure the cause: inserted markup, a changed page and some leaks (for example through images if img-src is wide) remain possible;
  • For DOM sinks there are Trusted Types (require-trusted-types-for 'script'), since February 2026 the current versions of all major browsers support them (Baseline 2026), but older versions do not, so they complement safe APIs rather than replace them.

A real case. In 2018 attackers modified a script on the British Airways site: when customers entered payment details, a skimmer script (attacks of this kind are called Magecart) sent them to a third-party server. More than 400,000 customers were affected. In October 2020 the UK regulator ICO announced a fine of 20 million pounds (a proposed 183 million had been named in 2019), citing insufficient protection of data. A strict CSP would not have cured the compromise of the file itself, but a policy with limited connect-src, img-src and form-action keeps a script from sending data to an unknown domain, and Subresource Integrity (integrity="sha384-…") detects a swapped third-party library.

How QA checks it. Looks at the response header of the main page and the API (DevTools → Network, or curl -I) and whether the policy is the same on the test environment and in production. On an authorized environment checks that an injected inline script is blocked (console) and that the application itself works under the policy: the e2e suite is run with the same headers as production. Report-Only reports are read as a list of defects. Third-party scripts (analytics, widgets) are inventoried: every allowed domain is a risk.

Common mistakes.

  • Believing that CSP replaces output encoding. It is a second line;
  • Adding 'unsafe-inline' because "otherwise everything breaks" and leaving it forever;
  • Using a static nonce that does not change between responses: it can be guessed or seen.

Check yourself

The policy script-src 'self' 'unsafe-inline' is set on a site with XSS in comments. Will it stop an injected <script>?

Answer

No. 'unsafe-inline' allows inline scripts, so the injected one will run too. A nonce or hashes are needed instead of 'unsafe-inline', and above all the output encoding must be fixed.

Why launch CSP in Report-Only mode first?

Answer

The browser blocks nothing but sends violation reports. So you see which legitimate scripts and domains the policy would break and fix them before blocking, without breaking the site for users.

In an interview. Junior: CSP is a header that tells the browser where scripts may be executed from. It reduces the damage of XSS but does not replace output encoding. Middle/Senior: I check the presence and strength of the policy: nonce or hashes instead of unsafe-inline, object-src, base-uri, frame-ancestors, limited connect-src and form-action, SRI for third-party scripts. I roll it out through Report-Only, and the policy must work the same on the test environment and in production.

CSRF and SameSite: a foreign request with your cookies

CSRF is when a foreign page makes the browser send a request with the user's cookie. The server performs a state change and the attacker does not see the response. Defences are an anti-CSRF token, an Origin check and SameSite, but SameSite is only one layer: Lax allows top-level GET navigations, and a subdomain of the same site is not cross-site. Changes go only through POST, PUT or DELETE.

Pentest · Client side

A user opened a foreign page and a transfer appeared in the bank. He clicked nothing in the bank.

A user is logged in to a bank and at the same time opens a foreign page. That page automatically submits a form to the bank’s address and the bank carries out the transfer: the browser added the session cookie itself. This is CSRF (cross-site request forgery). It is covered briefly in the OWASP overview, and here are the mechanism in more depth and the defence in detail, in particular the SameSite attribute.

Mechanism. The browser attaches cookies to every request to their site, even when another page initiated the request. The attack needs three conditions: the action changes state (a transfer, an email change), authentication relies on a cookie, and all request parameters are predictable. The attacking page:

<form action="https://bank.example/transfer" method="POST">
  <input name="to" value="attacker">
  <input name="amount" value="1000">
</form>
<script>document.forms[0].submit()</script>

The attacker does not see the response (this separates CSRF from XSS): he only forces an action. So CSRF is about changes, not reading.

SameSite. A cookie attribute decides whether to send it in "cross-site" requests (a site is the registrable domain, for example example.com, with all subdomains):

  • Strict — never sent from another site, even when following a link;
  • Lax — sent only on a top-level navigation with an ordinary GET (a link click), but not in a POST from a foreign form, an iframe or fetch;
  • None — always sent, requires Secure.

What happens to the session cookie

POST from foreign · Nonecookie sentPOST from foreign · Laxno cookieGET link · Laxcookie sent
Figure 1. Lax stops a cross-site POST but a GET navigation gets the cookie: changes must never be made through GET.

In Chrome a cookie without an explicit SameSite is treated as Lax (since 2020, version 80); for such cookies Chrome still sends them on a top-level cross-site POST for two minutes after they are set. Other browsers behave differently, so set it explicitly: Set-Cookie: sid=…; Secure; HttpOnly; SameSite=Lax (or Strict for sensitive sessions).

Other defences.

  • An anti-CSRF token: a random value tied to the session that the page passes in the body or a header and the server compares. A foreign page does not know it;
  • Checking Origin (and if needed Referer) and the Sec-Fetch-Site header: the browser itself marks that the request is cross-site;
  • Re-authentication for sensitive actions (a password, a confirmation code).

A caution: "JSON only" is not a defence by itself (a form with text/plain can carry a string that looks like JSON), while an Authorization: Bearer header that a script adds manually is protected from CSRF, because the browser does not add it on its own.

A real case. In September 2008 Princeton researchers William Zeller and Edward Felten showed CSRF flaws on well-known sites: ING Direct, YouTube, MetaFilter and The New York Times. In the ING Direct case an attacker could open extra accounts on behalf of a user and move money out. It is one of the first publicly described CSRF flaws on a bank site. The sites fixed the flaws, and the authors also released a browser extension that protected only against cross-site POSTs. SameSite did not exist then: protection rested on server-side tokens.

Limits and bypasses.

  • Site ≠ origin. A subdomain blog.example.com shares the site with app.example.com: XSS on the blog sends requests with the cookie, and SameSite changes nothing;
  • A state-changing GET. An address /delete?id=5 opened by navigation gets the cookie even with Lax;
  • XSS defeats all tokens because the script reads them from the page;
  • Login CSRF: a foreign login form signs the user in to the attacker’s account; a token is needed on the login too.

How QA checks it. Look at the cookie attributes in DevTools (Application → Cookies tab): SameSite, Secure, HttpOnly. On an authorized environment: repeat a change without a token or with another user’s token (403 is expected), with another Origin, with GET instead of POST. A separate pass over pages on subdomains. Check that the refusal really changed nothing (read the state after the attempt).

Check yourself

The session cookie has SameSite=Lax, and an email change is done through GET /account/email?new=…. Is it protected from CSRF?

Answer

No. Lax sends the cookie on a top-level navigation by link (GET), so a foreign page can redirect to this address. Changes are made only with POST/PUT/DELETE and a token or an Origin check.

Why is XSS on the subdomain blog.example.com dangerous for app.example.com even though the cookie has SameSite=Strict?

Answer

Both subdomains belong to the same site, so for SameSite requests from the blog are not "cross-site": the cookie is attached. So subdomains with risky content are isolated and tokens or an Origin check are kept in addition.

In an interview. Junior: CSRF is when a foreign page makes the user’s browser send a request with his cookie. The defence is a token, SameSite and an Origin check. Middle/Senior: I distinguish site and origin, remember that Lax lets GET navigations through, so changes only with POST and a token; I check subdomains, login CSRF and that a refusal really changed nothing. SameSite is a layer, not a replacement for tokens.

CORS: when the browser lets a foreign site read the response

CORS is the server's permission, enforced by the browser, for a foreign origin to read responses; it does not protect the server, because curl ignores it. It is dangerous when the server reflects an arbitrary Origin with Allow-Credentials, accepts null or compares origins by suffix or prefix. The right way is a closed list of full origins plus Vary: Origin.

Pentest · Client side

A frontend on another domain gets a CORS error. Add Allow-Origin: * and forget it?

A frontend is developed on app.example, the API lives on api.example, and the console shows a red CORS error. The quickest "cure" is to reflect any Origin in the response header or to set *. Sometimes this is harmless, and sometimes it lets any site read a user’s private data. The lesson tells the cases apart.

Mechanism. Under the same-origin policy a script on a page cannot read the responses of another origin (scheme + host + port). CORS (Cross-Origin Resource Sharing) is the server’s permission, enforced by the browser, to break this rule for chosen origins. So CORS does not protect the server: curl or any backend ignores it, and in simple cases (a form, GET) the browser still sends the request and only blocks reading the response. It protects the user from foreign pages and is not a means of authentication.

For "non-simple" requests (Content-Type: application/json, custom headers, PUT/DELETE) the browser first sends a preflight, an OPTIONS request asking for permission:

Preflight and the main request

browserserverOPTIONS + Originallowed origins and methodsGET + cookiedata, the page reads it
Figure 1. If the permission in the preflight response does not match the origin, the main request is not sent.

With cookies (fetch(url, { credentials: "include" })) stricter rules apply: Access-Control-Allow-Origin must be a specific origin, not *, and Access-Control-Allow-Credentials: true is added. This very combination makes a mistake dangerous.

A vulnerable configuration example. An authorized test, your own account. A request with an arbitrary Origin:

GET /api/account HTTP/1.1
Host: api.shop.example
Origin: https://evil.example
Cookie: sid=<your-test-session>

HTTP/1.1 200 OK
Access-Control-Allow-Origin: https://evil.example
Access-Control-Allow-Credentials: true

The server reflected a foreign origin and allowed cookies. Now any page a logged-in user opens (provided his cookie is sent cross-site: SameSite=None in a browser that neither blocks nor partitions third-party cookies, such as Chrome by default) can run fetch to /api/account and read the response. A set of Origin variants is checked:

Origin: https://evil.example           -> reflected?
Origin: null                           -> allowed?
Origin: https://shop.example.evil.net  -> prefix check?
Origin: https://evilshop.example       -> suffix check?
Origin: http://shop.example            -> plain http trusted?

Typical configuration mistakes: reflecting any origin; allowing null (pages in a sandboxed iframe, file://, data: get that origin); weak comparison (endsWith("shop.example") lets evilshop.example through, startsWith("https://shop.example") lets https://shop.example.evil.net through); trusting all subdomains and http origins; a missing Vary: Origin (a cache may serve someone else’s response).

The fix: compare the full origin string with a closed list.

const ALLOWED = new Set([
  "https://shop.example",
  "https://admin.shop.example",
]);
if (ALLOWED.has(origin)) {
  res.setHeader("Access-Control-Allow-Origin", origin);
  res.setHeader("Access-Control-Allow-Credentials", "true");
  res.setHeader("Vary", "Origin");
}

A real case. In October 2016 James Kettle (PortSwigger) published research on CORS mistakes in real sites. On one cryptocurrency exchange the server reflected any origin with cookies allowed, which let users’ API keys be stolen from a foreign page; the exchange fixed it in about 20 minutes. Others allowed null and used weak suffix or prefix comparison (definitelynotadvisor.com passed a check for advisor.com). The research showed that a "working" CORS made by reflecting the origin regularly reaches production.

Limits. * without cookies is acceptable for really public data (open fonts, a public API). But for a service inside an internal network even it lets a foreign page read, through an employee’s browser, what is reachable only from inside. Cookies with SameSite=Lax are not sent in a cross-site fetch, so some attacks are weaker, while an API with a token in the Authorization header (the site’s script takes it from localStorage) is not exposed to a foreign page by origin reflection: that page has no token, and the browser does not add it by itself.

Common mistakes.

  • Treating CORS as protection of the server from requests. It only governs reading the response in a browser;
  • Curing the error by reflecting the origin instead of a list;
  • Not adding Vary: Origin and letting a cache mix responses.

Check yourself

An API answers Access-Control-Allow-Origin: * and Access-Control-Allow-Credentials: true. Can a foreign site read the user’s private data?

Answer

Not through this combination: the browser does not let the page read the response to a request with cookies when the value is *. It is dangerous when the server reflects a specific origin with that permission. The configuration should still be fixed because it points to a wrong understanding.

Why is the check origin.endsWith("shop.example") unreliable?

Answer

It lets through any domain with such an ending, for example https://evilshop.example. The full origin string has to be compared with a closed list, not a part of the string.

In an interview. Junior: CORS is a server permission by which the browser lets a foreign page read a response. It is not protection of the server, and reflecting any origin with cookies is not allowed. Middle/Senior: I test an arbitrary Origin, null, prefixes and suffixes, an http origin, the combination with Allow-Credentials and Vary: Origin. The fix is a closed list of full origins; for public data without cookies * is acceptable.

Clickjacking: an invisible button under the cursor

Clickjacking is when a foreign page puts your site in a transparent iframe over a decoy, and the user clicks the real button without knowing it. Protection is a Content-Security-Policy header with frame-ancestors (the older X-Frame-Options), while a JavaScript window.top check is unreliable. A CSRF token does not help, because the user makes the request.

Pentest · Client side

A user clicked "Claim prize" and something changed in his account. What did he really click?

A page promises a prize and has a big button. But over it lies a transparent iframe of another site, in which a "Delete account" button ended up under the cursor. The user clicks where he looks, and the click reaches the hidden site. This is clickjacking (UI redress): the term was introduced by Jeremiah Grossman and Robert Hansen in 2008.

Two layers under one click

What the user seesClaim prizeclickWhat is really under it: a transparent iframeDelete account
Figure 1. The user suspects nothing: both layers coincide in position.

Mechanism. The attacker opens a foreign site in an iframe with the style opacity: 0 and positions it so that the needed button lands right over the decoy. The browser sends the click to the top layer, which is the iframe. Addresses like ?text=… with values that prefill a field let the action be prepared. For success the action in the iframe must also run as the user, that is the session cookie has to be sent. Cookies with SameSite=Lax or Strict are not sent in a cross-site iframe, so the framed page opens logged out; the risk remains where the cookie is SameSite=None and the browser does not partition third-party cookies (Chrome by default), or the embedding happens within the same site.

A real case. On 12 February 2009 a "Don’t Click" prank spread on Twitter: a page had a button with that label, and above it a transparent iframe with a Twitter form whose field was prefilled through the address. A click published a message with a link on behalf of the user, and it reached his followers. A script that stops a page from loading in an iframe ("frame-busting") is unreliable; later the headers described below replaced it. A similar "likejacking" scheme made people press "like" on Facebook.

Defence. The server forbids embedding the page with a header:

Content-Security-Policy: frame-ancestors 'none'

# legacy, still sent for old browsers
X-Frame-Options: DENY
  • frame-ancestors 'none' forbids embedding entirely, 'self' allows only your own origin, a list of origins allows chosen partners. If both headers are sent, frame-ancestors takes priority;
  • X-Frame-Options (DENY or SAMEORIGIN) is older, described in RFC 7034, and its value ALLOW-FROM is obsolete;
  • JavaScript "frame busting" is unreliable (an iframe’s sandbox turns it off), so it stays a fallback;
  • Sensitive actions (deleting, payment) additionally need a confirmation or a re-entered password, and cookies carry SameSite.

How QA checks it. Looks at the headers of pages with actions (login, settings, payment, deletion) in DevTools or curl -I. On an authorized environment builds a local page with <iframe src="…">: if the target page loads, embedding is not forbidden. Exception: pages that partners deliberately embed (payment widgets) must have a closed list in frame-ancestors.

Common mistakes.

  • Relying on JavaScript that checks window.top;
  • Setting the header only on the main page and not on pages with actions;
  • Mixing it up with CSRF: in clickjacking the user makes the click himself and a CSRF token does not help because the request is genuine.

Check yourself

A page has a CSRF token but answers without frame-ancestors and X-Frame-Options. Is it protected from clickjacking?

Answer

No. In clickjacking the user himself makes the request with the token by his click in the frame, so the token is valid. A ban on embedding (frame-ancestors) or a confirmation of the sensitive action is needed.

Why can a page open logged out in a cross-site iframe even if the user is logged in?

Answer

If the session cookie has SameSite=Lax or Strict, the browser does not attach it to requests of an iframe from another site. So the attack works with a SameSite=None cookie or embedding within one site.

In an interview. Junior: Clickjacking is when a site in a transparent iframe lies over a decoy and the user clicks it unknowingly. The defence is the frame-ancestors header (and X-Frame-Options). Middle/Senior: I check the headers of pages with actions and a test frame, partner embeds separately with a closed list. I remember SameSite, confirmation of sensitive actions and that a CSRF token does not protect from clickjacking.