Cross-Site Scripting (XSS) and DOM-based XSS are common vulnerabilities in web applications that occur when untrusted user input is executed by the browser. These attacks can be prevented by ensuring that all string variables included in the HTML or web client are properly encoded. Below are steps to achieve this security:
Using HTML Escape Functions
Manually encode all user inputs before including them in your HTML. Here is an example function in JavaScript:
function escapeHtml(str) {
return str.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
// Usage
const userInput = "<script>alert('XSS');</script>";
const safeInput = escapeHtml(userInput);
document.body.innerHTML = `<p>${safeInput}</p>`;
Using Frontend Templates
Modern frontend frameworks like React, Angular, Vue, and others include mechanisms to safely handle user inputs. These frameworks automatically encode contexts to prevent XSS attacks.
React Example
In React, the content is automatically escaped:
const userInput = "<script>alert('XSS');</script>";
function App() {
return (
<div>
<p>{userInput}</p> {/* React automatically escapes this */}
</div>
);
}
To safely render HTML (only when absolutely necessary), you can use the dangerouslySetInnerHTML attribute, but use this sparingly and only with sanitized data:
function createMarkup() {
return { __html: 'First · Second' };
}
function MyComponent() {
return <div dangerouslySetInnerHTML={createMarkup()} />;
}
Angular Example
Angular automatically escapes content in templates:
<p>{{ userInput }}</p> <!-- Automatically escapes userInput -->
Use innerHtml property binding cautiously and only with sanitized data:
<div [innerHTML]="safeHtml"></div>
In the corresponding TypeScript file:
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
export class AppComponent {
safeHtml: SafeHtml;
constructor(private sanitizer: DomSanitizer) {
const dangerousHtml = "<script>alert('XSS');</script>";
this.safeHtml = this.sanitizer.bypassSecurityTrustHtml(dangerousHtml);
}
}
Server-Side Encoding
Make sure to encode data server-side as well before sending it to the client:
Node.js Example
Using a package like he:
const he = require('he');
const userInput = "<script>alert('XSS');</script>";
const safeInput = he.encode(userInput);
// Use safeInput to respond to client side
res.send(`<p>${safeInput}</p>`);
Content Security Policy (CSP)
Implementing CSP headers can greatly reduce the risk of XSS:
Content-Security-Policy: default-src 'self'; script-src 'self' 'nonce-abc123';
Update your web server configuration to include these headers.
Review and Sanitize Inputs
Regularly review inputs for malicious attempts and sanitize inputs and outputs to keep your applications secure.
By following these steps and making use of frameworks and best practices, you can mitigate the risks of XSS and DOM-based XSS attacks in your web applications.