HTML5 XSS protection strategies
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:
- Attacker submits malicious content to the database
- Server returns a page containing the malicious script
- 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 policyscript-src
: Controls script execution permissionsstyle-src
: Restricts CSS loading sourcesreport-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, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
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
上一篇:响应式设计与性能平衡
下一篇:CSP(内容安全策略)的使用