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
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
#[macro_use]
extern crate html5ever;
#[macro_use]
extern crate maplit;
#[macro_use]
extern crate tendril;
extern crate url;
use html5ever::{driver as html, QualName};
use html5ever::rcdom::{RcDom, NodeData, Handle};
use html5ever::serialize::{serialize, SerializeOpts, TraversalScope};
use html5ever::tree_builder::{NodeOrText, TreeSink};
use std::collections::{HashMap, HashSet};
use tendril::stream::TendrilSink;
use url::Url;
pub fn clean(src: &str) -> String {
Ammonia::default().clean(src)
}
pub struct Ammonia<'a> {
pub tags: HashSet<&'a str>,
pub tag_attributes: HashMap<&'a str, HashSet<&'a str>>,
pub generic_attributes: HashSet<&'a str>,
pub url_schemes: HashSet<&'a str>,
pub url_relative: bool,
pub strip_comments: bool,
pub keep_cleaned_elements: bool,
}
impl<'a> Default for Ammonia<'a> {
fn default() -> Self {
let tags = hashset![
"a", "b", "blockquote", "br", "code", "dd", "del", "dl", "dt",
"em", "i", "h1", "h2", "h3", "hr", "img", "kbd", "li", "ol", "p",
"pre", "s", "strike", "strong", "sub", "sup", "table", "tbody",
"td", "th", "thead", "tr", "ul", "hr"
];
let generic_attributes = hashset![
"title"
];
let tag_attributes = hashmap![
"a" => hashset![
"href"
],
"img" => hashset![
"width", "height", "src", "alt"
]
];
let url_schemes = hashset![
"http", "https", "mailto"
];
Ammonia{
tags: tags,
tag_attributes: tag_attributes,
generic_attributes: generic_attributes,
url_schemes: url_schemes,
url_relative: false,
strip_comments: true,
keep_cleaned_elements: false,
}
}
}
impl<'a> Ammonia<'a> {
pub fn clean(&self, src: &'a str) -> String {
let mut parser = html::parse_fragment(RcDom::default(), html::ParseOpts::default(), QualName::new(None, ns!(), local_name!("div")), vec![]);
parser.process(format_tendril!("{}", src));
let mut dom = parser.finish();
let mut stack = Vec::new();
let body = {
let children = dom.document.children.borrow();
children[0].clone()
};
stack.push(body.clone());
while !stack.is_empty() {
let node = stack.pop().unwrap();
let mut has_children = {
match node.data {
NodeData::Comment{..} | NodeData::Text{..} | NodeData::Doctype{..} | NodeData::ProcessingInstruction{..} => false,
NodeData::Document | NodeData::Element{..} => true,
}
};
while has_children {
let mut children = std::mem::replace(&mut *node.children.borrow_mut(), Vec::new());
for child in &mut children {
self.clean_child(&mut dom, child, node.clone());
}
{
has_children = node.children.borrow().len() != children.len();
}
}
stack.extend(node.children.borrow().iter().cloned());
}
let mut ret_val = Vec::new();
let opts = SerializeOpts{
traversal_scope: TraversalScope::ChildrenOnly,
.. SerializeOpts::default()
};
serialize(&mut ret_val, &body, opts).unwrap();
String::from_utf8(ret_val).unwrap()
}
fn clean_child(&self, dom: &mut RcDom, child: &mut Handle, parent: Handle) {
let pass = {
match child.data {
NodeData::Text{..} => true,
NodeData::Comment{..} => !self.strip_comments,
NodeData::Doctype{..} |
NodeData::Document | NodeData::ProcessingInstruction{..} => false,
NodeData::Element{ref name, ref attrs, ..} => {
let safe_tag = {
if self.tags.contains(&*name.local) {
let attr_filter = |attr: &html5ever::Attribute| {
let whitelisted = self.generic_attributes.contains(&*attr.name.local) ||
self.tag_attributes.get(&*name.local).map(|ta| ta.contains(&*attr.name.local)) == Some(true);
if !whitelisted {
false
} else if &*attr.name.local == "href" || &*attr.name.local == "src" || (&*name.local == "object" && &*attr.name.local == "data") {
let url = Url::parse(&*attr.value);
if let Ok(url) = url {
self.url_schemes.contains(url.scheme())
} else if url == Err(url::ParseError::RelativeUrlWithoutBase) {
self.url_relative
} else {
false
}
} else {
true
}
};
if self.keep_cleaned_elements {
attrs.borrow_mut().retain(attr_filter);
true
} else {
attrs.borrow().iter().all(attr_filter)
}
} else {
false
}
};
if !safe_tag {
for sub in child.children.borrow_mut().iter_mut() {
sub.parent.replace(None);
dom.append(&parent.clone(), NodeOrText::AppendNode(sub.clone()));
}
}
safe_tag
},
}
};
if pass {
child.parent.replace(None);
dom.append(&parent.clone(), NodeOrText::AppendNode(child.clone()));
}
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn included_angles() {
let fragment = "1 < 2";
let result = clean(fragment);
assert_eq!(result, "1 < 2");
}
#[test]
fn remove_script() {
let fragment = "an <script>evil()</script> example";
let result = clean(fragment);
assert_eq!(result, "an evil() example");
}
#[test]
fn ignore_link() {
let fragment = "a <a href=\"http://www.google.com\">good</a> example";
let result = clean(fragment);
assert_eq!(result, fragment);
}
#[test]
fn remove_unsafe_link() {
let fragment = "a <a onclick=\"evil()\" href=\"http://www.google.com\">evil</a> example";
let result = clean(fragment);
assert_eq!(result, "a evil example");
}
#[test]
fn remove_js_link() {
let fragment = "a <a href=\"javascript:evil()\">evil</a> example";
let result = clean(fragment);
assert_eq!(result, "a evil example");
}
#[test]
fn tag_rebalance() {
let fragment = "<b>AWESOME!";
let result = clean(fragment);
assert_eq!(result, "<b>AWESOME!</b>");
}
#[test]
fn allow_url_relative() {
let fragment = "<a href=test>Test</a>";
let cleaner = Ammonia{
url_relative: true,
.. Ammonia::default()
};
let result = cleaner.clean(fragment);
assert_eq!(result, "<a href=\"test\">Test</a>");
}
#[test]
fn deny_url_relative() {
let fragment = "<a href=test>Test</a>";
let cleaner = Ammonia{
url_relative: false,
.. Ammonia::default()
};
let result = cleaner.clean(fragment);
assert_eq!(result, "Test");
}
#[test]
fn object_data() {
let fragment = "<span data=\"javascript:evil()\">Test</span><object data=\"javascript:evil()\"></object>M";
let expected = "<span data=\"javascript:evil()\">Test</span>M";
let cleaner = Ammonia{
tags: hashset![
"span", "object"
],
generic_attributes: hashset![
"data"
],
.. Ammonia::default()
};
let result = cleaner.clean(fragment);
assert_eq!(result, expected);
}
#[test]
fn remove_attributes() {
let fragment = "<table border=\"1\"><tr></tr></table>";
let cleaner = Ammonia {
keep_cleaned_elements: true,
.. Ammonia::default()
};
let result = cleaner.clean(fragment);
assert_eq!(result, "<table><tr></tr></table>");
}
#[test]
fn quotes_in_attrs() {
let fragment = "<b title='\"'>contents</b>";
let result = clean(fragment);
assert_eq!(result, "<b title=\""\">contents</b>");
}
#[test]
fn test_10() {
let fragment = "<SCRIPT/alert(10);/";
let result = clean(fragment);
assert_eq!(result, "");
}
#[test]
fn test_11() {
let fragment = "<IMG SRC=\"javas%63ript:alert(11);\">";
let result = clean(fragment);
assert_eq!(result, "");
}
#[test]
fn test_100() {
let fragment = "<!-- Here is a comment: -- This is a nested comment -->\n<a href=\"http://harmless.com/This is still inside the comment: --evadefilter><img onerror=alert(100) src=''/><a href=\"test\">link</a>";
let result = clean(fragment);
assert_eq!(result, "\nlink");
}
}