PYTHON
Sanitize User-Generated HTML to Prevent XSS Attacks in Python
Learn to prevent Cross-Site Scripting (XSS) by securely sanitizing user-generated HTML content in Python applications using the `bleach` library.
import bleach
def sanitize_user_html(raw_html):
"""
Sanitizes user-generated HTML to prevent XSS attacks.
Allows only a safe subset of HTML tags and attributes.
"""
# Define allowed tags and attributes
# Example: allow basic text formatting, links, images
allowed_tags = [
'p', 'b', 'i', 'u', 'em', 'strong', 'a', 'img',
'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'ul', 'ol', 'li',
'blockquote', 'code', 'pre'
]
allowed_attrs = {
'a': ['href', 'title', 'target'],
'img': ['src', 'alt', 'width', 'height'],
'*': ['class', 'id'] # Allow class/id on all allowed tags
}
# Clean the HTML using bleach
cleaned_html = bleach.clean(
raw_html,
tags=allowed_tags,
attributes=allowed_attrs,
strip=True # Strip disallowed tags rather than escaping their content
)
return cleaned_html
# Example Usage:
user_input = "<script>alert('XSS!');</script><p>Hello, <b>world</b>!</p><a href='javascript:alert(\"XSS\")'>Click me</a>"
safe_html = sanitize_user_html(user_input)
# print(safe_html) # Expected: <p>Hello, <b>world</b>!</p><a>Click me</a>
How it works: This Python snippet demonstrates how to sanitize user-generated HTML to prevent Cross-Site Scripting (XSS) vulnerabilities using the `bleach` library. It defines a whitelist of allowed HTML tags and attributes. Any tags or attributes not explicitly in the whitelist are removed or stripped, ensuring that only safe content is rendered. This is crucial when displaying user input that might contain malicious scripts or unsafe HTML structures.