阿里云主机折上折
  • 微信号
Current Site:Index > HTML5 XSS protection strategies

HTML5 XSS protection strategies

Author:Chuan Chen 阅读数:29785人阅读 分类: HTML

Basic Concepts of XSS Attacks in HTML5

XSS (Cross-Site Scripting) attacks execute malicious scripts by injecting them into web pages. HTML5's new features like contentEditable and postMessage expand the attack surface. The typical workflow of a stored XSS attack:

  1. Attacker submits malicious content to the database
  2. Server returns a page containing the malicious script
  3. User's browser executes the malicious code
// Typical XSS injection example  
const userInput = '<script>alert("XSS")</script>';  
document.getElementById('comment').innerHTML = userInput;  

Content Security Policy (CSP)

CSP defines trusted content sources through HTTP headers or meta tags and is one of the most important modern browser defenses. Full policy example:

Content-Security-Policy:  
  default-src 'self';  
  script-src 'self' https://trusted.cdn.com 'unsafe-inline' 'unsafe-eval';  
  style-src 'self' 'unsafe-inline';  
  img-src *;  
  media-src media1.com media2.com;  
  frame-src youtube.com;  
  report-uri /csp-violation-report;  

Key directives:

  • default-src: Default resource loading policy
  • script-src: Controls script execution permissions
  • style-src: Restricts CSS loading sources
  • report-uri: Violation report address

Input Filtering and Output Encoding

Client-Side Filtering Example

function sanitizeInput(input) {  
  const div = document.createElement('div');  
  div.textContent = input;  
  return div.innerHTML  
    .replace(/&/g, "&amp;")  
    .replace(/</g, "&lt;")  
    .replace(/>/g, "&gt;")  
    .replace(/"/g, "&quot;")  
    .replace(/'/g, "&#39;");  
}  

Server-Side Node.js Handling

const escapeHtml = require('escape-html');  

app.post('/comment', (req, res) => {  
  const safeContent = escapeHtml(req.body.content);  
  // Store in database  
});  

HTML5 Security API Applications

Sandbox Attribute for Secure iframes

<iframe  
  src="untrusted.html"  
  sandbox="allow-scripts allow-same-origin"  
  referrerpolicy="no-referrer">  
</iframe>  

Secure Context Restrictions

// Check if running in a secure context  
if (window.isSecureContext) {  
  // Allow access to sensitive APIs like Service Worker  
}  

Data Binding and Template Engine Protections

Angular Auto-Escaping Mechanism

<!-- Auto-escaping -->  
<p>{{ userControlledInput }}</p>  

<!-- Explicitly mark trusted HTML -->  
<p [innerHTML]="trustedHtml"></p>  

Vue.js v-html Protection

new Vue({  
  el: '#app',  
  data: {  
    rawHtml: '<span style="color:red">Red Text</span>'  
  },  
  methods: {  
    sanitize(html) {  
      // Use libraries like DOMPurify  
    }  
  }  
})  

Modern Browser Security Mechanisms

Trusted Types API

// Enable Trusted Types  
Content-Security-Policy: require-trusted-types-for 'script';  

// Create policy  
const policy = trustedTypes.createPolicy('escapePolicy', {  
  createHTML: input => DOMPurify.sanitize(input)  
});  

document.getElementById('user-content').innerHTML = policy.createHTML(untrustedInput);  

Subresource Integrity (SRI)

<script  
  src="https://example.com/script.js"  
  integrity="sha384-oqVuAfXRKap7fdgcCY5uykM6+R9GqQ8K/uxy9rx7HNQlGYl1kPzQho1wx4JwY8wC"  
  crossorigin="anonymous">  
</script>  

Form and User Input Protection

Input Type Validation

<input type="email" pattern="[^@]+@[^@]+\.[a-zA-Z]{2,6}" required>  

<!-- Disable autofill -->  
<input type="text" autocomplete="off">  

File Upload Protection

// Validate file type and content  
function validateFile(file) {  
  const validTypes = ['image/jpeg', 'image/png'];  
  return validTypes.includes(file.type) &&  
         file.size < 2 * 1024 * 1024;  
}  

Secure DOM Manipulation Practices

Safe Node Creation

// Unsafe string concatenation  
document.body.innerHTML = '<div>' + userInput + '</div>';  

// Safe DOM manipulation  
const div = document.createElement('div');  
div.textContent = userInput;  
document.body.appendChild(div);  

Event Handling Protection

// Unsafe onclick binding  
element.setAttribute('onclick', userInput);  

// Secure event listener  
element.addEventListener('click', () => {  
  // Controlled logic  
});  

Same-Origin Policy and Cross-Origin Security

Fine-Grained CORS Control

Access-Control-Allow-Origin: https://trusted-site.com  
Access-Control-Allow-Methods: GET, POST  
Access-Control-Allow-Headers: Content-Type  
Access-Control-Allow-Credentials: true  
Access-Control-Max-Age: 86400  

postMessage Security Verification

// Verify origin when receiving messages  
window.addEventListener('message', (event) => {  
  if (event.origin !== 'https://expected-origin.com') return;  
  // Process message  
});  

Client-Side Storage Security

Web Storage Access Control

// Sensitive data should not be stored in localStorage  
if (data.includes('password')) {  
  throw new Error('Sensitive data prohibited');  
}  

// Use sessionStorage instead  
sessionStorage.setItem('tempData', encryptedData);  

IndexedDB Security Practices

// Use encrypted storage  
const encryptData = (data) => {  
  // Encrypt using Web Crypto API  
};  

db.transaction('store').objectStore('data').add({  
  id: 1,  
  content: encryptData(sensitiveInfo)  
});  

Vulnerability Detection and Response

XSS Auditor Alternatives

// Monitor DOM modifications  
const observer = new MutationObserver((mutations) => {  
  mutations.forEach((mutation) => {  
    if (mutation.addedNodes.length) {  
      checkForMaliciousNodes(mutation.addedNodes);  
    }  
  });  
});  

observer.observe(document.body, {  
  childList: true,  
  subtree: true  
});  

Violation Report Collection

// Handle CSP violation reports  
window.addEventListener('securitypolicyviolation', (e) => {  
  fetch('/report-endpoint', {  
    method: 'POST',  
    body: JSON.stringify({  
      violatedDirective: e.violatedDirective,  
      blockedURI: e.blockedURI,  
      lineNumber: e.lineNumber  
    })  
  });  
});  

本站部分内容来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn

Front End Chuan

Front End Chuan, Chen Chuan's Code Teahouse 🍵, specializing in exorcising all kinds of stubborn bugs 💻. Daily serving baldness-warning-level development insights 🛠️, with a bonus of one-liners that'll make you laugh for ten years 🐟. Occasionally drops pixel-perfect romance brewed in a coffee cup ☕.