Escape HTML entities to prevent Cross-Site Scripting attacks.
Code
Generalrequire 'cgi'
# Escape HTML entities to prevent XSS
safe_output = CGI.escapeHTML(user_input)
return safe_outputParameters
Untrusted user input (try a malicious payload)
What is XSS?
Cross-Site Scripting (XSS) occurs when untrusted data is included in a web page without proper escaping. An attacker can inject malicious scripts that execute in other users' browsers.
# DANGEROUS: Directly embedding user input in HTML
html = "<div>Welcome, #{user_input}!</div>"
# If user_input is "<script>alert('XSS')</script>", the script executes!
Why Escaping Works
The CGI.escapeHTML method converts dangerous characters to HTML entities:
| Character | Escaped | Why |
|---|---|---|
< | < | Prevents opening tags |
> | > | Prevents closing tags |
" | " | Prevents breaking out of attributes |
' | ' | Prevents breaking out of attributes |
& | & | Prevents entity injection |
# SAFE: Escaped output
safe_html = "<div>Welcome, #{CGI.escapeHTML(user_input)}!</div>"
# Renders as text, not executable HTML
In Rails
Rails auto-escapes in ERB templates by default:
<!-- Auto-escaped (safe) -->
<div>Welcome, <%= user_input %></div>
<!-- Raw output (dangerous!) - only if you trust the input -->
<div>Welcome, <%= raw user_input %></div>
<div>Welcome, <%== user_input %></div>
The Rule
Always use CGI.escapeHTML when embedding untrusted data in HTML. In Rails, trust the auto-escaping and avoid raw or html_safe with untrusted data.
More Ruby Snippets
Hash SHA-256
Generate a SHA-256 hash of a string.
Array Difference
Find elements in the first array that are not present in the second array.
Array Frequencies
Count how many times each value appears in an array and return a frequency map.
Array Head
Get the first n elements of an array.
Array Intersection
Find common elements that exist in both arrays.
Array Tail
Get the last n elements of an array.