Перейти к основному содержимому
HTML/JS Execution, Same-Origin Policy, CORS & CSP
Урок 2 из 18

HTML/JS Execution, Same-Origin Policy, CORS & CSP

Understand how browsers parse HTML and run JavaScript, how the Same-Origin Policy isolates sites, and how CORS and Content Security Policy control cross-origin access and script execution.

Начальный 26 мин Веб-безопасность
Этого урока пока нет на выбранном языке — показана версия на другом языке. Перевод готовится.
Только в разрешённой среде — Описанные здесь приёмы применяются только в учебных лабораториях и в системах, которые принадлежат вам или на которые есть письменное разрешение.

Цели обучения

  • Explain how browsers parse HTML into the DOM and execute client-side JavaScript
  • Determine whether two URLs share the same origin using scheme, host, and port
  • Identify dangerous CORS configurations such as arbitrary Origin reflection with credentials
  • Interpret a Content Security Policy header and explain how key directives reduce script risk

Рекомендуется заранее: HTTP-запросы и ответы, cookie и управление сессиями

#Why this matters

In the previous lesson, you saw how browsers exchange HTTP requests and carry session cookies automatically. A browser also builds a live page from HTML and runs JavaScript from remote servers. If any script on one website could read responses from your bank or webmail tab using your stored cookies, a single malicious link would expose every active account.

Modern browser security relies on three layered controls: the Same-Origin Policy (SOP) isolates sites by default, Cross-Origin Resource Sharing (CORS) grants controlled cross-origin exceptions, and Content Security Policy (CSP) restricts which scripts and resources a page may execute.

#How browsers parse HTML and execute JavaScript

When a browser receives HTML, it parses tags into the Document Object Model (DOM), a live tree of elements. Whenever it encounters a script element or an inline event handler like onload, it runs that JavaScript with access to the DOM and any non-HttpOnly cookies.

Because the browser downloads all client-side JavaScript to run it, anyone can read or modify it in Browser DevTools (Network or Sources tab):

javascript
// Vulnerable client-only check: readable and bypassable in DevTools
function unlockReport(pin) {
  if (pin === "4819") {
    fetch("/api/internal-report").then(r => r.text()).then(console.log);
  }
}

Never store secrets or enforce access control solely in browser JavaScript.

#The Same-Origin Policy (SOP)

The origin of a URL is its (scheme, host, port) tuple. Two URLs share an origin only when all three match, as shown when comparing against https://app.lab.local/dashboard (port 443):

Target URL Scheme Host Port Same origin?
https://app.lab.local/settings https app.lab.local 443 Yes
http://app.lab.local/dashboard http app.lab.local 80 No (scheme differs)
https://api.lab.local/dashboard https api.lab.local 443 No (host differs)
https://app.lab.local:8443/dashboard https app.lab.local 8443 No (port differs)

Under SOP, JavaScript on https://attacker.test cannot read HTTP responses from https://app.lab.local. Crucially, SOP restricts reading responses via script, not sending cross-origin img loads or form submissions, which is why cookies also need SameSite flags and CSRF defences.

#Controlled sharing with CORS

Legitimate frontends often call an API on another subdomain, such as https://app.lab.local fetching JSON from https://api.lab.local. CORS lets the API declare allowed readers via response headers.

Cross-origin fetch with CORS headersCross-origin fetch with CORS headersBrowserAPIGET /profile (Origin: https://app.lab.local)200 OK (Access-Control-Allow-Origin: https://app.lab.local)Browser verifies header and allows script to read the response

For non-simple methods like DELETE or custom headers, the browser first sends an OPTIONS preflight request to confirm permission.

CORS becomes dangerous when servers misconfigure trust:

  1. Dynamic Origin reflection with credentials: Echoing any incoming Origin header into Access-Control-Allow-Origin while setting Access-Control-Allow-Credentials: true lets any site read authenticated user data.
  2. Trusting Origin: null: Sandboxed iframe elements send Origin: null, so allow-listing null lets untrusted pages read responses.
  3. Weak string matching: Checking origin.endsWith("lab.local") falsely trusts https://evil-lab.local.
Checking CORS headers with curl on a lab API
$ curl -s -i -H "Origin: https://attacker.test" http://api.lab.local/profile | grep -i "access-control"
Access-Control-Allow-Origin: https://attacker.test
Access-Control-Allow-Credentials: true

Browsers forbid combining wildcard Access-Control-Allow-Origin: * with Access-Control-Allow-Credentials: true, because that would expose private responses to every site.

#Restricting script execution with CSP

Content Security Policy (CSP) uses the Content-Security-Policy response header to restrict which scripts, endpoints, and frames a page may use, limiting the impact of HTML or script injection.

Directive Purpose Safe example
default-src Fallback for unlisted resource types default-src 'self'
script-src Controls which JavaScript may run script-src 'nonce-r8K2mP9q'
connect-src Limits fetch, XHR, and WebSocket targets connect-src 'self' https://api.lab.local
object-src Controls legacy plugins object-src 'none'
base-uri Restricts base tag targets base-uri 'self'
frame-ancestors Lists sites allowed to frame the page frame-ancestors 'none'

Strong policies avoid 'unsafe-inline' and 'unsafe-eval', issuing a fresh cryptographic nonce per response (a nonce="r8K2mP9q" attribute on the script element) so injected inline scripts without the matching nonce are blocked.

#Defending and common mistakes

  • Treating client-side JS as hidden: Users can inspect and modify all browser code in DevTools; enforce secrets and authorization on the server.
  • Reflecting Origin headers blindly: Match Origin against an exact allow-list of scheme, host, and port.
  • Weak CSP rules: Including 'unsafe-inline' or script-src * lets injected scripts execute.
  • Relying on CSP alone: CSP mitigates XSS impact but never replaces context-aware output encoding.

#Summary

  • Browsers parse HTML into the DOM and execute JavaScript with page access, so client-side checks cannot protect secrets.
  • The Same-Origin Policy isolates sites by (scheme, host, port), blocking cross-origin script reads by default.
  • CORS enables selective cross-origin reads, but reflecting arbitrary Origin headers or null with credentials leaks private data.
  • Content Security Policy uses directives like script-src, object-src, and frame-ancestors to constrain scripts and framing.

Проверка знаний

Войдите, чтобы проходить тест, завершать уроки и сохранять прогресс. Войти в систему

Практика: проверьте свои знания