Cross-site scripting (XSS)
Hücumçunun yazdığı mətn səhifəndə necə koda çevrilir: reflected, stored və DOM-based XSS, təhlükəli sink-lər, kontekstə uyğun encoding, framework-lərin escape hatch-ləri, sanitizasiya, strict CSP, Trusted Types və əlavə müdafiə qatı kimi cookie-lər.
Oxu səviyyəsi
Seçilmiş səviyyəyə qədər olan bölmələr göstərilir.
Başlamazdan əvvəl
İlkin şərt yoxdur.
Bu mövzu Junior səviyyəsindən başlayır.
XSS nədir və hücumçu nə edə bilər
Cross-site scripting (XSS) sayt hücumçunun idarə edə biləcəyi girişi götürüb onu səhifəyə elə yerləşdirəndə baş verir ki, brauzer onu kod kimi icra edir. Bundan sonra hücumçunun skripti sənin origin-ində işləyir, sanki onu sən yazmısan. Same-origin policy artıq heç nəyi qorumur, çünki kod onsuz da içəridədir.
const params = new URLSearchParams(location.search);
document.querySelector("#greeting").innerHTML = "Hello, " + params.get("name");?name=Ada ilə bu kod Ada-nı salamlayır. ?name=<img src=x onerror="steal()"> ilə isə brauzer dəyəri HTML kimi parse edir, şəkil yüklənmir və onerror handler-i işə düşür. Hücumçuya bu URL-li bir link kifayətdir.
Hücumçunun kodu nə edə bilər
O səhifədə sənin JavaScript-inin edə bildiyi hər şeyi, istifadəçinin sessiyası ilə:
- İstifadəçinin adından işləmək. İstifadəçinin cookie-ləri ilə same-origin sorğular göndərmək: çatdırılma ünvanını və ya e-poçtu dəyişmək, sifariş vermək, məzmun dərc etmək.
- Səhifəni oxumaq. Şəxsi məlumatlar, mesajlar, HTML-ə yazılmış CSRF token-ləri, DOM-dakı hər şey.
- Storage-ı oxumaq.
localStoragevə yasessionStorage-dakı token-lər hücumçuya göndərilə və istənilən yerdən yenidən istifadə oluna bilər. - Səhifəni dəyişmək. Sənin real domenində saxta login forması göstərmək, formalardakı klaviatura basışlarını yazmaq.
Adətən edə bilmədiyi şey HttpOnly cookie-ni oxumaqdır: document.cookie onu göstərmir. Bu, sessiyanı sonradan istifadə üçün oğurlamağı çətinləşdirir, amma hücumu dayandırmır — səhifə açıq olduqca skriptə istifadəçi adından sorğu göndərmək üçün cookie-nin özü lazım deyil.
Niyə vacibdir
XSS görüntü bug-ını hesabın ələ keçirilməsinə çevirir. O, hələ də veb tətbiqlərdə ən çox rast gəlinən zəifliklərdən biridir və backend qədər frontend problemidir: bir çox XSS bug-ı serverin template-lərinə heç toxunmur, tamamilə klient tərəfindəki kodda yaşayır.
Əsas məqamlar
- XSS = hücumçunun idarə etdiyi məlumatın səhifəndə kod (HTML, JavaScript, URL) kimi şərh olunması.
- Təsiri "
alert()açılır" yox, "hücumçu sənin saytında istifadəçinin özüdür" deməkdir. - Müdafiə məlumatı məlumat olaraq saxlamaqdır: dəqiq kontekst üçün encode və ya sanitizasiya et, gözdən qaçan səhvlər üçün isə brauzerin tətbiq etdiyi qatlar (CSP, Trusted Types) əlavə et.
Cross-site scripting (XSS) happens when a site takes input an attacker can control and puts it into a page in a way that the browser runs it as code. The attacker's script then runs in your origin, as if you had written it. The same-origin policy no longer protects anything, because the code is already inside.
const params = new URLSearchParams(location.search);
document.querySelector("#greeting").innerHTML = "Hello, " + params.get("name");With ?name=Ada this greets Ada. With ?name=<img src=x onerror="steal()"> the browser parses the value as HTML, the image fails to load, and the onerror handler runs. A link with that URL is all an attacker needs.
What the attacker's code can do
Everything your own JavaScript can do on that page, with the user's session:
- Act as the user. Send same-origin requests with the user's cookies attached: change the delivery address or email, place an order, post content.
- Read the page. Personal data, messages, CSRF tokens rendered into the HTML, anything in the DOM.
- Read storage. Tokens in
localStorageorsessionStoragecan be sent to the attacker and reused from anywhere. - Change the page. Show a fake login form on your real domain, record keystrokes in forms.
What it usually cannot do is read an HttpOnly cookie: document.cookie does not expose it. That limits stealing the session for later, but it does not stop the attack — the script does not need the cookie to send requests as the user while the page is open.
Why it matters
XSS turns a display bug into account takeover. It is still one of the most common vulnerabilities in web apps, and it is a frontend problem as much as a backend one: many XSS bugs never touch the server's templates and live entirely in client-side code.
Key points
- XSS = attacker-controlled data interpreted as code (HTML, JavaScript, URLs) in your page.
- The impact is "the attacker is the user on your site", not just "an
alert()pops up". - The defence is to keep data as data: encode or sanitise for the exact context, and add browser-enforced layers (CSP, Trusted Types) for the mistakes that slip through.
Reflected, stored və DOM-based XSS
XSS adətən zərərli girişin haradan gəldiyinə və harada koda çevrildiyinə görə qruplaşdırılır.
Reflected XSS
Server sorğudan gələn girişi birbaşa cavaba yazır:
app.get("/search", (req, res) => {
res.send(`<h1>Results for ${req.query.q}</h1>`);
});Payload URL-dədir. Hücumçu qurbanı xüsusi hazırlanmış linki açmağa məcbur etməlidir (e-poçt, çat mesajı, redirect) və hücum yalnız linki açanlara təsir edir.
Stored XSS
Payload saxlanılır — rəy, şərh, profil adı, dəstək sorğusu — və sonradan ona baxan hər kəs üçün render olunur. Xüsusi link lazım deyil, hücum hər ziyarətçiyə təsir edə və istifadəçi məzmununa back office-də baxan admin-lərə də çata bilər. MDN onu məhz buna görə xüsusilə ciddi adlandırır.
Tipik hal: istifadəçilər bir az formatlama edə bilsin deyə şərhlər innerHTML ilə render olunur. Onda içində <img src=x onerror=…> olan bir şərh mövzunu açan hər kəsin səhifəsində işə düşür.
DOM-based XSS
Bütün axın brauzerdə gedir: klient kodu hücumçunun təsir edə biləcəyi mənbəni (source) oxuyur və onu şərh edən sink-ə yazır.
const tab = decodeURIComponent(location.hash.slice(1));
document.querySelector("#title").innerHTML = tab;Tipik mənbələr: location.search, location.hash, document.referrer, window.name, postMessage məlumatı və sənin öz API-ndən gələn, amma istifadəçinin yazdığı məlumat. URL-in #-dan sonrakı hissəsi serverə heç vaxt göndərilmir, ona görə serverdəki filtrlər və log-lar belə payload-u heç görmür. Onu klient kodunun review-u və brauzerin tətbiq etdiyi nəzarət (Trusted Types) tutur.
Kateqoriyalar kəsişir
Saxlanmış dəyəri klient kodu innerHTML-ə render edə bilər (həm stored, həm də DOM-based). Adlar bug-ı axtarmağa kömək edir, düzəliş isə hər yerdə eynidir: etibarsız məlumatın interpretator-la görüşdüyü yeri tap və ora məlumat kimi çatdığından əmin ol.
Code review-da veriləcək suallar
- Bu dəyər haradan gələ bilər? Onu kim yaza bilər — indi və ya bir ildən sonra?
- O, harada bitir — mətndə, atributda, URL-də, skriptdə?
- Həmin yer məhz bu kontekst üçün encode və ya sanitizasiya olunurmu?
XSS is usually grouped by where the malicious input comes from and where it is turned into code.
Reflected XSS
The server takes input from the request and puts it straight into the response:
app.get("/search", (req, res) => {
res.send(`<h1>Results for ${req.query.q}</h1>`);
});The payload lives in the URL. The attacker has to get the victim to open a crafted link (an email, a chat message, a redirect), and it hits only the people who open it.
Stored XSS
The payload is saved — a review, a comment, a profile name, a support ticket — and rendered later for everyone who views it. No crafted link is needed, it can hit every visitor, and it can reach admins who look at user content in a back office. MDN calls it particularly severe for that reason.
A typical case: comments rendered with innerHTML so that users can use a little formatting. One comment containing <img src=x onerror=…> then runs in the page of everyone who opens the thread.
DOM-based XSS
The whole flow happens in the browser: client-side code reads a source an attacker can influence and writes it into a sink that interprets it.
const tab = decodeURIComponent(location.hash.slice(1));
document.querySelector("#title").innerHTML = tab;Typical sources: location.search, location.hash, document.referrer, window.name, postMessage data, and data from your own API that a user wrote. The URL fragment after # is never sent to the server, so server-side filters and logs never see such a payload. Client-side code review and browser-enforced controls (Trusted Types) are what catch it.
The categories overlap
A stored value can be rendered by client-side code into innerHTML (stored and DOM-based). The labels help you search for the bug; the fix is the same everywhere: find where untrusted data meets an interpreter, and make sure it arrives there as data.
Questions to ask in a code review
- Where can this value come from? Who can write it, now or in a year?
- Where does it end up — text, an attribute, a URL, a script?
- Is that place encoded or sanitised for exactly that context?
Təhlükəli sink-lər: sətir harada koda çevrilir
Sink sətri HTML, JavaScript və ya yüklənəcək, keçid ediləcək URL kimi şərh edən API-dir. XSS bug-larının çoxu etibarsız məlumatla qidalanan sink-dir. Code review-da onları tanımağı öyrən.
HTML sink-ləri
element.innerHTML, outerHTML, insertAdjacentHTML(), document.write(), Range.createContextualFragment() və onların üzərindəki örtüklər (jQuery-nin .html()-i, React-in dangerouslySetInnerHTML-i, Vue-nun v-html-i).
Geniş yayılmış yanlış təhlükəsizlik hissi: innerHTML ilə əlavə olunan <script> elementləri icra olunmur. Amma başqa çox şey icra olunur:
el.innerHTML = "<script>steal()</script>";
el.innerHTML = '<img src=x onerror="steal()">';
el.innerHTML = "<details open ontoggle=steal()>";Birinci sətir heç nə etmir; ikinci və üçüncü isə şəkil yüklənməyəndə və ya element açılan kimi steal()-i çağırır. document.write() daha pisdir: onun yazdığı skriptlər icra olunur.
JavaScript sink-ləri
eval(), new Function(string) və funksiya əvəzinə sətirlə çağırılan setTimeout / setInterval. Bunların hər biri məlumatı birbaşa koda çevirir:
setTimeout("showToast('" + message + "')", 1000);
setTimeout(() => showToast(message), 1000);Birinci sətir sink-dir; ikincisi funksiya ötürür və message-in içində nə olursa olsun, təhlükəsizdir.
URL sink-ləri
javascript: URL-i brauzer ona keçid edəndə öz kodunu icra edir: <a href>, <form action>, <iframe src>, location.href = …, window.open(…). Dəyəri yoxlanmayan "istifadəçinin saytına link" sahəsi də sink-dir:
link.href = profile.website;Burada escape kömək etmir (javascript:-də escape ediləcək simvol yoxdur); sxem allow-list ilə yoxlanmalıdır.
Atribut və handler sink-ləri
Inline event handler atributları (onclick, onerror, onload, …) JavaScript-dir. el.setAttribute("onclick", value) və ya <div onclick="…${value}…"> qurmaq məlumatı skriptə yerləşdirir. <script> və ya <iframe>-dəki src, iframe-in srcdoc-u da belədir.
Təhlükəsiz qarşılıqlar
textContent,innerText,createTextNode()və input-unvalue-su — həmişə mətndir, heç vaxt parse olunmur.- Handler atributları əvəzinə funksiya ilə
addEventListener(). - Zərərsiz atributlar (
title,alt,data-*) üçünsetAttribute(), URL atributları üçün isə yalnız sxem yoxlamasından sonra. - Məlumat üçün
eval()əvəzinəJSON.parse().
demək olar ki, hər təhlükəli API üçün təhlükəsiz qarşılığı var; DOM-based XSS-in çoxunu "sink-i tap, mətn API-si ilə əvəz et" yanaşması düzəldir.
A sink is an API that interprets a string as HTML, JavaScript or a URL to load or navigate to. Most XSS bugs are a sink fed with untrusted data. Learn to spot them in code review.
HTML sinks
element.innerHTML, outerHTML, insertAdjacentHTML(), document.write(), Range.createContextualFragment(), and wrappers around them (jQuery's .html(), React's dangerouslySetInnerHTML, Vue's v-html).
A common false sense of safety: <script> elements inserted with innerHTML do not run. Many other things do:
el.innerHTML = "<script>steal()</script>";
el.innerHTML = '<img src=x onerror="steal()">';
el.innerHTML = "<details open ontoggle=steal()>";The first line does nothing; the second and third run steal() as soon as the image fails or the element opens. document.write() is worse: scripts it writes are executed.
JavaScript sinks
eval(), new Function(string), and setTimeout / setInterval called with a string instead of a function. Any of them turns data into code directly:
setTimeout("showToast('" + message + "')", 1000);
setTimeout(() => showToast(message), 1000);The first line is a sink; the second passes a function and is safe whatever message contains.
URL sinks
A javascript: URL runs its code when the browser navigates to it: <a href>, <form action>, <iframe src>, location.href = …, window.open(…). A "link to the user's website" field is a sink if the value is not checked:
link.href = profile.website;Escaping does not help here (javascript: contains nothing to escape); the scheme must be allow-listed.
Attribute and handler sinks
Inline event handler attributes (onclick, onerror, onload, …) are JavaScript. el.setAttribute("onclick", value) or building <div onclick="…${value}…"> puts data into a script. So does src on <script> or <iframe>, and srcdoc on an iframe.
Safe counterparts
textContent,innerText,createTextNode()and an input'svalue— always text, never parsed.addEventListener()with a function instead of handler attributes.setAttribute()for harmless attributes (title,alt,data-*), and URL attributes only after a scheme check.JSON.parse()instead ofeval()for data.
The has a safe API for nearly every unsafe one; "find the sink, replace it with the text API" fixes most DOM-based XSS.
Kontekstə uyğun output encoding
Output encoding hədəf dildə mənası olan simvolları parser-in adi mətn kimi oxuyacağı formaya salır. Vahid "escape" funksiyası yoxdur: nəyin təhlükəli olduğu dəyərin düşdüyü kontekstdən asılıdır, ona görə də çıxış anında məhz həmin kontekst üçün encode edirsən.
HTML mətni və dırnaqlı atributlar
Teqlərin arasında və dırnaq içindəki atribut dəyərlərində bu beş simvolu encode et (OWASP-ın siyahısı):
function escapeHtml(text) {
return text
.replaceAll("&", "&")
.replaceAll("<", "<")
.replaceAll(">", ">")
.replaceAll('"', """)
.replaceAll("'", "'");
}& birinci gəlir, yoxsa indicə yaratdığın hər entity-nin &-ı yenidən encode olunur. Atributları həmişə dırnağa al. Dırnaqsız atributda yeni atribut başlatmaq üçün bir boşluq kifayətdir, escapeHtml isə boşluqlara toxunmur:
<p title="x" onmouseover="steal()">
<p title=x onmouseover=steal()>Birincisi zərərsiz bir title-dır. İkincisi title üstəgəl event handler-dir.
URL-lər
URL-i HTML-encode etmək onu təhlükəsiz etmir: javascript:steal()-da encode ediləcək heç bir simvol yoxdur. Bütöv URL üçün sxemi allow-list ilə yoxla (http:, https:, bəlkə də mailto:). URL-in içindəki dəyər üçünsə yalnız həmin hissəni encode et:
const href = `/search?q=${encodeURIComponent(query)}`;JavaScript və CSS
Skript və ya stil mənbəyini etibarsız məlumatdan qurma; OWASP bunları tək encoding-in etibarlı kömək etmədiyi kontekstlər adlandırır. Server rendering-də klassik bug state-i inline skriptə yerləşdirməkdir:
<script>window.__STATE__ = ${JSON.stringify(state)}</script>JSON.stringify düzgün JavaScript yaradır, amma HTML parser skripti ilk </script>-də bitirir — hətta o, JSON sətrinin içində olsa belə. İçində </script><img src=x onerror=…> olan rəy mətni buradan çölə çıxır. Serializasiya olunmuş JSON-da <-ı \u003c kimi escape et (və ya bunu edən serializer işlət), yaxud məlumatı eyni escape ilə <script type="application/json"> elementinə qoy və JSON.parse(el.textContent) ilə oxu.
Qaydalar
- Çıxışda, həmin çıxışın konteksti üçün encode et. Əvvəlcədən escape olunmuş mətni saxlamaq ikiqat escape-ə və heç kimin escape etmədiyi yerlərdə xam mətnə gətirib çıxarır.
- Ümumiyyətlə encoding tələb etməyən API-lərə üstünlük ver:
textContent, framework-ün mətn interpolyasiyası,URLSearchParams. - Dəyər mütləq HTML olmalıdırsa, encoding yanlış alətdir: sənə sanitizer lazımdır.
Output encoding turns characters that have a meaning in the target language into a form that the parser reads as plain text. There is no single "escape" function: what is dangerous depends on the context the value lands in, so you encode for that context at the moment of output.
HTML text and quoted attributes
Between tags and inside quoted attribute values, encode these five characters (OWASP's list):
function escapeHtml(text) {
return text
.replaceAll("&", "&")
.replaceAll("<", "<")
.replaceAll(">", ">")
.replaceAll('"', """)
.replaceAll("'", "'");
}& goes first, or the & of every entity you just produced is encoded again. Always quote attributes. In an unquoted attribute a space is enough to start a new attribute, and escapeHtml does not touch spaces:
<p title="x" onmouseover="steal()">
<p title=x onmouseover=steal()>The first is one harmless title. The second is a title plus an event handler.
URLs
HTML-encoding a URL does not make it safe: javascript:steal() contains no character to encode. For a whole URL, validate the scheme against an allow-list (http:, https:, maybe mailto:). For a value inside a URL, encode just that part:
const href = `/search?q=${encodeURIComponent(query)}`;JavaScript and CSS
Don't build script or style source from untrusted data; OWASP calls these contexts where encoding alone does not reliably help. A classic server-rendering bug is injecting state into an inline script:
<script>window.__STATE__ = ${JSON.stringify(state)}</script>JSON.stringify produces valid JavaScript, but the HTML parser ends the script at the first </script> — even inside a JSON string. A review text containing </script><img src=x onerror=…> breaks out. Escape < as \u003c in the serialized JSON (or use a serializer that does), or put the data in a <script type="application/json"> element with the same escaping and read it with JSON.parse(el.textContent).
Rules
- Encode at output, for the context of that output. Storing pre-escaped text leads to double escaping and to raw text in places nobody escaped.
- Prefer APIs that need no encoding at all:
textContent, a framework's text interpolation,URLSearchParams. - If a value must be HTML, encoding is the wrong tool: you need a sanitiser.
React və digər framework-lər: avtomatik escape və escape hatch-lər
Müasir framework-lər susmaya görə encode edir. React-də JSX-dəki sətir həmişə mətn kimi render olunur, atribut dəyərləri isə atribut kimi təyin edilir, heç vaxt markup kimi parse olunmur:
function Review({ review }) {
return (
<article title={review.author}>
<p>{review.text}</p>
</article>
);
}review.text <img src=x onerror=…> olsa, istifadəçi məhz bu simvolları görəcək. Server rendering də escape edir: renderToString <img src=x onerror=…> çıxarır. React tətbiqlərində sətir template-ləri ilə qurulan tətbiqlərdən xeyli az XSS bug-ı olmasının səbəbi bu default-dur. Bug-lar escape hatch-lərdə yaşayır.
dangerouslySetInnerHTML
<div dangerouslySetInnerHTML={{ __html: html }} />Bu, innerHTML-i təyin edir və həmin sink-in bütün risklərini daşıyır. react.dev: markup tam etibarlı mənbədən gəlmirsə, bu yolla XSS zəifliyi yaratmaq "çox asandır". O, sanitizasiya olunmuş sətir və ya TrustedHTML obyekti qəbul edir. Hər rast gəldiyin yerə təhlükəsizlik review-u tələb edən məqam kimi bax; react/no-danger ESLint qaydası onları göstərir.
href və src-dəki URL-lər
React dəyəri escape edir, amma escape javascript: URL-ini təhlükəsiz etmir. React 19 onu bloklayır: href, src, action və formAction üçün javascript: URL-ini "React has blocked a javascript: URL as a security precaution." xətası atan URL ilə əvəz edir (react-dom 19.3.0-da, həm klientdə, həm də server rendering-də yoxlanıb). O, yalnız bu sxemi bloklayır. OWASP qeyd edir ki, bu, tətbiq səviyyəsində URL yoxlamasını əvəz etmir: istifadəçinin verdiyi linklər üçün http: və https:-i allow-list et.
Digər escape hatch-lər
- Birbaşa DOM-a müraciət:
ref.current.innerHTML = …və ya istifadəçi sətirləri ötürülən third-party widget. - Etibarsız obyekti props-a yaymaq:
<a {...userProvidedProps}>məlumatahref-i, həttadangerouslySetInnerHTML-i seçməyə imkan verir. - Kitabxananın HTML-ə çevirdiyi və sonra xam halda əlavə olunan Markdown və rich text.
- SSR zamanı inline
<script>-ə yazılan serializasiya olunmuş state (əvvəlki bölməyə bax). - Digər framework-lərdə də eyni mənzərədir: Vue-nun
v-html-i, Svelte-in{@html …}-u, Angular-ın daxili sanitizasiyasını söndürənbypassSecurityTrustHtml()və oxşarları.
Nümunə: HTML sətri olmadan bir az formatlama
**qalın** mətni və sətir keçidlərini dəstəkləyən şərh funksiyası çox vaxt mətni HTML sətrinə çevirib (**…** → <strong>, \n → <br>) onu dangerouslySetInnerHTML-ə verməklə qurulur. Onda istifadəçinin yazdığı qalan hər şey də markup-a çevrilir. Təhlükəsiz variant funksionallığı HTML sətirləri olmadan saxlayır: mətni böl, hissələri React children kimi render et, <strong> və <br>-i isə element kimi yarat. Bir az formatlama lazımdırsa, element qur; HTML və sanitizer-ə yalnız istifadəçilər həqiqətən HTML yazanda müraciət et.
Modern frameworks encode by default. In React, a string in JSX is always rendered as text, and attribute values are set as attributes, never parsed as markup:
function Review({ review }) {
return (
<article title={review.author}>
<p>{review.text}</p>
</article>
);
}If review.text is <img src=x onerror=…>, the user sees exactly those characters. Server rendering escapes too: renderToString outputs <img src=x onerror=…>. This default is why most React apps have far fewer XSS bugs than string-template apps. The bugs live in the escape hatches.
dangerouslySetInnerHTML
<div dangerouslySetInnerHTML={{ __html: html }} />This sets innerHTML, with all the risks of that sink. react.dev: unless the markup comes from a completely trusted source, "it is trivial to introduce an XSS vulnerability this way". It accepts a sanitised string or a TrustedHTML object. Treat every occurrence as a security review item; the ESLint rule react/no-danger flags them.
URLs in href and src
React escapes the value, but escaping does not make a javascript: URL safe. React 19 blocks it: for href, src, action and formAction it replaces a javascript: URL with one that throws "React has blocked a javascript: URL as a security precaution." (checked in react-dom 19.3.0, on the client and in server rendering). It blocks only that scheme. OWASP notes that this does not replace application-level URL validation: allow-list http: and https: for user-supplied links.
Other escape hatches
- Direct DOM access:
ref.current.innerHTML = …, or a third-party widget fed user strings. - Spreading untrusted objects into props:
<a {...userProvidedProps}>lets data choosehrefor evendangerouslySetInnerHTML. - Markdown and rich text rendered to HTML by a library, then inserted raw.
- Serialized state in an inline
<script>during SSR (see the previous section). - Other frameworks have the same shape: Vue's
v-html, Svelte's{@html …}, Angular'sbypassSecurityTrustHtml()and friends, which switch off Angular's built-in sanitising.
Example: a little formatting without HTML strings
A comment feature that supports **bold** and line breaks is often built by turning the text into an HTML string (**…** → <strong>, \n → <br>) and passing it to dangerouslySetInnerHTML. Everything else the user typed becomes markup too. The safe version keeps the feature without HTML strings: split the text, render the parts as React children and create <strong> and <br> as elements. When you only need a little formatting, build elements; reach for HTML plus a sanitiser only when users really author HTML.
HTML və URL-lərin sanitizasiyası
Encoding mətn üçündür. İstifadəçilər həqiqətən HTML yazırsa (rich-text redaktoru, CMS, e-poçt mətnləri), sənə sanitizer lazımdır: o, HTML-i parse edir və yalnız zərərsiz elementlərin və atributların allow-list-ini saxlayır.
Regex yox, dəstəklənən kitabxana işlət
import DOMPurify from "dompurify";
const clean = DOMPurify.sanitize(dirty, {
ALLOWED_TAGS: ["p", "br", "strong", "em", "ul", "ol", "li", "a"],
ALLOWED_ATTR: ["href"],
});
container.innerHTML = clean;OWASP DOMPurify-ı tövsiyə edir. O, event handler atributlarını və href-dəki javascript: kimi təhlükəli URL-ləri silir, parse etmək üçün isə brauzerin öz HTML parser-indən istifadə edir, yəni yoxladığı şey brauzerin quracağı şeyin özüdür. Regex bunu bacarmaz: HTML-də adlar böyük-kiçik hərfə həssas deyil, dırnaqlar məcburi deyil, entity-lər, iç-içə və sınıq markup, kod icra edən onlarla teq və atribut var. <script>…</script>-i silən filtr <img onerror>-a toxunmur, <scr<script></script>ipt> üzərində isə skript teqini özü yaradır.
Sanitizer-i effektiv saxlayan qaydalar:
- Əlavə etməzdən dərhal əvvəl sanitizasiya et və nəticəni dəyişmədən əlavə et. OWASP: sanitizasiyadan sonra məzmunu dəyişmək onu mənasız edə bilər.
- Allow-list-i funksionallığın tələb etdiyi qədər kiçik saxla və kitabxananı yenilə: sanitizer bypass-ları müntəzəm tapılır və düzəldilir.
- Serverdə DOM implementasiyası lazımdır (məsələn, jsdom ilə DOMPurify), ya da sanitizasiyanı brauzerdə et.
HTML Sanitizer API (element.setHTML()) bunu platformanın özünə gətirir. MDN-in uyğunluq məlumatına görə o, Chrome 146 və Firefox 148-də var, Safari-də isə hələ yoxdur, ona görə bu gün kitabxananı əvəz etmir.
URL sxemlərini URL API ilə allow-list et
const ALLOWED = new Set(["http:", "https:", "mailto:"]);
function safeHref(input) {
try {
const url = new URL(input, location.href);
return ALLOWED.has(url.protocol) ? url.href : "about:blank";
} catch {
return "about:blank";
}
}Əvvəlcə parse et, sonra yoxla: URL parser sxemi kiçik hərflərə salır və brauzerlərin də nəzərə almadığı tab-ları, sətir keçidlərini və əvvəldəki boşluqları silir, ona görə Java\tScript:… javascript: kimi görünür. startsWith("javascript:") kimi sətir yoxlaması bu variantları buraxır, block-list isə ağlına gəlməyən sxemləri (data:, vbscript:) buraxır. İcazəli sxemləri yoxla, qadağan olunanları yox.
Aləti seçmək
| Məlumat | Alət |
|---|---|
| Adi mətn | Mətn API-ləri və ya framework interpolyasiyası; sanitizer lazım deyil |
| Bir az formatlama (qalın mətn, sətir keçidləri) | Öz sintaksisini parse et və element yarat |
| İstifadəçinin yazdığı HTML | Ciddi allow-list ilə DOMPurify |
| İstifadəçinin verdiyi linklər | URL API və sxem allow-list-i |
Encoding is for text. When users really do author HTML (a rich-text editor, a CMS, email bodies), you need a sanitiser: it parses the HTML and keeps only an allow-list of harmless elements and attributes.
Use a maintained library, not a regex
import DOMPurify from "dompurify";
const clean = DOMPurify.sanitize(dirty, {
ALLOWED_TAGS: ["p", "br", "strong", "em", "ul", "ol", "li", "a"],
ALLOWED_ATTR: ["href"],
});
container.innerHTML = clean;OWASP recommends DOMPurify. It removes event handler attributes and unsafe URLs such as javascript: in href, and it parses with the browser's own HTML parser, so what it checks is what the browser will build. A regex cannot do that: HTML has case-insensitive names, optional quotes, entities, nested and broken markup, and dozens of tags and attributes that run code. A filter that deletes <script>…</script> leaves <img onerror> untouched, and on <scr<script></script>ipt> it creates a script tag.
Rules that keep a sanitiser effective:
- Sanitise right before inserting, and insert the result unchanged. OWASP: modifying content after sanitising can void it.
- Keep the allow-list as small as the feature needs, and keep the library updated: sanitiser bypasses are found and fixed regularly.
- On the server, a DOM implementation is needed (DOMPurify with jsdom, for example), or sanitise in the browser.
The HTML Sanitizer API (element.setHTML()) brings this into the platform. Per MDN's compatibility data it ships in Chrome 146 and Firefox 148 but not in Safari yet, so it is not a replacement for a library today.
Allow-list URL schemes with the URL API
const ALLOWED = new Set(["http:", "https:", "mailto:"]);
function safeHref(input) {
try {
const url = new URL(input, location.href);
return ALLOWED.has(url.protocol) ? url.href : "about:blank";
} catch {
return "about:blank";
}
}Parse first, then check: the URL parser lowercases the scheme and removes the tabs, newlines and leading spaces that browsers also ignore, so Java\tScript:… is reported as javascript:. A string check like startsWith("javascript:") misses those variants, and a block-list misses schemes you did not think of (data:, vbscript:). Check allowed schemes, not forbidden ones.
Choosing the tool
| Data | Tool |
|---|---|
| Plain text | Text APIs or framework interpolation; no sanitiser needed |
| A little formatting (bold, line breaks) | Parse your own syntax and create elements |
| User-authored HTML | DOMPurify with a strict allow-list |
| User-supplied links | URL API plus a scheme allow-list |
Content Security Policy: strict CSP və report-only
Content Security Policy brauzerə səhifənin hansı skriptlərdən (və digər resurslardan) istifadə edə biləcəyini deyən cavab başlığıdır. O, injection-u düzəltmir; encoding unudulanda əlavə olunmuş kodun işə düşməsinin qarşısını alan ikinci qatdır.
Strict CSP: nonce və ya hash
MDN və web.dev host siyahıları əvəzinə nonce və ya hash əsaslı strict siyasəti tövsiyə edir:
Content-Security-Policy:
script-src 'nonce-R4nd0mPerResp0nse' 'strict-dynamic';
object-src 'none';
base-uri 'none';<script nonce="R4nd0mPerResp0nse" src="/assets/index-5c71ab.js"></script>- Server hər cavab üçün yeni, təxmin olunmayan nonce yaradır və onu render etdiyi hər script teqinə yazır. Əlavə olunmuş markup onu bilə bilməz, ona görə inject edilmiş
<script>işə düşmür. - Statik səhifələr bunun əvəzinə inline skriptlərinin hash-lərini sadalaya bilər (
'sha256-…'). 'strict-dynamic'etibarı ötürür: nonce-lu skriptin yüklədiyi skriptlər (məsələn,document.createElement("script")ilə) də işləyə bilər, beləcə bundler-lər və tag manager-lər işləməyə davam edir. Onu dəstəkləyən brauzerlərdə eyni direktivdəki host siyahıları,'self'və'unsafe-inline'nəzərə alınmır — web.dev dəhttps: 'unsafe-inline'-ı məhz buna görə yalnız çox köhnə brauzerlər üçün ehtiyat variant kimi təklif edir.- Strict siyasət inline event handler-ləri,
javascript:URL-lərini vəeval()-u da bloklayır.onclick="…"-larıaddEventListener()-ə köçürməli olacaqsan.
Host allow-list-ləri niyə zəifdir
script-src 'self' https://cdn.example.com həmin hostlardakı bütün skriptlərə icazə verir. İcazəli hostda JSONP endpoint-i və ya DOM-dakı template-ləri icra edən köhnə kitabxana varsa, hücumçu ondan kod işə salmaq üçün istifadə edə bilər. Strict CSP-nin əsasında duran Google araşdırması ("CSP Is Dead, Long Live CSP!", 2016) allow-list siyasətlərinin əksəriyyətindən yan keçmək mümkün olduğunu göstərdi.
Əvvəlcə report-only
Content-Security-Policy-Report-Only: script-src 'nonce-…' 'strict-dynamic'; object-src 'none'; base-uri 'none'; report-to csp
Reporting-Endpoints: csp="https://shop.example/csp-reports"Report-only başlığı heç nəyi tətbiq etmir, hər pozuntunu bildirir və onu <meta> elementi ilə təyin etmək olmur. report-uri köhnəlib (deprecated), amma MDN bütün brauzerlər report-to-nu dəstəkləyənə qədər onu da göndərməyi məsləhət görür. Səs-küyə hazır ol: brauzer extension-ları da inline skriptlər əlavə edir.
Report-only siyasət hücumu dəqiq təsvir edə bilər — səhifədə inline event handler icra olunub, heç vaxt istifadə etmədiyin hostdan şəkil yüklənib — və yenə də heç birini bloklamaz. Tətbiq olunan siyasətdə script-src handler-i, img-src isə məlumatı çölə daşıyan sorğunu dayandırardı. Bir səhifədə cəmlənən yeni növ hesabatı araşdırılmalı siqnal say, report-only-ni isə son məntəqə yox, bitmə tarixi olan mərhələ kimi qəbul et.
Platformanın review-xss incident-i işləyən mağazada qəribə CSP hesabatlarını mənbəyinə qədər izləməyə imkan verir.
Content Security Policy is a response header that tells the browser which scripts (and other resources) the page may use. It does not fix an injection; it is a second layer that stops injected code from running when encoding was missed.
Strict CSP: nonces or hashes
MDN and web.dev recommend a strict policy, based on nonces or hashes rather than host lists:
Content-Security-Policy:
script-src 'nonce-R4nd0mPerResp0nse' 'strict-dynamic';
object-src 'none';
base-uri 'none';<script nonce="R4nd0mPerResp0nse" src="/assets/index-5c71ab.js"></script>- The server generates a new, unpredictable nonce for every response and puts it on each script tag it renders. Injected markup cannot guess it, so an injected
<script>does not run. - Static pages can list hashes of their inline scripts instead (
'sha256-…'). 'strict-dynamic'passes the trust on: scripts that a nonced script loads (for example withdocument.createElement("script")) may run too, so bundlers and tag managers keep working. In browsers that support it, host lists,'self'and'unsafe-inline'in the same directive are ignored — which is why web.dev suggests addinghttps: 'unsafe-inline'only as a fallback for very old browsers.- A strict policy also blocks inline event handlers,
javascript:URLs andeval(). Expect to refactoronclick="…"intoaddEventListener().
Why host allow-lists are weak
script-src 'self' https://cdn.example.com allows every script on those hosts. If an allowed host serves a JSONP endpoint or an old library that evaluates templates from the DOM, an attacker can use it to run code. Google's research behind strict CSP ("CSP Is Dead, Long Live CSP!", 2016) found that most allow-list policies could be bypassed.
Report-only first
Content-Security-Policy-Report-Only: script-src 'nonce-…' 'strict-dynamic'; object-src 'none'; base-uri 'none'; report-to csp
Reporting-Endpoints: csp="https://shop.example/csp-reports"The report-only header enforces nothing and reports every violation; it cannot be set in a <meta> element. report-uri is deprecated, but MDN suggests sending it alongside report-to until every browser supports report-to. Expect noise: browser extensions inject inline scripts too.
A report-only policy can describe an attack precisely — an inline event handler executing on a page, an image loaded from a host you never use — and still block none of it. Enforced, script-src would stop the handler and img-src the request that carries data out. Treat a new kind of report concentrated on one page as a signal to investigate, and treat report-only as a phase with an end date, not a destination.
The platform's review-xss incident lets you trace strange CSP reports in a running shop back to their source.
Trusted Types, cookie-lər və çoxqatlı müdafiə
Encoding və sanitizasiya hər developer-in hər sink-i düzgün işləməsindən asılıdır. Trusted Types və cookie atributları kimsə səhv edəndə işə düşən, brauzerin tətbiq etdiyi qatlardır.
Trusted Types
Bu CSP direktivi ilə DOM XSS sink-ləri sətir qəbul etməyi dayandırır:
Content-Security-Policy: require-trusted-types-for 'script'; trusted-types reviewsİndi innerHTML-ə, outerHTML-ə, insertAdjacentHTML()-ə, document.write()-a, skriptin src-inə və oxşar sink-lərə adi sətir vermək TypeError atır (sətirlə eval() və new Function() isə EvalError atır). Yalnız policy-nin yaratdığı obyektlər qəbul olunur:
const policy = trustedTypes.createPolicy("reviews", {
createHTML: (input) => DOMPurify.sanitize(input),
});
container.innerHTML = policy.createHTML(review.html);
container.innerHTML = review.html;Birinci mənimsətmə işləyir, ikincisi xəta atır. trusted-types direktivi kodunun yarada biləcəyi policy adlarını sadalayır, beləcə riskli kod kod bazasındakı hər innerHTML-ə yox, review olunmuş bir neçə policy-yə toplanır. API özü heç nəyi sanitizasiya etmir: policy sən ona nə yazmısansa, onu edir. React dangerouslySetInnerHTML-ə verilən TrustedHTML-i brauzerə dəyişmədən ötürür. default adlı policy sink-ə çatan hər adi sətri alır; MDN onu yalnız keçid dövründə tövsiyə edir. Əvvəlcə pozuntuları toplamaq üçün Content-Security-Policy-Report-Only ilə başla.
Dəstək: MDN-ə görə Trusted Types Baseline 2026-dır, 2026-cı ilin fevralından bəri yeni əlçatandır (Chrome 83, Safari 26, Firefox 148). Köhnə brauzerlər onu sadəcə tətbiq etmir.
Cookie-lər və token-lər
HttpOnlycookie-nidocument.cookie-dən gizlədir, ona görə XSS payload-u sessiyanı sonradan istifadə üçün köçürə bilmir.localStorage-da saxlanan token isə başqadır: payload onu oxuyub başqa hosta, məsələn, şəkil URL-i ilə göndərə bilər.HttpOnlysessiya cookie-si ilə bu oğurluq alınmır.SameSitebrauzerin cookie-ni cross-site sorğularda nə vaxt göndərəcəyini məhdudlaşdırır. Bu, CSRF müdafiəsidir. İnject olunmuş skript sənin öz saytında işləyir, ona görə onun sorğuları same-site-dır və cookie onsuz da göndərilir.Securecookie-ni adi HTTP-dən uzaq saxlayır.
Heç biri skriptin səhifə açıq olduqca istifadəçi adından işləməsinə mane olmur: çatdırılma ünvanını dəyişmək üçün bir same-origin sorğu kifayətdir. Həssas dəyişikliklərdən (e-poçt, parol, ödəniş və ya çatdırılma məlumatları) əvvəl yenidən autentifikasiya tələb et.
Yenə də baş verəndə
Render-i düzəlt (əsas səbəb), saxlanmış payload-ları sil, ifşa oluna biləcək sessiya və token-ləri ləğv et, həmin müddətdə edilən əməliyyatları yoxla və payload-u mətn kimi render etdiyini yoxlayan test əlavə et. Sonra indiyədək yalnız hesabat verən CSP-ni tətbiq olunan rejimə keçir.
Encoding and sanitising depend on every developer getting every sink right. Trusted Types and cookie attributes are browser-enforced layers for when someone does not.
Trusted Types
With this CSP directive, DOM XSS sinks stop accepting strings:
Content-Security-Policy: require-trusted-types-for 'script'; trusted-types reviewsPassing a plain string to innerHTML, outerHTML, insertAdjacentHTML(), document.write(), a script's src and similar sinks now throws a TypeError (string eval() and new Function() throw an EvalError). Only objects created by a policy are accepted:
const policy = trustedTypes.createPolicy("reviews", {
createHTML: (input) => DOMPurify.sanitize(input),
});
container.innerHTML = policy.createHTML(review.html);
container.innerHTML = review.html;The first assignment works; the second throws. The trusted-types directive lists the policy names your code may create, so the risky code is concentrated in a few reviewed policies instead of every innerHTML in the codebase. The API sanitises nothing by itself: the policy does what you write in it. React passes a TrustedHTML given to dangerouslySetInnerHTML to the browser unchanged. A policy named default receives every plain string that reaches a sink; MDN recommends it only during migration. Roll out with Content-Security-Policy-Report-Only to collect violations first.
Support: Trusted Types is Baseline 2026, newly available since February 2026 (Chrome 83, Safari 26, Firefox 148, per MDN). Older browsers simply do not enforce it.
Cookies and tokens
HttpOnlyhides a cookie fromdocument.cookie, so an XSS payload cannot copy the session to use later. A token kept inlocalStorageis different: a payload can read it and send it to another host, for example in an image URL. With anHttpOnlysession cookie that theft does not work.SameSitelimits when the browser sends a cookie on cross-site requests. It is a CSRF defence. Injected script runs on your own site, so its requests are same-site and carry the cookie anyway.Securekeeps the cookie off plain HTTP.
None of them stops the script from acting as the user while the page is open: changing a delivery address needs only a same-origin request. Ask for re-authentication before sensitive changes (email, password, payout or delivery details).
When it happens anyway
Fix the rendering (the root cause), remove the stored payloads, revoke the sessions and tokens that could have been exposed, review the actions taken in that window, and add a test that renders the payload as text. Then enforce the CSP you were only reporting.
Müsahibə üçün məsləhətlər
30 saniyəlik cavab. "XSS hücumçunun idarə etdiyi məlumat brauzerin onu kod kimi şərh etdiyi yerə — HTML-ə, skriptə, javascript: URL-inə — çatanda baş verir: hücumçunun skripti bizim origin-də işləyir və istifadəçinin edə bildiyi hər şeyi edə bilir. Mən məlumatı məlumat olaraq saxlamaqla qarşısını alıram: framework-ün mətn render-i və ya kontekstə uyğun encoding, HTML həqiqətən lazım olanda DOMPurify kimi sanitizer, URL-lər üçün sxem allow-list-i. Üstünə brauzerin tətbiq etdiyi qatları əlavə edirəm: nonce əsaslı strict CSP, Trusted Types və HttpOnly sessiya cookie-ləri."
Gözlənilən suallar
- Reflected, stored və DOM-based arasında fərq? Payload haradan gəlir (sorğudan, bazadan, klient tərəfindəki mənbədən) və harada koda çevrilir (serverin HTML-ində və ya klient tərəfindəki sink-də). Hər birinə bir nümunə gətir.
- React XSS-dən qorunurmu? Mətn və atributlar susmaya görə escape olunur, React 19 isə
href,src,actionvəformAction-dakıjavascript:URL-lərini bloklayır. BoşluqlardangerouslySetInnerHTML, ref-lər vasitəsilə birbaşa DOM yazıları, başqa URL sxemləri, etibarsız props-un yayılması və serializasiya olunmuş SSR state-idir. innerHTML-dəki<script>niyə işləmir — deməli,innerHTMLtəhlükəsizdir? Bu yolla əlavə olunan skriptlər işləmir, amma event handler atributları işləyir (<img src=x onerror=…>).HttpOnlyXSS-i dayandırırmı? Xeyr. O, cookie-nin oxunmasını dayandırır; skript yenə də istifadəçi adından sorğu göndərə bilər.- Mövcud tətbiqdə CSP-ni necə tətbiq edərdin? Nonce əsaslı strict siyasət, əvvəlcə hesabat endpoint-i ilə
Content-Security-Policy-Report-Only, inline handler-lərin vəeval-un silinməsi, hesabatların təhlili (extension-lar səs-küy yaradır), sonra tətbiq.
Bal itirdən səhvlər
- XSS-i "
alert()açılır" kimi təqdim etmək. Təsirdən danış: hesab dəyişiklikləri, məlumat oğurluğu, istifadəçi adından əməliyyatlar. - Hər kontekst üçün bir "escape" funksiyası. URL-i və ya skripti HTML-escape etmək onu təhlükəsiz etmir.
- Regex sanitizer-lər və block-list-lər (
replace(/<script>/g, ""),!url.startsWith("javascript:")). - CSP-ni həll adlandırmaq. O, ikinci qatdır; həll sink-dədir.
- WAF-ın problemi həll etdiyini demək. OWASP: WAF-lar XSS-in qarşısını etibarlı şəkildə ala bilmir və encoding-i, təhlükəsiz DOM API-lərini və sanitizasiyanı əvəz etmir.
Senior səviyyəni göstərən məqamlar
Stored XSS incident-ini əvvəldən axıra qədər izah et: onu necə görərdin (bir səhifədə cəmlənən CSP hesabatları, heç kimin etmədiyi hesab dəyişikliyi), sink-i necə tapardın (istifadəçi məzmunu ilə qidalanan HTML sink-lərini axtarmaq), funksionallığı saxlayan düzəliş, cavab tədbirləri (payload-ları silmək, sessiyaları ləğv etmək, əməliyyatları yoxlamaq) və növbətinin qarşısını nə alır (lint qaydaları, tətbiq olunan CSP, Trusted Types, localStorage-dan kənarda saxlanan sessiyalar, testlərdə XSS payload-ları).
A 30-second answer. "XSS is when attacker-controlled data reaches a place where the browser interprets it as code — HTML, a script, a javascript: URL — so the attacker's script runs in our origin and can do anything the user can. I prevent it by keeping data as data: framework text rendering or context-specific encoding, a sanitiser like DOMPurify when HTML is really needed, a scheme allow-list for URLs. Then I add browser-enforced layers: a strict nonce-based CSP, Trusted Types, and HttpOnly session cookies."
Questions you are likely to get
- Reflected vs stored vs DOM-based? Where the payload comes from (the request, the database, a client-side source) and where it becomes code (the server's HTML or a client-side sink). Give one example of each.
- Is React safe from XSS? Text and attributes are escaped by default, and React 19 blocks
javascript:URLs inhref,src,actionandformAction. The holes aredangerouslySetInnerHTML, direct DOM writes through refs, other URL schemes, spreading untrusted props and serialized SSR state. - Why doesn't
<script>ininnerHTMLrun — so isinnerHTMLsafe? Scripts inserted that way don't run, but event handler attributes do (<img src=x onerror=…>). - Does
HttpOnlystop XSS? No. It stops reading the cookie; the script can still send requests as the user. - How would you roll out CSP on an existing app? Strict nonce-based policy,
Content-Security-Policy-Report-Onlyfirst with a reporting endpoint, remove inline handlers andeval, triage reports (extensions add noise), then enforce.
Mistakes that cost points
- Treating XSS as "an
alert()pops up". Talk about the impact: account changes, data theft, actions as the user. - One "escape" function for every context. HTML-escaping a URL or a script does not make it safe.
- Regex sanitisers and block-lists (
replace(/<script>/g, ""),!url.startsWith("javascript:")). - Calling CSP the fix. It is a second layer; the fix is at the sink.
- Saying a WAF solves it. OWASP: WAFs cannot reliably prevent XSS and are not a substitute for encoding, safe DOM APIs and sanitising.
Senior signal
Walk through a stored-XSS incident end to end: how you would notice it (CSP reports concentrated on one page, an account change nobody made), how you would find the sink (search for HTML sinks fed with user content), a fix that keeps the feature, the response (remove payloads, revoke sessions, audit actions), and what prevents the next one (lint rules, enforced CSP, Trusted Types, sessions out of localStorage, XSS payloads in tests).
Kodu XSS baxımından review edərkən nəyi yoxlamalı
Bu siyahını özün yazmadığın və səhifəyə məlumat yerləşdirən kodda işlət: komanda yoldaşının pull request-i, kitabxananın issue tracker-indəki snippet və ya AI assistentinin təklifi. Etibarsız məlumatla qidalanan tək bir sink hücumçunun skriptini sənin origin-ində istifadəçinin adından işə salır, adi girişlə yazılmış testlər isə bunu heç vaxt göstərmir.
- Hansısa HTML sink-i (
innerHTML,insertAdjacentHTML(),document.write(),dangerouslySetInnerHTML,v-html) istifadəçinin və ya URL-in idarə edə biləcəyi sətri alırmı? Mətnin yeritextContentvə ya JSX interpolyasiyasıdır.<img src=x onerror=alert(1)>ilə yoxla:<script>payload-u heç nəyi sübut etmir, çünkiinnerHTMLilə əlavə olunan skriptlər icra olunmur. - HTML mütləq HTML qalmalıdırsa, onu əlavə etməzdən dərhal əvvəl kiçik allow-list ilə DOMPurify təmizləyirmi? Regex və ya
replace(/<script>/g, "")kimi block-list<img onerror>-a toxunmur. - İstifadəçinin verdiyi URL-lər sxemlərin allow-list-i ilə yoxlanırmı?
href,src,location.hrefvəwindow.open()javascript:URL-lərini icra edir, escape isə kömək etmir.new URL(input)vəprotocol-unhttp:və yahttps:olduğunu yoxlayan şərt axtar;startsWith("javascript:")"JaVa\tScript:…"-i buraxır, React 19 isə yalnızjavascript:-i bloklayır. - Hansısa sətir koda çevrilirmi?
eval(),new Function(), sətirlə çağırılansetTimeoutvə məlumatdan qurulanonclickatributlarını axtar. Funksiya ötür,addEventListener()işlət, məlumatıJSON.parse()ilə oxu. - Etibarsız obyektlər props-a yayılırmı, məsələn
<a {...data}>? Ondahref-i, həttadangerouslySetInnerHTML-i məlumat özü seçə bilir. - Server rendering-də inline
<script>-ə yazılan state escape olunurmu?JSON.stringify</script>-i olduğu kimi saxlayır, HTML parser isə skripti elə orada bitirir.<-ı\u003ckimi escape et və ya bunu edən serializer işlət. - Sessiya token-ləri
localStorage-dan kənarda saxlanırmı? İnject olunmuş skript onları oxuyub başqa hosta göndərə bilər;HttpOnlycookie isədocument.cookie-dən gizlidir.
Use this list on code you did not write that puts data into a page: a teammate's pull request, a snippet from a library's issue tracker or an AI assistant's suggestion. One sink fed with untrusted data lets an attacker's script run in your origin as the user, and tests with normal input never reveal it.
- Does any HTML sink (
innerHTML,insertAdjacentHTML(),document.write(),dangerouslySetInnerHTML,v-html) receive a string a user or the URL controls? Text belongs intextContentor JSX interpolation. Test with<img src=x onerror=alert(1)>: a<script>payload proves nothing, because scripts inserted withinnerHTMLdo not run. - If HTML must stay HTML, does DOMPurify with a small allow-list clean it right before insertion? A regex or block-list such as
replace(/<script>/g, "")leaves<img onerror>untouched. - Are user-supplied URLs checked against an allow-list of schemes?
href,src,location.hrefandwindow.open()runjavascript:URLs, and escaping does not help. Look fornew URL(input)plus aprotocolcheck forhttp:orhttps:;startsWith("javascript:")misses"JaVa\tScript:…", and React 19 blocks onlyjavascript:. - Is any string turned into code? Look for
eval(),new Function(),setTimeoutwith a string andonclickattributes built from data. Pass functions, useaddEventListener(), parse data withJSON.parse(). - Are untrusted objects spread into props, as in
<a {...data}>? The data can then choosehrefor evendangerouslySetInnerHTML. - In server rendering, is state written into an inline
<script>escaped?JSON.stringifykeeps</script>intact, and the HTML parser ends the script there. Escape<as\u003c, or use a serializer that does. - Are session tokens kept out of
localStorage? An injected script can read and send them to another host; anHttpOnlycookie is hidden fromdocument.cookie.
Özünü yoxla
Təcrübədə sına
Bu mövzudan istifadə edən praktiki işlər.