-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhtml_security_demo.py
More file actions
130 lines (104 loc) Β· 4.39 KB
/
html_security_demo.py
File metadata and controls
130 lines (104 loc) Β· 4.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Comprehensive demonstration of HTML template security risks
"""
from template_engine import TemplateEngine
def html_security_demo():
"""Demonstrate security risks when auto_escape is disabled for HTML."""
print("π¨ SECURITY DEMO: HTML Templates Without auto_escape")
print("=" * 70)
engine = TemplateEngine()
# Simulate malicious user input
malicious_input = {
'user_name': '<script>alert("Stolen cookies: " + document.cookie)</script>',
'user_bio': '<img src="x" onerror="window.location=\'http://evil-site.com\'">',
'comment': '</textarea><script>alert("XSS in form!")</script><textarea>',
'search_term': '" onmouseover="alert(\'Hover attack!\')" data="'
}
html_template = '''<!DOCTYPE html>
<html>
<head>
<title>User Profile</title>
</head>
<body>
<h1>User: $user_name</h1>
<p>Bio: $user_bio</p>
<div>Comment: $comment</div>
<input type="text" value="$search_term" placeholder="Search...">
</body>
</html>'''
print("π Malicious User Input:")
for key, value in malicious_input.items():
print(f" π {key}: {repr(value)}")
print(f"\nπ SAFE HTML (auto_escape=True):")
print("=" * 50)
safe_html = engine.render(html_template, malicious_input, auto_escape=True)
print(safe_html)
print(f"\nπ DANGEROUS HTML (auto_escape=False):")
print("=" * 50)
dangerous_html = engine.render(html_template, malicious_input, auto_escape=False)
print(dangerous_html)
print(f"\nπ― WHAT HAPPENS IN BROWSER:")
print("=" * 50)
print("β
SAFE VERSION:")
print(" β’ Scripts display as text: <script>...</script>")
print(" β’ No JavaScript execution")
print(" β’ HTML structure preserved")
print(" β’ Users see the actual input, not code")
print("\nβ DANGEROUS VERSION:")
print(" β’ Scripts EXECUTE in browser!")
print(" β’ alert() dialogs would pop up")
print(" β’ Cookies could be stolen")
print(" β’ Users could be redirected to malicious sites")
print(" β’ Form inputs could be hijacked")
def content_type_examples():
"""Show different content types and escaping needs."""
print(f"\n\nπ CONTENT TYPE EXAMPLES")
print("=" * 50)
engine = TemplateEngine()
data = {
'code_snippet': '<div class="highlight">print("Hello")</div>',
'user_message': 'I love <3 your site & want to share it!',
'math_formula': 'if x < 5 && y > 10 then result = x & y',
'html_content': '<p>This is <strong>bold</strong> text</p>'
}
examples = [
("Code Documentation", '$code_snippet'),
("User Message", '$user_message'),
("Math Formula", '$math_formula'),
("Rich Content", '$html_content')
]
for title, template in examples:
print(f"\nπ {title}:")
print(f" Input: {repr(data[template[1:]])}")
escaped = engine.render(template, data, auto_escape=True)
unescaped = engine.render(template, data, auto_escape=False)
print(f" β
Escaped: {escaped}")
print(f" β Unescaped: {unescaped}")
def recommendations():
"""Provide security recommendations."""
print(f"\n\nπ‘ SECURITY RECOMMENDATIONS")
print("=" * 50)
print("π― FOR HTML TEMPLATES:")
print(" β
ALWAYS use auto_escape=True")
print(" β
engine.render(template, data, auto_escape=True)")
print(" β
Escapes: < > & \" to prevent XSS")
print(" β
Preserves Unicode characters")
print("\nπ― FOR TEXT/EMAIL TEMPLATES:")
print(" β
Use auto_escape=False")
print(" β
engine.render(template, data, auto_escape=False)")
print(" β
Preserves all characters exactly")
print(" β
No HTML escaping needed")
print("\nπ― RULE OF THUMB:")
print(" π HTML output β auto_escape=True")
print(" π Text output β auto_escape=False")
print(" π€ When unsure β auto_escape=True (safer!)")
print("\nβ οΈ NEVER DO THIS IN PRODUCTION:")
print(" β engine.render(html_template, user_data, auto_escape=False)")
print(" β Disabling escaping with user-generated content")
print(" β Trusting user input without validation")
if __name__ == "__main__":
html_security_demo()
content_type_examples()
recommendations()