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
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
|
package org.jsoup.safety;
/*
Thank you to Ryan Grove (wonko.com) for the Ruby HTML cleaner http://github.com/rgrove/sanitize/, which inspired
this whitelist configuration, and the initial defaults.
*/
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.jsoup.helper.Validate;
import org.jsoup.nodes.Attribute;
import org.jsoup.nodes.Attributes;
import org.jsoup.nodes.Element;
/**
* Whitelists define what HTML (elements and attributes) to allow through the
* cleaner. Everything else is removed.
* <p/>
* Start with one of the defaults:
* <ul>
* <li>{@link #none}
* <li>{@link #simpleText}
* <li>{@link #basic}
* <li>{@link #basicWithImages}
* <li>{@link #relaxed}
* </ul>
* <p/>
* If you need to allow more through (please be careful!), tweak a base
* whitelist with:
* <ul>
* <li>{@link #addTags}
* <li>{@link #addAttributes}
* <li>{@link #addEnforcedAttribute}
* <li>{@link #addProtocols}
* </ul>
* <p/>
* The cleaner and these whitelists assume that you want to clean a
* <code>body</code> fragment of HTML (to add user supplied HTML into a
* templated page), and not to clean a full HTML document. If the latter is the
* case, either wrap the document HTML around the cleaned body HTML, or create a
* whitelist that allows <code>html</code> and <code>head</code> elements as
* appropriate.
* <p/>
* If you are going to extend a whitelist, please be very careful. Make sure you
* understand what attributes may lead to XSS attack vectors. URL attributes are
* particularly vulnerable and require careful validation. See
* http://ha.ckers.org/xss.html for some XSS attack examples.
*
* @author Jonathan Hedley
*/
public class Whitelist {
private Set<TagName> tagNames; // tags allowed, lower case. e.g. [p, br,
// span]
private Map<TagName, Set<AttributeKey>> attributes; // tag -> attribute[].
// allowed attributes
// [href] for a tag.
private Map<TagName, Map<AttributeKey, AttributeValue>> enforcedAttributes; // always
// set
// these
// attribute
// values
private Map<TagName, Map<AttributeKey, Set<Protocol>>> protocols; // allowed
// URL
// protocols
// for
// attributes
private boolean preserveRelativeLinks; // option to preserve relative links
/**
* This whitelist allows only text nodes: all HTML will be stripped.
*
* @return whitelist
*/
public static Whitelist none() {
return new Whitelist();
}
/**
* This whitelist allows only simple text formatting:
* <code>b, em, i, strong, u</code>. All other HTML (tags and attributes)
* will be removed.
*
* @return whitelist
*/
public static Whitelist simpleText() {
return new Whitelist().addTags("b", "em", "i", "strong", "u");
}
/**
* This whitelist allows a fuller range of text nodes:
* <code>a, b, blockquote, br, cite, code, dd, dl, dt, em, i, li,
ol, p, pre, q, small, strike, strong, sub, sup, u, ul</code>, and
* appropriate attributes.
* <p/>
* Links (<code>a</code> elements) can point to
* <code>http, https, ftp, mailto</code>, and have an enforced
* <code>rel=nofollow</code> attribute.
* <p/>
* Does not allow images.
*
* @return whitelist
*/
public static Whitelist basic() {
return new Whitelist()
.addTags("a", "b", "blockquote", "br", "cite", "code", "dd",
"dl", "dt", "em", "i", "li", "ol", "p", "pre", "q",
"small", "strike", "strong", "sub", "sup", "u", "ul")
.addAttributes("a", "href").addAttributes("blockquote", "cite")
.addAttributes("q", "cite")
.addProtocols("a", "href", "ftp", "http", "https", "mailto")
.addProtocols("blockquote", "cite", "http", "https")
.addProtocols("cite", "cite", "http", "https")
.addEnforcedAttribute("a", "rel", "nofollow");
}
/**
* This whitelist allows the same text tags as {@link #basic}, and also
* allows <code>img</code> tags, with appropriate attributes, with
* <code>src</code> pointing to <code>http</code> or <code>https</code>.
*
* @return whitelist
*/
public static Whitelist basicWithImages() {
return basic()
.addTags("img")
.addAttributes("img", "align", "alt", "height", "src", "title",
"width").addProtocols("img", "src", "http", "https");
}
/**
* This whitelist allows a full range of text and structural body HTML:
* <code>a, b, blockquote, br, caption, cite,
code, col, colgroup, dd, dl, dt, em, h1, h2, h3, h4, h5, h6, i, img, li, ol, p, pre, q, small, strike, strong, sub,
sup, table, tbody, td, tfoot, th, thead, tr, u, ul</code>
* <p/>
* Links do not have an enforced <code>rel=nofollow</code> attribute, but
* you can add that if desired.
*
* @return whitelist
*/
public static Whitelist relaxed() {
return new Whitelist()
.addTags("a", "b", "blockquote", "br", "caption", "cite",
"code", "col", "colgroup", "dd", "div", "dl", "dt",
"em", "h1", "h2", "h3", "h4", "h5", "h6", "i", "img",
"li", "ol", "p", "pre", "q", "small", "strike",
"strong", "sub", "sup", "table", "tbody", "td",
"tfoot", "th", "thead", "tr", "u", "ul")
.addAttributes("a", "href", "title")
.addAttributes("blockquote", "cite")
.addAttributes("col", "span", "width")
.addAttributes("colgroup", "span", "width")
.addAttributes("img", "align", "alt", "height", "src", "title",
"width")
.addAttributes("ol", "start", "type")
.addAttributes("q", "cite")
.addAttributes("table", "summary", "width")
.addAttributes("td", "abbr", "axis", "colspan", "rowspan",
"width")
.addAttributes("th", "abbr", "axis", "colspan", "rowspan",
"scope", "width").addAttributes("ul", "type")
.addProtocols("a", "href", "ftp", "http", "https", "mailto")
.addProtocols("blockquote", "cite", "http", "https")
.addProtocols("img", "src", "http", "https")
.addProtocols("q", "cite", "http", "https");
}
/**
* Create a new, empty whitelist. Generally it will be better to start with
* a default prepared whitelist instead.
*
* @see #basic()
* @see #basicWithImages()
* @see #simpleText()
* @see #relaxed()
*/
public Whitelist() {
tagNames = new HashSet<TagName>();
attributes = new HashMap<TagName, Set<AttributeKey>>();
enforcedAttributes = new HashMap<TagName, Map<AttributeKey, AttributeValue>>();
protocols = new HashMap<TagName, Map<AttributeKey, Set<Protocol>>>();
preserveRelativeLinks = false;
}
/**
* Add a list of allowed elements to a whitelist. (If a tag is not allowed,
* it will be removed from the HTML.)
*
* @param tags
* tag names to allow
* @return this (for chaining)
*/
public Whitelist addTags(String... tags) {
Validate.notNull(tags);
for (String tagName : tags) {
Validate.notEmpty(tagName);
tagNames.add(TagName.valueOf(tagName));
}
return this;
}
/**
* Add a list of allowed attributes to a tag. (If an attribute is not
* allowed on an element, it will be removed.)
* <p/>
* E.g.: <code>addAttributes("a", "href", "class")</code> allows
* <code>href</code> and <code>class</code> attributes on <code>a</code>
* tags.
* <p/>
* To make an attribute valid for <b>all tags</b>, use the pseudo tag
* <code>:all</code>, e.g. <code>addAttributes(":all", "class")</code>.
*
* @param tag
* The tag the attributes are for. The tag will be added to the
* allowed tag list if necessary.
* @param keys
* List of valid attributes for the tag
* @return this (for chaining)
*/
public Whitelist addAttributes(String tag, String... keys) {
Validate.notEmpty(tag);
Validate.notNull(keys);
Validate.isTrue(keys.length > 0, "No attributes supplied.");
TagName tagName = TagName.valueOf(tag);
if (!tagNames.contains(tagName)) {
tagNames.add(tagName);
}
Set<AttributeKey> attributeSet = new HashSet<AttributeKey>();
for (String key : keys) {
Validate.notEmpty(key);
attributeSet.add(AttributeKey.valueOf(key));
}
if (attributes.containsKey(tagName)) {
Set<AttributeKey> currentSet = attributes.get(tagName);
currentSet.addAll(attributeSet);
} else {
attributes.put(tagName, attributeSet);
}
return this;
}
/**
* Add an enforced attribute to a tag. An enforced attribute will always be
* added to the element. If the element already has the attribute set, it
* will be overridden.
* <p/>
* E.g.: <code>addEnforcedAttribute("a", "rel", "nofollow")</code> will make
* all <code>a</code> tags output as
* <code><a href="..." rel="nofollow"></code>
*
* @param tag
* The tag the enforced attribute is for. The tag will be added
* to the allowed tag list if necessary.
* @param key
* The attribute key
* @param value
* The enforced attribute value
* @return this (for chaining)
*/
public Whitelist addEnforcedAttribute(String tag, String key, String value) {
Validate.notEmpty(tag);
Validate.notEmpty(key);
Validate.notEmpty(value);
TagName tagName = TagName.valueOf(tag);
if (!tagNames.contains(tagName)) {
tagNames.add(tagName);
}
AttributeKey attrKey = AttributeKey.valueOf(key);
AttributeValue attrVal = AttributeValue.valueOf(value);
if (enforcedAttributes.containsKey(tagName)) {
enforcedAttributes.get(tagName).put(attrKey, attrVal);
} else {
Map<AttributeKey, AttributeValue> attrMap = new HashMap<AttributeKey, AttributeValue>();
attrMap.put(attrKey, attrVal);
enforcedAttributes.put(tagName, attrMap);
}
return this;
}
/**
* Configure this Whitelist to preserve relative links in an element's URL
* attribute, or convert them to absolute links. By default, this is
* <b>false</b>: URLs will be made absolute (e.g. start with an allowed
* protocol, like e.g. {@code http://}.
* <p />
* Note that when handling relative links, the input document must have an
* appropriate {@code base URI} set when parsing, so that the link's
* protocol can be confirmed. Regardless of the setting of the
* {@code preserve relative
* links} option, the link must be resolvable against the base URI to an
* allowed protocol; otherwise the attribute will be removed.
*
* @param preserve
* {@code true} to allow relative links, {@code false} (default)
* to deny
* @return this Whitelist, for chaining.
* @see #addProtocols
*/
public Whitelist preserveRelativeLinks(boolean preserve) {
preserveRelativeLinks = preserve;
return this;
}
/**
* Add allowed URL protocols for an element's URL attribute. This restricts
* the possible values of the attribute to URLs with the defined protocol.
* <p/>
* E.g.: <code>addProtocols("a", "href", "ftp", "http", "https")</code>
*
* @param tag
* Tag the URL protocol is for
* @param key
* Attribute key
* @param protocols
* List of valid protocols
* @return this, for chaining
*/
public Whitelist addProtocols(String tag, String key, String... protocols) {
Validate.notEmpty(tag);
Validate.notEmpty(key);
Validate.notNull(protocols);
TagName tagName = TagName.valueOf(tag);
AttributeKey attrKey = AttributeKey.valueOf(key);
Map<AttributeKey, Set<Protocol>> attrMap;
Set<Protocol> protSet;
if (this.protocols.containsKey(tagName)) {
attrMap = this.protocols.get(tagName);
} else {
attrMap = new HashMap<AttributeKey, Set<Protocol>>();
this.protocols.put(tagName, attrMap);
}
if (attrMap.containsKey(attrKey)) {
protSet = attrMap.get(attrKey);
} else {
protSet = new HashSet<Protocol>();
attrMap.put(attrKey, protSet);
}
for (String protocol : protocols) {
Validate.notEmpty(protocol);
Protocol prot = Protocol.valueOf(protocol);
protSet.add(prot);
}
return this;
}
boolean isSafeTag(String tag) {
return tagNames.contains(TagName.valueOf(tag));
}
boolean isSafeAttribute(String tagName, Element el, Attribute attr) {
TagName tag = TagName.valueOf(tagName);
AttributeKey key = AttributeKey.valueOf(attr.getKey());
if (attributes.containsKey(tag)) {
if (attributes.get(tag).contains(key)) {
if (protocols.containsKey(tag)) {
Map<AttributeKey, Set<Protocol>> attrProts = protocols
.get(tag);
// ok if not defined protocol; otherwise test
return !attrProts.containsKey(key)
|| testValidProtocol(el, attr, attrProts.get(key));
} else { // attribute found, no protocols defined, so OK
return true;
}
}
}
// no attributes defined for tag, try :all tag
return !tagName.equals(":all") && isSafeAttribute(":all", el, attr);
}
private boolean testValidProtocol(Element el, Attribute attr,
Set<Protocol> protocols) {
// try to resolve relative urls to abs, and optionally update the
// attribute so output html has abs.
// rels without a baseuri get removed
String value = el.absUrl(attr.getKey());
if (value.length() == 0) {
value = attr.getValue(); // if it could not be made abs, run as-is
// to allow custom unknown protocols
}
if (!preserveRelativeLinks) {
attr.setValue(value);
}
for (Protocol protocol : protocols) {
String prot = protocol.toString() + ":";
if (value.toLowerCase().startsWith(prot)) {
return true;
}
}
return false;
}
Attributes getEnforcedAttributes(String tagName) {
Attributes attrs = new Attributes();
TagName tag = TagName.valueOf(tagName);
if (enforcedAttributes.containsKey(tag)) {
Map<AttributeKey, AttributeValue> keyVals = enforcedAttributes
.get(tag);
for (Map.Entry<AttributeKey, AttributeValue> entry : keyVals
.entrySet()) {
attrs.put(entry.getKey().toString(), entry.getValue()
.toString());
}
}
return attrs;
}
// named types for config. All just hold strings, but here for my sanity.
static class TagName extends TypedValue {
TagName(String value) {
super(value);
}
static TagName valueOf(String value) {
return new TagName(value);
}
}
static class AttributeKey extends TypedValue {
AttributeKey(String value) {
super(value);
}
static AttributeKey valueOf(String value) {
return new AttributeKey(value);
}
}
static class AttributeValue extends TypedValue {
AttributeValue(String value) {
super(value);
}
static AttributeValue valueOf(String value) {
return new AttributeValue(value);
}
}
static class Protocol extends TypedValue {
Protocol(String value) {
super(value);
}
static Protocol valueOf(String value) {
return new Protocol(value);
}
}
abstract static class TypedValue {
private String value;
TypedValue(String value) {
Validate.notNull(value);
this.value = value;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((value == null) ? 0 : value.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
TypedValue other = (TypedValue) obj;
if (value == null) {
if (other.value != null) {
return false;
}
} else if (!value.equals(other.value)) {
return false;
}
return true;
}
@Override
public String toString() {
return value;
}
}
}
|