Middle+
Tell me about XSS attacks: types and protection methods.
sobes.tech AI
Answer from AI
XSS (Cross-Site Scripting) is a vulnerability where an attacker injects malicious script into a web page, which is then executed in the browsers of other users.
Types of XSS:
- Stored XSS (persistent) — the malicious script is stored on the server (e.g., in a database) and displayed to all users.
- Reflected XSS — the script is transmitted via URL or form and immediately reflected in the server's response.
- DOM-based XSS — the vulnerability arises from improper handling of data on the client side (in JavaScript), without server involvement.
Protection methods:
- Escaping all user data when outputting in HTML, attributes, JavaScript, CSS.
- Validation and filtering of incoming data on the server.
- Using Content Security Policy (CSP) to restrict script sources.
- Employing modern frameworks that automatically protect against XSS.
Example of escaping in JavaScript:
function escapeHtml(text) {
return text
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
const userInput = '<script>alert("XSS")</script>';
const safeContent = escapeHtml(userInput);
document.getElementById('output').innerHTML = safeContent;
This approach prevents malicious code execution.