Debian Codegraph @

closure-library/closure/goog/html/sanitizer/htmlsanitizer.js

raw
1 // Copyright 2016 The Closure Library Authors. All Rights Reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS-IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15
16 /**
17 * @fileoverview An HTML sanitizer that can satisfy a variety of security
18 * policies.
19 *
20 * This package provides html sanitizing functions. It does not enforce string
21 * to string conversion, instead returning a dom-like element when possible.
22 *
23 * Examples of usage of the static {@code goog.goog.html.sanitizer.sanitize}:
24 * <pre>
25 * var safeHtml = goog.html.sanitizer.sanitize('<script src="xss.js" />');
26 * goog.dom.safe.setInnerHtml(el, safeHtml);
27 * </pre>
28 *
29 * @supported IE 10+, Chrome 26+, Firefox 22+, Safari 7.1+, Opera 15+
30 */
31
32 goog.provide('goog.html.sanitizer.HtmlSanitizer');
33 goog.provide('goog.html.sanitizer.HtmlSanitizer.Builder');
34 goog.provide('goog.html.sanitizer.HtmlSanitizerAttributePolicy');
35 goog.provide('goog.html.sanitizer.HtmlSanitizerPolicy');
36 goog.provide('goog.html.sanitizer.HtmlSanitizerPolicyContext');
37 goog.provide('goog.html.sanitizer.HtmlSanitizerPolicyHints');
38 goog.provide('goog.html.sanitizer.HtmlSanitizerUrlPolicy');
39
40 goog.require('goog.array');
41 goog.require('goog.asserts');
42 goog.require('goog.dom');
43 goog.require('goog.dom.NodeType');
44 goog.require('goog.dom.TagName');
45 goog.require('goog.functions');
46 goog.require('goog.html.SafeHtml');
47 goog.require('goog.html.SafeStyle');
48 goog.require('goog.html.SafeStyleSheet');
49 goog.require('goog.html.SafeUrl');
50 goog.require('goog.html.sanitizer.AttributeSanitizedWhitelist');
51 goog.require('goog.html.sanitizer.AttributeWhitelist');
52 goog.require('goog.html.sanitizer.CssSanitizer');
53 goog.require('goog.html.sanitizer.ElementWeakMap');
54 goog.require('goog.html.sanitizer.TagBlacklist');
55 goog.require('goog.html.sanitizer.TagWhitelist');
56 goog.require('goog.html.sanitizer.noclobber');
57 goog.require('goog.html.uncheckedconversions');
58 goog.require('goog.object');
59 goog.require('goog.string');
60 goog.require('goog.string.Const');
61 goog.require('goog.userAgent');
62
63
64 /**
65 * Type for optional hints to policy handler functions.
66 * @typedef {{
67 * tagName: (string|undefined),
68 * attributeName: (string|undefined),
69 * cssProperty: (string|undefined)
70 * }}
71 */
72 goog.html.sanitizer.HtmlSanitizerPolicyHints;
73
74
75 /**
76 * Type for optional context objects to the policy handler functions.
77 * @typedef {{
78 * cssStyle: (?CSSStyleDeclaration|undefined)
79 * }}
80 */
81 goog.html.sanitizer.HtmlSanitizerPolicyContext;
82
83
84 /**
85 * Type for a policy function.
86 * @typedef {function(string, goog.html.sanitizer.HtmlSanitizerPolicyHints=,
87 * goog.html.sanitizer.HtmlSanitizerPolicyContext=,
88 * (function(string, ?=, ?=, ?=):?string)=):?string}
89 */
90 goog.html.sanitizer.HtmlSanitizerPolicy;
91
92
93 /**
94 * Type for a URL policy function.
95 *
96 * @typedef {function(string, !goog.html.sanitizer.HtmlSanitizerPolicyHints=):
97 * ?goog.html.SafeUrl}
98 */
99 goog.html.sanitizer.HtmlSanitizerUrlPolicy;
100
101
102 /**
103 * Type for attribute policy configuration.
104 * @typedef {{
105 * tagName: string,
106 * attributeName: string,
107 * policy: ?goog.html.sanitizer.HtmlSanitizerPolicy
108 * }}
109 */
110 goog.html.sanitizer.HtmlSanitizerAttributePolicy;
111
112
113 /**
114 * Whether the HTML sanitizer is supported. For now mainly exclude
115 * IE9 or below where we know the sanitizer is insecure.
116 * @private @const {boolean}
117 */
118 goog.html.sanitizer.HTML_SANITIZER_SUPPORTED_ =
119 !goog.userAgent.IE || document.documentMode >= 10;
120
121
122 /**
123 * Whether the template tag is supported.
124 * @package @const {boolean}
125 */
126 goog.html.sanitizer.HTML_SANITIZER_TEMPLATE_SUPPORTED =
127 !goog.userAgent.IE || document.documentMode == null;
128
129
130 /**
131 * Prefix used by all internal html sanitizer booking properties.
132 * @private @const {string}
133 */
134 goog.html.sanitizer.HTML_SANITIZER_BOOKKEEPING_PREFIX_ = 'data-sanitizer-';
135
136
137 /**
138 * Temporary attribute name in which html sanitizer uses for bookkeeping.
139 * @private @const {string}
140 */
141 goog.html.sanitizer.HTML_SANITIZER_BOOKKEEPING_ATTR_NAME_ =
142 goog.html.sanitizer.HTML_SANITIZER_BOOKKEEPING_PREFIX_ + 'elem-num';
143
144
145 /**
146 * Attribute name added to span tags that replace unknown tags. The value of
147 * this attribute is the name of the tag before the sanitization occurred.
148 * @private @const {string}
149 */
150 goog.html.sanitizer.HTML_SANITIZER_SANITIZED_ATTR_NAME_ =
151 goog.html.sanitizer.HTML_SANITIZER_BOOKKEEPING_PREFIX_ + 'original-tag';
152
153
154 /**
155 * Attribute name added to blacklisted tags to then filter them from the output.
156 * @private @const {string}
157 */
158 goog.html.sanitizer.HTML_SANITIZER_BLACKLISTED_TAG_ =
159 goog.html.sanitizer.HTML_SANITIZER_BOOKKEEPING_PREFIX_ + 'blacklisted-tag';
160
161
162 /**
163 * Special value for the STYLE container ID, which makes the sanitizer choose
164 * a new random ID on each call to {@link sanitize}.
165 * @private @const {string}
166 */
167 goog.html.sanitizer.RANDOM_CONTAINER_ = '*';
168
169
170 /**
171 * Creates an HTML sanitizer.
172 * @param {!goog.html.sanitizer.HtmlSanitizer.Builder=} opt_builder
173 * @final @constructor @struct
174 */
175 goog.html.sanitizer.HtmlSanitizer = function(opt_builder) {
176 var builder = opt_builder || new goog.html.sanitizer.HtmlSanitizer.Builder();
177
178 builder.installPolicies_();
179
180 /** @private @const {boolean} */
181 this.shouldSanitizeTemplateContents_ =
182 builder.shouldSanitizeTemplateContents_;
183
184 /**
185 * @private @const {!Object<string, !goog.html.sanitizer.HtmlSanitizerPolicy>}
186 */
187 this.attributeHandlers_ = goog.object.clone(builder.attributeWhitelist_);
188
189 /** @private @const {!Object<string, boolean>} */
190 this.tagBlacklist_ = goog.object.clone(builder.tagBlacklist_);
191
192 /** @private @const {!Object<string, boolean>} */
193 this.tagWhitelist_ = goog.object.clone(builder.tagWhitelist_);
194
195 /** @private @const {boolean} */
196 this.shouldAddOriginalTagNames_ = builder.shouldAddOriginalTagNames_;
197
198 // Add whitelist data-* attributes from the builder to the attributeHandlers
199 // with a default cleanUpAttribute function. data-* attributes are inert as
200 // per HTML5 specs, so not much sanitization needed.
201 goog.array.forEach(builder.dataAttributeWhitelist_, function(dataAttr) {
202 goog.asserts.assert(goog.string.startsWith(dataAttr, 'data-'));
203 goog.asserts.assert(!goog.string.startsWith(
204 dataAttr, goog.html.sanitizer.HTML_SANITIZER_BOOKKEEPING_PREFIX_));
205
206 this.attributeHandlers_['* ' + dataAttr.toUpperCase()] =
207 /** @type {!goog.html.sanitizer.HtmlSanitizerPolicy} */ (
208 goog.html.sanitizer.HtmlSanitizer.cleanUpAttribute_);
209 }, this);
210
211 /** @private @const {!goog.html.sanitizer.HtmlSanitizerUrlPolicy} */
212 this.networkRequestUrlPolicy_ = builder.networkRequestUrlPolicy_;
213
214 /** @private @const {?string} */
215 this.styleContainer_ = builder.styleContainer_;
216
217 /** @private @const {boolean} */
218 this.inlineStyleRules_ = builder.inlineStyleRules_;
219 };
220
221
222 /**
223 * Transforms a {@link HtmlSanitizerUrlPolicy} into a
224 * {@link HtmlSanitizerPolicy} by returning a wrapper that calls the {@link
225 * HtmlSanitizerUrlPolicy} with the required arguments and unwraps the returned
226 * {@link SafeUrl}. This is necessary because internally the sanitizer works
227 * with {@HtmlSanitizerPolicy} to sanitize attributes, but its public API must
228 * use {@HtmlSanitizerUrlPolicy} to ensure that callers do not violate SafeHtml
229 * invariants in their custom handlers.
230 * @param {!goog.html.sanitizer.HtmlSanitizerUrlPolicy} urlPolicy
231 * @return {!goog.html.sanitizer.HtmlSanitizerPolicy}
232 * @private
233 */
234 goog.html.sanitizer.HtmlSanitizer.wrapUrlPolicy_ = function(urlPolicy) {
235 return /** @type {!goog.html.sanitizer.HtmlSanitizerPolicy} */ (function(
236 url, policyHints) {
237 var trimmed =
238 goog.html.sanitizer.HtmlSanitizer.cleanUpAttribute_(url, policyHints);
239 var safeUrl = urlPolicy(trimmed, policyHints);
240 if (safeUrl &&
241 goog.html.SafeUrl.unwrap(safeUrl) !=
242 goog.html.SafeUrl.INNOCUOUS_STRING) {
243 return goog.html.SafeUrl.unwrap(safeUrl);
244 } else {
245 return null;
246 }
247 });
248 };
249
250
251
252 /**
253 * The builder for the HTML Sanitizer. All methods except build return this.
254 * @final @constructor @struct
255 */
256 goog.html.sanitizer.HtmlSanitizer.Builder = function() {
257 /**
258 * A set of attribute sanitization functions. Default built-in handlers are
259 * all tag-agnostic by design. Note that some attributes behave differently
260 * when attached to different nodes (for example, the href attribute will
261 * generally not make a network request, but &lt;link href=""&gt; does), and
262 * so when necessary a tag-specific handler can be used to override a
263 * tag-agnostic one.
264 * @private {!Object<string, !goog.html.sanitizer.HtmlSanitizerPolicy>}
265 */
266 this.attributeWhitelist_ = {};
267 goog.array.forEach(
268 [
269 goog.html.sanitizer.AttributeWhitelist,
270 goog.html.sanitizer.AttributeSanitizedWhitelist
271 ],
272 function(wl) {
273 goog.array.forEach(goog.object.getKeys(wl), function(attr) {
274 this.attributeWhitelist_[attr] =
275 /** @type {!goog.html.sanitizer.HtmlSanitizerPolicy} */
276 (goog.html.sanitizer.HtmlSanitizer.cleanUpAttribute_);
277 }, this);
278 },
279 this);
280
281 /**
282 * A set of attribute handlers that should not inherit their default policy
283 * during build().
284 * @private @const {!Object<string, boolean>}
285 */
286 this.attributeOverrideList_ = {};
287
288 /**
289 * Whether the content of TEMPLATE tags (assuming TEMPLATE is whitelisted)
290 * should be sanitized or passed through.
291 * @private {boolean}
292 */
293 this.shouldSanitizeTemplateContents_ = true;
294
295 /**
296 * List of data attributes to whitelist. Data-attributes are inert and don't
297 * require sanitization.
298 * @private @const {!Array<string>}
299 */
300 this.dataAttributeWhitelist_ = [];
301
302 /**
303 * A tag blacklist, to effectively remove an element and its children from the
304 * dom.
305 * @private @const {!Object<string, boolean>}
306 */
307 this.tagBlacklist_ = goog.object.clone(goog.html.sanitizer.TagBlacklist);
308
309 /**
310 * A tag whitelist, to effectively allow an element and its children from the
311 * dom.
312 * @private {!Object<string, boolean>}
313 */
314 this.tagWhitelist_ = goog.object.clone(goog.html.sanitizer.TagWhitelist);
315
316 /**
317 * Whether non-whitelisted and non-blacklisted tags that have been converted
318 * to &lt;span&rt; tags will contain the original tag in a data attribute.
319 * @private {boolean}
320 */
321 this.shouldAddOriginalTagNames_ = false;
322
323 /**
324 * A function to be applied to URLs found on the parsing process which do not
325 * trigger requests.
326 * @private {!goog.html.sanitizer.HtmlSanitizerUrlPolicy}
327 */
328 this.urlPolicy_ = goog.html.sanitizer.HtmlSanitizer.defaultUrlPolicy_;
329
330 /**
331 * A function to be applied to urls found on the parsing process which may
332 * trigger requests.
333 * @private {!goog.html.sanitizer.HtmlSanitizerUrlPolicy}
334 */
335 this.networkRequestUrlPolicy_ =
336 goog.html.sanitizer.HtmlSanitizer.defaultNetworkRequestUrlPolicy_;
337
338 /**
339 * A function to be applied to names found on the parsing process.
340 * @private {!goog.html.sanitizer.HtmlSanitizerPolicy}
341 */
342 this.namePolicy_ = goog.html.sanitizer.HtmlSanitizer.defaultNamePolicy_;
343
344 /**
345 * A function to be applied to other tokens (i.e. classes and IDs) found on
346 * the parsing process.
347 * @private {!goog.html.sanitizer.HtmlSanitizerPolicy}
348 */
349 this.tokenPolicy_ = goog.html.sanitizer.HtmlSanitizer.defaultTokenPolicy_;
350
351 /**
352 * A function to sanitize inline CSS styles. Defaults to deny all.
353 * @private {function(
354 * !goog.html.sanitizer.HtmlSanitizerPolicy,
355 * string,
356 * !goog.html.sanitizer.HtmlSanitizerPolicyHints,
357 * !goog.html.sanitizer.HtmlSanitizerPolicyContext):?string}
358 */
359 this.sanitizeInlineCssPolicy_ = goog.functions.NULL;
360
361 /**
362 * An optional ID to restrict the scope of CSS rules when STYLE tags are
363 * allowed.
364 * @private {?string}
365 */
366 this.styleContainer_ = null;
367
368 /**
369 * Whether rules in STYLE tags should be inlined into style attributes.
370 * @private {boolean}
371 */
372 this.inlineStyleRules_ = false;
373
374 /**
375 * True iff policies have been installed for the instance.
376 * @private {boolean}
377 */
378 this.policiesInstalled_ = false;
379 };
380
381
382 /**
383 * Extends the list of allowed data attributes.
384 * @param {!Array<string>} dataAttributeWhitelist
385 * @return {!goog.html.sanitizer.HtmlSanitizer.Builder}
386 */
387 goog.html.sanitizer.HtmlSanitizer.Builder.prototype.allowDataAttributes =
388 function(dataAttributeWhitelist) {
389 goog.array.extend(this.dataAttributeWhitelist_, dataAttributeWhitelist);
390 return this;
391 };
392
393
394 /**
395 * Allows form tags in the HTML. Without this all form tags and content will be
396 * dropped.
397 * @return {!goog.html.sanitizer.HtmlSanitizer.Builder}
398 */
399 goog.html.sanitizer.HtmlSanitizer.Builder.prototype.allowFormTag = function() {
400 delete this.tagBlacklist_['FORM'];
401 return this;
402 };
403
404
405 /**
406 * Allows STYLE tags. Note that the sanitizer wraps the output of each call to
407 * {@link sanitize} with a SPAN tag, give it a random ID unique across multiple
408 * calls, and then restrict all CSS rules found inside STYLE tags to only apply
409 * to children of the SPAN tag. This means that CSS rules in STYLE tags will
410 * only apply to content provided in the same call to {@link sanitize}. This
411 * feature is not compatible with {@link inlineStyleRules}.
412 * @return {!goog.html.sanitizer.HtmlSanitizer.Builder}
413 */
414 goog.html.sanitizer.HtmlSanitizer.Builder.prototype.allowStyleTag = function() {
415 if (this.inlineStyleRules_) {
416 throw new Error('Rules from STYLE tags are already being inlined.');
417 }
418 delete this.tagBlacklist_['STYLE'];
419 this.styleContainer_ = goog.html.sanitizer.RANDOM_CONTAINER_;
420 return this;
421 };
422
423
424 /**
425 * Fixes the ID of the style container used for CSS rules found in STYLE tags,
426 * and disables automatic wrapping with the container. This allows multiple
427 * calls to {@link sanitize} to share STYLE rules. If opt_styleContainer is
428 * missing, the sanitizer will stop restricting the scope of CSS rules
429 * altogether. Requires {@link allowStyleTag} to be called first.
430 * @param {string=} opt_styleContainer An optional container ID to restrict the
431 * scope of any CSS rule found in STYLE tags.
432 * @return {!goog.html.sanitizer.HtmlSanitizer.Builder}
433 */
434 goog.html.sanitizer.HtmlSanitizer.Builder.prototype.withStyleContainer =
435 function(opt_styleContainer) {
436 if ('STYLE' in this.tagBlacklist_) {
437 throw new Error('STYLE tags must first be allowed through allowStyleTag.');
438 }
439 if (opt_styleContainer != undefined) {
440 if (!/^[a-zA-Z][\w-:\.]*$/.test(opt_styleContainer)) {
441 throw new Error('Invalid ID.');
442 }
443 this.styleContainer_ = opt_styleContainer;
444 } else {
445 this.styleContainer_ = null;
446 }
447 return this;
448 };
449
450
451 /**
452 * Converts rules in STYLE tags into style attributes on the tags they apply to.
453 * This feature is not compatible with {@link withStyleContainer} and {@link
454 * allowStyleTag}. This method requires {@link allowCssStyles} (otherwise rules
455 * would be deleted after being inlined), and is not compatible with {@link
456 * allowStyleTag}.
457 * @return {!goog.html.sanitizer.HtmlSanitizer.Builder}
458 */
459 goog.html.sanitizer.HtmlSanitizer.Builder.prototype.inlineStyleRules =
460 function() {
461 if (this.sanitizeInlineCssPolicy_ == goog.functions.NULL) {
462 throw new Error(
463 'Inlining style rules requires allowing STYLE attributes ' +
464 'first.');
465 }
466 if (!('STYLE' in this.tagBlacklist_)) {
467 throw new Error(
468 'You have already configured the builder to allow STYLE tags in the ' +
469 'output. Inlining style rules would prevent STYLE tags from ' +
470 'appearing in the output and conflict with such directive.');
471 }
472 this.inlineStyleRules_ = true;
473 return this;
474 };
475
476
477 /**
478 * Allows inline CSS styles.
479 * @return {!goog.html.sanitizer.HtmlSanitizer.Builder}
480 */
481 goog.html.sanitizer.HtmlSanitizer.Builder.prototype.allowCssStyles =
482 function() {
483 this.sanitizeInlineCssPolicy_ =
484 goog.html.sanitizer.HtmlSanitizer.sanitizeCssDeclarationList_;
485 return this;
486 };
487
488
489 /**
490 * Extends the tag whitelist (Package-internal utility method only).
491 * @param {!Array<string>} tags The list of tags to be added to the whitelist.
492 * @return {!goog.html.sanitizer.HtmlSanitizer.Builder}
493 * @package
494 */
495 goog.html.sanitizer.HtmlSanitizer.Builder.prototype
496 .alsoAllowTagsPrivateDoNotAccessOrElse = function(tags) {
497 goog.array.forEach(tags, function(tag) {
498 this.tagWhitelist_[tag.toUpperCase()] = true;
499 }, this);
500 return this;
501 };
502
503
504 /**
505 * Extends the attribute whitelist (Package-internal utility method only).
506 * @param {!Array<(string|!goog.html.sanitizer.HtmlSanitizerAttributePolicy)>}
507 * attrs The list of attributes to be added to the whitelist.
508 * @return {!goog.html.sanitizer.HtmlSanitizer.Builder}
509 * @package
510 */
511 goog.html.sanitizer.HtmlSanitizer.Builder.prototype
512 .alsoAllowAttributesPrivateDoNotAccessOrElse = function(attrs) {
513 goog.array.forEach(attrs, function(attr) {
514 if (goog.isString(attr)) {
515 attr = {tagName: '*', attributeName: attr, policy: null};
516 }
517 var handlerName = goog.html.sanitizer.HtmlSanitizer.attrIdentifier_(
518 attr.tagName, attr.attributeName);
519 this.attributeWhitelist_[handlerName] = attr.policy ?
520 attr.policy :
521 /** @type {!goog.html.sanitizer.HtmlSanitizerPolicy} */ (
522 goog.html.sanitizer.HtmlSanitizer.cleanUpAttribute_);
523 this.attributeOverrideList_[handlerName] = true;
524 }, this);
525 return this;
526 };
527
528
529 /**
530 * Turns off sanitization of template tag contents and pass them unmodified
531 * (Package-internal utility method only).
532 * @return {!goog.html.sanitizer.HtmlSanitizer.Builder}
533 * @throws {!Error}
534 * @package
535 */
536 goog.html.sanitizer.HtmlSanitizer.Builder.prototype
537 .keepUnsanitizedTemplateContentsPrivateDoNotAccessOrElse = function() {
538 if (!goog.html.sanitizer.HTML_SANITIZER_TEMPLATE_SUPPORTED) {
539 throw new Error(
540 'Cannot let unsanitized template contents through on ' +
541 'browsers that do not support TEMPLATE.');
542 }
543 this.shouldSanitizeTemplateContents_ = false;
544 return this;
545 };
546
547
548 /**
549 * Allows only the provided whitelist of tags. Tags still need to be in the
550 * TagWhitelist to be allowed.
551 * <p>
552 * SPAN tags are ALWAYS ALLOWED as part of the mechanism required to preserve
553 * the HTML tree structure (when removing non-blacklisted tags and
554 * non-whitelisted tags).
555 * @param {!Array<string>} tagWhitelist
556 * @return {!goog.html.sanitizer.HtmlSanitizer.Builder}
557 * @throws {Error} Thrown if an attempt is made to allow a non-whitelisted tag.
558 */
559 goog.html.sanitizer.HtmlSanitizer.Builder.prototype.onlyAllowTags = function(
560 tagWhitelist) {
561 this.tagWhitelist_ = {'SPAN': true};
562 goog.array.forEach(tagWhitelist, function(tag) {
563 tag = tag.toUpperCase();
564 if (goog.html.sanitizer.TagWhitelist[tag]) {
565 this.tagWhitelist_[tag] = true;
566 } else {
567 throw new Error(
568 'Only whitelisted tags can be allowed. See ' +
569 'goog.html.sanitizer.TagWhitelist.');
570 }
571 }, this);
572 return this;
573 };
574
575
576 /**
577 * Allows only the provided whitelist of attributes, possibly setting a custom
578 * policy for them. The set of tag/attribute combinations need to be a subset of
579 * the currently allowed combinations.
580 * <p>
581 * Note that you cannot define a generic handler for an attribute if only a
582 * tag-specific one is present, and vice versa. To configure the sanitizer to
583 * accept an attribute only for a specific tag when only a generic handler is
584 * whitelisted, use the goog.html.sanitizer.HtmlSanitizerPolicyHints parameter
585 * and simply reject the attribute in unwanted tags.
586 * <p>
587 * Also note that the sanitizer's policy is still called after the provided one,
588 * to ensure that supplying misconfigured policy cannot introduce
589 * vulnerabilities. To completely override an existing attribute policy or to
590 * allow new attributes, see the goog.html.sanitizer.unsafe package.
591 * @param {!Array<(string|!goog.html.sanitizer.HtmlSanitizerAttributePolicy)>}
592 * attrWhitelist The subset of attributes that the sanitizer will accept.
593 * Attributes can come in of two forms:
594 * - string: allow all values for this attribute on all tags.
595 * - HtmlSanitizerAttributePolicy: allows specifying a policy for a
596 * particular tag. The tagName can be "*", which means all tags. If no
597 * policy is passed, the default is to allow all values.
598 * The tag and attribute names are case-insensitive.
599 * Note that the policy for id, URLs, names etc is controlled separately
600 * (using withCustom* methods).
601 * @return {!goog.html.sanitizer.HtmlSanitizer.Builder}
602 * @throws {Error} Thrown if an attempt is made to allow a non-whitelisted
603 * attribute.
604 */
605 goog.html.sanitizer.HtmlSanitizer.Builder.prototype.onlyAllowAttributes =
606 function(attrWhitelist) {
607 var oldWhitelist = this.attributeWhitelist_;
608 this.attributeWhitelist_ = {};
609 goog.array.forEach(attrWhitelist, function(attr) {
610 if (goog.typeOf(attr) === 'string') {
611 attr = {tagName: '*', attributeName: attr.toUpperCase(), policy: null};
612 }
613 var handlerName = goog.html.sanitizer.HtmlSanitizer.attrIdentifier_(
614 attr.tagName, attr.attributeName);
615 if (!oldWhitelist[handlerName]) {
616 throw new Error('Only whitelisted attributes can be allowed.');
617 }
618 this.attributeWhitelist_[handlerName] = attr.policy ?
619 attr.policy :
620 /** @type {goog.html.sanitizer.HtmlSanitizerPolicy} */ (
621 goog.html.sanitizer.HtmlSanitizer.cleanUpAttribute_);
622 }, this);
623 return this;
624 };
625
626
627 /**
628 * Adds the original tag name in the data attribute 'original-tag' when unknown
629 * tags are sanitized to &lt;span&rt;, so that caller can distinguish them from
630 * actual &lt;span&rt; tags.
631 * @return {!goog.html.sanitizer.HtmlSanitizer.Builder}
632 */
633 goog.html.sanitizer.HtmlSanitizer.Builder.prototype.addOriginalTagNames =
634 function() {
635 this.shouldAddOriginalTagNames_ = true;
636 return this;
637 };
638
639
640 /**
641 * Sets a custom network URL policy.
642 * @param {!goog.html.sanitizer.HtmlSanitizerUrlPolicy}
643 * customNetworkReqUrlPolicy
644 * @return {!goog.html.sanitizer.HtmlSanitizer.Builder}
645 */
646 goog.html.sanitizer.HtmlSanitizer.Builder.prototype
647 .withCustomNetworkRequestUrlPolicy = function(customNetworkReqUrlPolicy) {
648 this.networkRequestUrlPolicy_ = customNetworkReqUrlPolicy;
649 return this;
650 };
651
652
653 /**
654 * Sets a custom non-network URL policy.
655 * @param {!goog.html.sanitizer.HtmlSanitizerUrlPolicy} customUrlPolicy
656 * @return {!goog.html.sanitizer.HtmlSanitizer.Builder}
657 */
658 goog.html.sanitizer.HtmlSanitizer.Builder.prototype.withCustomUrlPolicy =
659 function(customUrlPolicy) {
660 this.urlPolicy_ = customUrlPolicy;
661 return this;
662 };
663
664
665 /**
666 * Sets a custom name policy.
667 * @param {!goog.html.sanitizer.HtmlSanitizerPolicy} customNamePolicy
668 * @return {!goog.html.sanitizer.HtmlSanitizer.Builder}
669 */
670 goog.html.sanitizer.HtmlSanitizer.Builder.prototype.withCustomNamePolicy =
671 function(customNamePolicy) {
672 this.namePolicy_ = customNamePolicy;
673 return this;
674 };
675
676
677 /**
678 * Sets a custom token policy.
679 * @param {!goog.html.sanitizer.HtmlSanitizerPolicy} customTokenPolicy
680 * @return {!goog.html.sanitizer.HtmlSanitizer.Builder}
681 */
682 goog.html.sanitizer.HtmlSanitizer.Builder.prototype.withCustomTokenPolicy =
683 function(customTokenPolicy) {
684 this.tokenPolicy_ = customTokenPolicy;
685 return this;
686 };
687
688
689 /**
690 * Wraps a custom policy function with the sanitizer's default policy.
691 * @param {?goog.html.sanitizer.HtmlSanitizerPolicy} customPolicy The custom
692 * policy for the tag/attribute combination.
693 * @param {!goog.html.sanitizer.HtmlSanitizerPolicy} defaultPolicy The
694 * sanitizer's policy that is always called after the custom policy.
695 * @return {!goog.html.sanitizer.HtmlSanitizerPolicy}
696 * @private
697 */
698 goog.html.sanitizer.HtmlSanitizer.wrapPolicy_ = function(
699 customPolicy, defaultPolicy) {
700 return /** @type {!goog.html.sanitizer.HtmlSanitizerPolicy} */ (function(
701 value, hints, ctx, policy) {
702 var result = customPolicy(value, hints, ctx, policy);
703 return result == null ? null : defaultPolicy(result, hints, ctx, policy);
704 });
705 };
706
707
708 /**
709 * Installs the sanitizer's default policy for a specific tag/attribute
710 * combination on the provided whitelist, but only if a policy already exists.
711 * @param {!Object<string, !goog.html.sanitizer.HtmlSanitizerPolicy>}
712 * whitelist The whitelist to modify.
713 * @param {!Object<string, boolean>} overrideList The set of attributes handlers
714 * that should not be wrapped with a default policy.
715 * @param {string} key The tag/attribute combination
716 * @param {!goog.html.sanitizer.HtmlSanitizerPolicy} defaultPolicy The
717 * sanitizer's policy.
718 * @private
719 */
720 goog.html.sanitizer.HtmlSanitizer.installDefaultPolicy_ = function(
721 whitelist, overrideList, key, defaultPolicy) {
722 if (whitelist[key] && !overrideList[key]) {
723 whitelist[key] = goog.html.sanitizer.HtmlSanitizer.wrapPolicy_(
724 whitelist[key], defaultPolicy);
725 }
726 };
727
728
729 /**
730 * Builds and returns a goog.html.sanitizer.HtmlSanitizer object.
731 * @return {!goog.html.sanitizer.HtmlSanitizer}
732 */
733 goog.html.sanitizer.HtmlSanitizer.Builder.prototype.build = function() {
734 return new goog.html.sanitizer.HtmlSanitizer(this);
735 };
736
737
738 /**
739 * Installs the sanitization policies for the attributes.
740 * May only be called once.
741 * @private
742 */
743 goog.html.sanitizer.HtmlSanitizer.Builder.prototype.installPolicies_ =
744 function() {
745 if (this.policiesInstalled_) {
746 throw new Error('HtmlSanitizer.Builder.build() can only be used once.');
747 }
748
749 var installPolicy = goog.html.sanitizer.HtmlSanitizer.installDefaultPolicy_;
750
751 // Binding all the non-trivial attribute sanitizers to the appropriate,
752 // potentially customizable, handling functions at build().
753 installPolicy(
754 this.attributeWhitelist_, this.attributeOverrideList_, '* USEMAP',
755 /** @type {!goog.html.sanitizer.HtmlSanitizerPolicy} */ (
756 goog.html.sanitizer.HtmlSanitizer.sanitizeUrlFragment_));
757
758 var urlAttributes = ['* ACTION', '* CITE', '* HREF'];
759 var urlPolicy =
760 goog.html.sanitizer.HtmlSanitizer.wrapUrlPolicy_(this.urlPolicy_);
761 goog.array.forEach(urlAttributes, function(attribute) {
762 installPolicy(
763 this.attributeWhitelist_, this.attributeOverrideList_, attribute,
764 urlPolicy);
765 }, this);
766
767 var networkUrlAttributes = [
768 // LONGDESC can result in a network request. See b/23381636.
769 '* LONGDESC', '* SRC', 'LINK HREF'
770 ];
771 var networkRequestUrlPolicy =
772 goog.html.sanitizer.HtmlSanitizer.wrapUrlPolicy_(
773 this.networkRequestUrlPolicy_);
774 goog.array.forEach(networkUrlAttributes, function(attribute) {
775 installPolicy(
776 this.attributeWhitelist_, this.attributeOverrideList_, attribute,
777 networkRequestUrlPolicy);
778 }, this);
779
780 var nameAttributes = ['* FOR', '* HEADERS', '* NAME'];
781 goog.array.forEach(nameAttributes, function(attribute) {
782 installPolicy(
783 this.attributeWhitelist_, this.attributeOverrideList_, attribute,
784 /** @type {!goog.html.sanitizer.HtmlSanitizerPolicy} */ (goog.partial(
785 goog.html.sanitizer.HtmlSanitizer.sanitizeName_,
786 this.namePolicy_)));
787 }, this);
788
789 installPolicy(
790 this.attributeWhitelist_, this.attributeOverrideList_, 'A TARGET',
791 /** @type {!goog.html.sanitizer.HtmlSanitizerPolicy} */ (goog.partial(
792 goog.html.sanitizer.HtmlSanitizer.allowedAttributeValues_,
793 ['_blank', '_self'])));
794
795 installPolicy(
796 this.attributeWhitelist_, this.attributeOverrideList_, '* CLASS',
797 /** @type {!goog.html.sanitizer.HtmlSanitizerPolicy} */ (goog.partial(
798 goog.html.sanitizer.HtmlSanitizer.sanitizeClasses_,
799 this.tokenPolicy_)));
800
801 installPolicy(
802 this.attributeWhitelist_, this.attributeOverrideList_, '* ID',
803 /** @type {!goog.html.sanitizer.HtmlSanitizerPolicy} */ (goog.partial(
804 goog.html.sanitizer.HtmlSanitizer.sanitizeId_, this.tokenPolicy_)));
805
806 installPolicy(
807 this.attributeWhitelist_, this.attributeOverrideList_, '* STYLE',
808 /** @type {!goog.html.sanitizer.HtmlSanitizerPolicy} */
809 (goog.partial(this.sanitizeInlineCssPolicy_, networkRequestUrlPolicy)));
810
811 this.policiesInstalled_ = true;
812 };
813
814
815 /**
816 * The default policy for URLs: allow any.
817 * @private @const {!goog.html.sanitizer.HtmlSanitizerUrlPolicy}
818 */
819 goog.html.sanitizer.HtmlSanitizer.defaultUrlPolicy_ =
820 goog.html.SafeUrl.sanitize;
821
822
823 /**
824 * The default policy for URLs which cause network requests: drop all.
825 * @private @const {!goog.html.sanitizer.HtmlSanitizerUrlPolicy}
826 */
827 goog.html.sanitizer.HtmlSanitizer.defaultNetworkRequestUrlPolicy_ =
828 goog.functions.NULL;
829
830
831 /**
832 * The default policy for attribute names: drop all.
833 * @private @const {!goog.html.sanitizer.HtmlSanitizerPolicy}
834 */
835 goog.html.sanitizer.HtmlSanitizer.defaultNamePolicy_ = goog.functions.NULL;
836
837
838 /**
839 * The default policy for other tokens (i.e. class names and IDs): drop all.
840 * @private @const {!goog.html.sanitizer.HtmlSanitizerPolicy}
841 */
842 goog.html.sanitizer.HtmlSanitizer.defaultTokenPolicy_ = goog.functions.NULL;
843
844
845
846 /**
847 * Returns a key into the attribute handlers dictionary given a node name and
848 * an attribute name. If no node name is given, returns a key applying to all
849 * nodes.
850 * @param {?string} nodeName
851 * @param {string} attributeName
852 * @return {string} key into attribute handlers dict
853 * @private
854 */
855 goog.html.sanitizer.HtmlSanitizer.attrIdentifier_ = function(
856 nodeName, attributeName) {
857 if (!nodeName) {
858 nodeName = '*';
859 }
860 return (nodeName + ' ' + attributeName).toUpperCase();
861 };
862
863
864 /**
865 * Sanitizes a list of CSS declarations.
866 * @param {goog.html.sanitizer.HtmlSanitizerPolicy} policySanitizeUrl
867 * @param {string} attrValue
868 * @param {goog.html.sanitizer.HtmlSanitizerPolicyHints} policyHints
869 * @param {goog.html.sanitizer.HtmlSanitizerPolicyContext} policyContext
870 * @return {?string} sanitizedCss from the policyContext
871 * @private
872 */
873 goog.html.sanitizer.HtmlSanitizer.sanitizeCssDeclarationList_ = function(
874 policySanitizeUrl, attrValue, policyHints, policyContext) {
875 if (!policyContext.cssStyle) {
876 return null;
877 }
878 var naiveUriRewriter = function(uri, prop) {
879 policyHints.cssProperty = prop;
880 var sanitizedUrl = policySanitizeUrl(uri, policyHints);
881 if (sanitizedUrl == null) {
882 return null;
883 }
884 return goog.html.uncheckedconversions
885 .safeUrlFromStringKnownToSatisfyTypeContract(
886 goog.string.Const.from(
887 'HtmlSanitizerPolicy created with networkRequestUrlPolicy_ ' +
888 'when installing \'* STYLE\' handler.'),
889 sanitizedUrl);
890 };
891 var sanitizedStyle = goog.html.SafeStyle.unwrap(
892 goog.html.sanitizer.CssSanitizer.sanitizeInlineStyle(
893 policyContext.cssStyle, naiveUriRewriter));
894 return sanitizedStyle == '' ? null : sanitizedStyle;
895 };
896
897
898 /**
899 * Cleans up an attribute value that we don't particularly want to do anything
900 * to. At the moment we just trim the whitespace.
901 * @param {string} attrValue
902 * @param {goog.html.sanitizer.HtmlSanitizerPolicyHints} policyHints
903 * @return {string} sanitizedAttrValue
904 * @private
905 */
906 goog.html.sanitizer.HtmlSanitizer.cleanUpAttribute_ = function(
907 attrValue, policyHints) {
908 return goog.string.trim(attrValue);
909 };
910
911
912 /**
913 * Allows a set of attribute values.
914 * @param {!Array<string>} allowedValues Set of allowed values lowercased.
915 * @param {string} attrValue
916 * @param {goog.html.sanitizer.HtmlSanitizerPolicyHints} policyHints
917 * @return {?string} sanitizedAttrValue
918 * @private
919 */
920 goog.html.sanitizer.HtmlSanitizer.allowedAttributeValues_ = function(
921 allowedValues, attrValue, policyHints) {
922 var trimmed = goog.string.trim(attrValue);
923 return goog.array.contains(allowedValues, trimmed.toLowerCase()) ? trimmed :
924 null;
925 };
926
927
928 /**
929 * Sanitizes URL fragments.
930 * @param {string} urlFragment
931 * @param {goog.html.sanitizer.HtmlSanitizerPolicyHints} policyHints
932 * @return {?string} sanitizedAttrValue
933 * @private
934 */
935 goog.html.sanitizer.HtmlSanitizer.sanitizeUrlFragment_ = function(
936 urlFragment, policyHints) {
937 var trimmed = goog.string.trim(urlFragment);
938 if (trimmed && trimmed.charAt(0) == '#') {
939 // We do not apply the name or token policy to Url Fragments by design.
940 return trimmed;
941 }
942 return null;
943 };
944
945
946 /**
947 * Runs an attribute name through a name policy.
948 * @param {goog.html.sanitizer.HtmlSanitizerPolicy} namePolicy
949 * @param {string} attrName
950 * @param {goog.html.sanitizer.HtmlSanitizerPolicyHints} policyHints
951 * @return {?string} sanitizedAttrValue
952 * @private
953 */
954 goog.html.sanitizer.HtmlSanitizer.sanitizeName_ = function(
955 namePolicy, attrName, policyHints) {
956 var trimmed = goog.string.trim(attrName);
957 /* TODO(user): fail on names which contain illegal characters.
958 * NOTE(jasvir):
959 * There are two cases to be concerned about - escaped quotes in attribute
960 * values which is the responsibility of the serializer and illegal
961 * characters. The latter does violate the spec but I do not believe it has
962 * a security consequence.
963 */
964 return namePolicy(trimmed, policyHints);
965 };
966
967
968 /**
969 * Ensures that the class prefix is present on all space-separated tokens
970 * (i.e. all class names).
971 * @param {goog.html.sanitizer.HtmlSanitizerPolicy} tokenPolicy
972 * @param {string} attrValue
973 * @param {goog.html.sanitizer.HtmlSanitizerPolicyHints} policyHints
974 * @return {?string} sanitizedAttrValue
975 * @private
976 */
977 goog.html.sanitizer.HtmlSanitizer.sanitizeClasses_ = function(
978 tokenPolicy, attrValue, policyHints) {
979 // TODO(user): use a browser-supplied class list instead of a string.
980 var classes = attrValue.split(/(?:\s+)/);
981 var sanitizedClasses = [];
982 for (var i = 0; i < classes.length; i++) {
983 // TODO(user): skip classes which contain illegal characters.
984 var sanitizedClass = tokenPolicy(classes[i], policyHints);
985 if (sanitizedClass) {
986 sanitizedClasses.push(sanitizedClass);
987 }
988 }
989 return sanitizedClasses.length == 0 ? null : sanitizedClasses.join(' ');
990 };
991
992
993 /**
994 * Ensures that the id prefix is present.
995 * @param {goog.html.sanitizer.HtmlSanitizerPolicy} tokenPolicy
996 * @param {string} attrValue
997 * @param {goog.html.sanitizer.HtmlSanitizerPolicyHints} policyHints
998 * @return {?string} sanitizedAttrValue
999 * @private
1000 */
1001 goog.html.sanitizer.HtmlSanitizer.sanitizeId_ = function(
1002 tokenPolicy, attrValue, policyHints) {
1003 var trimmed = goog.string.trim(attrValue);
1004 // TODO(user): fail on IDs which contain illegal characters.
1005 return tokenPolicy(trimmed, policyHints);
1006 };
1007
1008
1009 /**
1010 * Parses a string of unsanitized HTML and provides an iterator over the
1011 * resulting DOM tree nodes. This DOM parsing must be wholly inert (that is,
1012 * it does not cause execution of any active content or cause the browser to
1013 * issue any requests). The returned iterator is guaranteed to iterate over a
1014 * parent element before iterating over any of its children.
1015 * @param {string} unsanitizedHtml
1016 * @return {!TreeWalker} Dom tree iterator
1017 * @private
1018 */
1019 goog.html.sanitizer.HtmlSanitizer.getDomTreeWalker_ = function(
1020 unsanitizedHtml) {
1021 var iteratorParent;
1022 // Use a <template> element if possible.
1023 var templateElement = document.createElement('template');
1024 if ('content' in templateElement) {
1025 templateElement.innerHTML = unsanitizedHtml;
1026 iteratorParent = templateElement.content;
1027 } else {
1028 // In browsers where <template> is not implemented, use an HTMLDocument.
1029 var doc = document.implementation.createHTMLDocument('x');
1030 iteratorParent = doc.body;
1031 doc.body.innerHTML = unsanitizedHtml;
1032 }
1033 return document.createTreeWalker(
1034 iteratorParent, NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_TEXT,
1035 null /* filter */, false /* entityReferenceExpansion */);
1036 };
1037
1038
1039 /**
1040 * Parses the DOM tree of a given HTML string, then walks the tree. For each
1041 * element, it creates a new sanitized version, applies sanitized attributes,
1042 * and returns a SafeHtml object representing the sanitized tree.
1043 * @param {string} unsanitizedHtml
1044 * @return {!goog.html.SafeHtml} Sanitized HTML
1045 */
1046 goog.html.sanitizer.HtmlSanitizer.prototype.sanitize = function(
1047 unsanitizedHtml) {
1048 var styleContainer = this.getStyleContainerId_();
1049 var sanitizedParent =
1050 this.sanitizeToDomNode_(unsanitizedHtml, styleContainer);
1051 var sanitizedString = new XMLSerializer().serializeToString(sanitizedParent);
1052
1053 // Remove the outer span added in sanitizeToDomNode. We could create an
1054 // element from it and then pull out the innerHTML, but this is more
1055 // performant.
1056 sanitizedString = sanitizedString.slice(
1057 sanitizedString.indexOf('>') + 1, sanitizedString.lastIndexOf('</'));
1058 if (sanitizedString == '') {
1059 return goog.html.SafeHtml.EMPTY;
1060 }
1061
1062 var safeHtml = goog.html.uncheckedconversions
1063 .safeHtmlFromStringKnownToSatisfyTypeContract(
1064 goog.string.Const.from('Output of HTML sanitizer'),
1065 sanitizedString);
1066 // If appropriate, rewrap the output with a style container.
1067 if (this.styleContainer_ == goog.html.sanitizer.RANDOM_CONTAINER_) {
1068 safeHtml = goog.html.SafeHtml.create(
1069 goog.dom.TagName.SPAN, {id: styleContainer}, safeHtml);
1070 }
1071
1072 return safeHtml;
1073 };
1074
1075
1076 /**
1077 * Parses the DOM tree of a given HTML string, then walks the tree. For each
1078 * element, it creates a new sanitized version, applies sanitized attributes,
1079 * and returns a span element containing the sanitized content.
1080 * @param {string} unsanitizedHtml
1081 * @return {!HTMLSpanElement} Sanitized HTML
1082 */
1083 goog.html.sanitizer.HtmlSanitizer.prototype.sanitizeToDomNode = function(
1084 unsanitizedHtml) {
1085 return this.sanitizeToDomNode_(unsanitizedHtml);
1086 };
1087
1088
1089 /**
1090 * Private variant of {@link sanitizeToDomNode} that allows passing a style
1091 * container. If used with an unsafe style container, it can cause an XSS and
1092 * thus we keep it private. Use the {@link withStyleContainer} builder function
1093 * to set a name for the style container.
1094 * @param {string} unsanitizedHtml
1095 * @param {?string=} opt_styleContainer
1096 * @return {!HTMLSpanElement} Sanitized HTML
1097 * @private
1098 */
1099 goog.html.sanitizer.HtmlSanitizer.prototype.sanitizeToDomNode_ = function(
1100 unsanitizedHtml, opt_styleContainer) {
1101 var sanitizedParent =
1102 /** @type {!HTMLSpanElement} */ (document.createElement('span'));
1103
1104 if (!goog.html.sanitizer.HTML_SANITIZER_SUPPORTED_) {
1105 return sanitizedParent;
1106 }
1107
1108 // Inline style rules on the unsanitized input, so that we don't have to
1109 // worry about customTokenPolicy and customNamePolicy interferring with
1110 // selectors.
1111 if (this.inlineStyleRules_) {
1112 // TODO(pelizzi): we are going to parse the document into a DOM tree twice,
1113 // once with DOMParser here, and once with TEMPLATE in the main sanitization
1114 // loop. It would be best if we used one technique consistently and parse it
1115 // once, but the decision to use TEMPLATE in the main body predates the work
1116 // on supporting STYLE tags, and we later found on that TEMPLATE inert
1117 // documents do not have computed stylesheet information on STYLE tags.
1118 var inertUnsanitizedDom =
1119 goog.html.sanitizer.CssSanitizer.safeParseHtmlAndGetInertElement(
1120 '<span>' + unsanitizedHtml + '</span>');
1121 goog.asserts.assert(
1122 inertUnsanitizedDom,
1123 'Older browsers that don\'t support inert ' +
1124 'parsing should not get to this branch');
1125 goog.html.sanitizer.CssSanitizer.inlineStyleRules(inertUnsanitizedDom);
1126 unsanitizedHtml = inertUnsanitizedDom.innerHTML;
1127 }
1128
1129
1130 var styleContainer = opt_styleContainer != undefined ?
1131 opt_styleContainer :
1132 this.getStyleContainerId_();
1133 if (styleContainer) {
1134 sanitizedParent.id = styleContainer;
1135 }
1136
1137 // Get the treeWalker initialized.
1138 try {
1139 var treeWalker =
1140 goog.html.sanitizer.HtmlSanitizer.getDomTreeWalker_(unsanitizedHtml);
1141 } catch (e) {
1142 return sanitizedParent;
1143 }
1144
1145 // Used in order to find the correct parent node in the sanitizedParent.
1146 var elementMap = goog.html.sanitizer.ElementWeakMap.newWeakMap();
1147 // Used for iteration.
1148 var dirtyNode;
1149 while (dirtyNode = treeWalker.nextNode()) {
1150 // Get a clean (sanitized) version of the dirty node.
1151 var cleanNode = this.sanitizeNode_(dirtyNode, styleContainer);
1152 if (goog.html.sanitizer.noclobber.isNodeElement(cleanNode)) {
1153 // If sanitizeNode_ returned an element, then the original node was also
1154 // an element.
1155 dirtyNode = goog.html.sanitizer.noclobber.assertNodeIsElement(dirtyNode);
1156 cleanNode = goog.html.sanitizer.noclobber.assertNodeIsElement(cleanNode);
1157 this.sanitizeAttrs_(dirtyNode, cleanNode);
1158 elementMap.set(dirtyNode, cleanNode);
1159
1160 // Template tag contents require special handling as they are not
1161 // traversed by the treewalker.
1162 this.maybeProcessTemplateContents_(dirtyNode, cleanNode);
1163 }
1164
1165 // TODO(pelizzi): [IMPROVEMENT] type-checking against clobbering (e.g.
1166 // ClobberedNode wrapper). Closure can unwrap these at compile time, see
1167 // ClosureOptimizePrimitives.java, jakubvrana has created one for
1168 // goog.dom.Tag. Alternatively, create two actual wrappers that expose
1169 // clobber-safe functions, getters and setters for Node and Element.
1170
1171 // TODO(pelizzi): [IMPROVEMENT] add an API to sanitize *from* DOM nodes so
1172 // that we don't have to use innerHTML on template recursion but instead we
1173 // can use importNode. The API could also be public as it is still a way to
1174 // make a document fragment conform to a policy, somewhat useful.
1175
1176 // Finds the parent to which cleanNode should be appended.
1177 var dirtyParent = goog.html.sanitizer.noclobber.getParentNode(dirtyNode);
1178 var isSanitizedParent = false;
1179 if (dirtyParent) {
1180 var dirtyParentNodeType =
1181 goog.html.sanitizer.noclobber.getNodeType(dirtyParent);
1182 var dirtyParentNodeName =
1183 goog.html.sanitizer.noclobber.getNodeName(dirtyParent).toLowerCase();
1184 var dirtyGrandParent =
1185 goog.html.sanitizer.noclobber.getParentNode(dirtyParent);
1186 // The following checks if target is an immediate child of the inert
1187 // parent template element
1188 if (dirtyParentNodeType == goog.dom.NodeType.DOCUMENT_FRAGMENT &&
1189 !dirtyGrandParent) {
1190 isSanitizedParent = true;
1191 } else if (dirtyParentNodeName == 'body' && dirtyGrandParent) {
1192 // The following checks if target is an immediate child of the inert
1193 // parent HtmlDocument.
1194 var dirtyGreatGrandParent =
1195 goog.html.sanitizer.noclobber.getParentNode(dirtyGrandParent);
1196 if (dirtyGreatGrandParent &&
1197 !goog.html.sanitizer.noclobber.getParentNode(
1198 dirtyGreatGrandParent)) {
1199 isSanitizedParent = true;
1200 }
1201 }
1202 }
1203 var target;
1204 if (isSanitizedParent || !dirtyParent) {
1205 target = sanitizedParent;
1206 } else if (goog.html.sanitizer.noclobber.isNodeElement(dirtyParent)) {
1207 target = elementMap.get(/** @type {!Element} */ (dirtyParent));
1208 }
1209 if (target.content) {
1210 target = target.content;
1211 }
1212 // Do not attach blacklisted tags that have been sanitized into templates.
1213 if (!goog.html.sanitizer.noclobber.isNodeElement(cleanNode) ||
1214 !cleanNode.hasAttribute(
1215 goog.html.sanitizer.HTML_SANITIZER_BLACKLISTED_TAG_)) {
1216 target.appendChild(cleanNode);
1217 }
1218 }
1219 if (elementMap.clear) {
1220 elementMap.clear();
1221 }
1222 return sanitizedParent;
1223 };
1224
1225
1226 /**
1227 * Gets the style container ID for the sanitized output, or creates a new random
1228 * one. If no style container is necessary or style containment is disabled,
1229 * returns null.
1230 * @return {?string}
1231 * @private
1232 */
1233 goog.html.sanitizer.HtmlSanitizer.prototype.getStyleContainerId_ = function() {
1234 var randomStyleContainmentEnabled =
1235 this.styleContainer_ == goog.html.sanitizer.RANDOM_CONTAINER_;
1236 var randomStyleContainmentNecessary =
1237 !('STYLE' in this.tagBlacklist_) && 'STYLE' in this.tagWhitelist_;
1238 // If the builder was configured to create a random unique ID, create one, but
1239 // do so only if STYLE is allowed to begin with.
1240 return randomStyleContainmentEnabled && randomStyleContainmentNecessary ?
1241 'sanitizer-' + goog.string.getRandomString() :
1242 this.styleContainer_;
1243 };
1244
1245
1246 /**
1247 * Returns a sanitized version of a node, with no children or user-provided
1248 * attributes.
1249 * @param {!Node} dirtyNode
1250 * @param {?string} styleContainer
1251 * @return {!Node}
1252 * @private
1253 */
1254 goog.html.sanitizer.HtmlSanitizer.prototype.sanitizeNode_ = function(
1255 dirtyNode, styleContainer) {
1256 // Text nodes don't need to be sanitized, unless they are children of STYLE
1257 // and STYLE tags are allowed.
1258 if (goog.html.sanitizer.noclobber.getNodeType(dirtyNode) ==
1259 goog.dom.NodeType.TEXT) {
1260 var textContent = dirtyNode.data;
1261 // If STYLE is allowed, apply a policy to its text content. Ideally
1262 // sanitizing text content of tags shouldn't be hardcoded for STYLE, but we
1263 // have no plans to support sanitizing the text content of other nodes for
1264 // now.
1265 var dirtyParent = goog.html.sanitizer.noclobber.getParentNode(dirtyNode);
1266 if (dirtyParent &&
1267 goog.html.sanitizer.noclobber.getNodeName(dirtyParent).toLowerCase() ==
1268 'style' &&
1269 !('STYLE' in this.tagBlacklist_) && 'STYLE' in this.tagWhitelist_) {
1270 // Note that we don't have access to the parsed CSS declarations inside a
1271 // TEMPLATE tag, so the CSS sanitizer accepts a string and parses it
1272 // on its own using DOMParser.
1273 textContent = goog.html.SafeStyleSheet.unwrap(
1274 goog.html.sanitizer.CssSanitizer.sanitizeStyleSheetString(
1275 textContent, styleContainer, goog.bind(function(uri, propName) {
1276 return this.networkRequestUrlPolicy_(
1277 uri, {cssProperty: propName});
1278 }, this)));
1279 }
1280 return document.createTextNode(textContent);
1281 }
1282
1283 // Non text nodes get an empty node based on black/white lists.
1284 var elemName =
1285 goog.html.sanitizer.noclobber.getNodeName(dirtyNode).toUpperCase();
1286 var sanitized = false;
1287 var blacklisted = false;
1288 var cleanElemName;
1289 if (elemName in this.tagBlacklist_) {
1290 // If it's in the inert blacklist, replace with template (and then add a
1291 // special data attribute to distinguish it from real template tags).
1292 // Note that this node will not be added to the final output, i.e. the
1293 // template tag is only an internal representation, and eventually will be
1294 // deleted.
1295 cleanElemName = 'template';
1296 blacklisted = true;
1297 } else if (this.tagWhitelist_[elemName]) {
1298 // If it's in the whitelist, keep as is.
1299 cleanElemName = elemName;
1300 } else {
1301 // If it's not in any list, replace with span. If the relevant builder
1302 // option is enabled, they will bear the original tag name in a data
1303 // attribute.
1304 cleanElemName = 'span';
1305 sanitized = true;
1306 }
1307 var cleanElem = document.createElement(cleanElemName);
1308 if (this.shouldAddOriginalTagNames_ && sanitized) {
1309 goog.html.sanitizer.noclobber.setElementAttribute(
1310 cleanElem, goog.html.sanitizer.HTML_SANITIZER_SANITIZED_ATTR_NAME_,
1311 elemName.toLowerCase());
1312 }
1313 if (blacklisted) {
1314 goog.html.sanitizer.noclobber.setElementAttribute(
1315 cleanElem, goog.html.sanitizer.HTML_SANITIZER_BLACKLISTED_TAG_, '');
1316 }
1317 return cleanElem;
1318 };
1319
1320
1321 /**
1322 * Applies sanitized versions of attributes from a dirtyElement to a
1323 * corresponding cleanElement.
1324 * @param {!Element} dirtyElement
1325 * @param {!Element} cleanElement
1326 * @private
1327 */
1328 goog.html.sanitizer.HtmlSanitizer.prototype.sanitizeAttrs_ = function(
1329 dirtyElement, cleanElement) {
1330 var attributes =
1331 goog.html.sanitizer.noclobber.getElementAttributes(dirtyElement);
1332 if (attributes == null) {
1333 return;
1334 }
1335 for (var i = 0, attribute; attribute = attributes[i]; i++) {
1336 if (attribute.specified) {
1337 var cleanValue = this.sanitizeAttribute_(dirtyElement, attribute);
1338 if (!goog.isNull(cleanValue)) {
1339 goog.html.sanitizer.noclobber.setElementAttribute(
1340 cleanElement, attribute.name, cleanValue);
1341 }
1342 }
1343 }
1344 };
1345
1346
1347 /**
1348 * Sanitizes an attribute value by looking up an attribute handler for the given
1349 * node and attribute names.
1350 * @param {!Element} dirtyElement
1351 * @param {!Attr} attribute
1352 * @return {?string} sanitizedAttrValue
1353 * @private
1354 */
1355 goog.html.sanitizer.HtmlSanitizer.prototype.sanitizeAttribute_ = function(
1356 dirtyElement, attribute) {
1357 var attributeName = attribute.name;
1358 if (goog.string.startsWith(
1359 attributeName,
1360 goog.html.sanitizer.HTML_SANITIZER_BOOKKEEPING_PREFIX_)) {
1361 return null;
1362 }
1363
1364 var elementName = goog.html.sanitizer.noclobber.getNodeName(dirtyElement);
1365 var unsanitizedAttrValue = attribute.value;
1366
1367 // Create policy hints object
1368 var policyHints = {
1369 tagName: goog.string.trim(elementName).toLowerCase(),
1370 attributeName: goog.string.trim(attributeName).toLowerCase()
1371 };
1372 var policyContext = goog.html.sanitizer.HtmlSanitizer.getContext_(
1373 policyHints.attributeName, dirtyElement);
1374
1375 // Prefer attribute handler for this specific tag.
1376 var tagHandlerIndex = goog.html.sanitizer.HtmlSanitizer.attrIdentifier_(
1377 elementName, attributeName);
1378 if (tagHandlerIndex in this.attributeHandlers_) {
1379 var handler = this.attributeHandlers_[tagHandlerIndex];
1380 return handler(unsanitizedAttrValue, policyHints, policyContext);
1381 }
1382 // Fall back on attribute handler for wildcard tag.
1383 var genericHandlerIndex =
1384 goog.html.sanitizer.HtmlSanitizer.attrIdentifier_(null, attributeName);
1385 if (genericHandlerIndex in this.attributeHandlers_) {
1386 var handler = this.attributeHandlers_[genericHandlerIndex];
1387 return handler(unsanitizedAttrValue, policyHints, policyContext);
1388 }
1389 return null;
1390 };
1391
1392
1393 /**
1394 * Processes the contents of a template tag. These are not traversed through the
1395 * treewalker because they belong to a separate document, and thus require
1396 * special handling.
1397 * <p>
1398 * If the relevant builder option is enabled and the template tag is allowed,
1399 * this method copies the contents over to the output DOM tree without
1400 * sanitization, otherwise the template contents are sanitized recursively.
1401 * @param {!Element} dirtyElement
1402 * @param {!Element} cleanElement
1403 * @private
1404 */
1405 goog.html.sanitizer.HtmlSanitizer.prototype.maybeProcessTemplateContents_ =
1406 function(dirtyElement, cleanElement) {
1407 var dirtyElementName =
1408 goog.html.sanitizer.noclobber.getNodeName(dirtyElement);
1409 if (!goog.html.sanitizer.HTML_SANITIZER_TEMPLATE_SUPPORTED ||
1410 dirtyElementName.toLowerCase() != 'template' ||
1411 cleanElement.hasAttribute(
1412 goog.html.sanitizer.HTML_SANITIZER_BLACKLISTED_TAG_)) {
1413 return;
1414 }
1415
1416 // If the template element was sanitized into a span tag, do not insert
1417 // unsanitized tags!
1418 if (this.shouldSanitizeTemplateContents_ ||
1419 cleanElement.nodeName.toLowerCase() !== 'template') {
1420 var dirtyElementHTML =
1421 goog.html.sanitizer.noclobber.getElementInnerHTML(dirtyElement);
1422 var templateSpan = this.sanitizeToDomNode(dirtyElementHTML);
1423 // appendChild with a forEach instead of an innertHTML as the latter is
1424 // slower.
1425 goog.array.forEach(templateSpan.childNodes, function(node) {
1426 cleanElement.appendChild(node);
1427 });
1428 } else {
1429 var templateDoc =
1430 /** @type {!HTMLTemplateElement} */ (cleanElement)
1431 .content.ownerDocument;
1432 var dirtyCopy =
1433 goog.asserts.assert(templateDoc.importNode(dirtyElement, true));
1434 var dirtyCopyChildren =
1435 goog.html.sanitizer.noclobber.getChildNodes(dirtyCopy);
1436 // appendChild with a forEach instead of an innerHTML as the latter is
1437 // slower and vulnerable to mXSS.
1438 goog.array.forEach(dirtyCopyChildren, function(node) {
1439 cleanElement.appendChild(node);
1440 });
1441 }
1442 };
1443
1444
1445 /**
1446 * Retrieves a HtmlSanitizerPolicyContext from a dirty node given an attribute
1447 * name.
1448 * @param {string} attributeName
1449 * @param {!Element} dirtyElement
1450 * @return {!goog.html.sanitizer.HtmlSanitizerPolicyContext}
1451 * @private
1452 */
1453 goog.html.sanitizer.HtmlSanitizer.getContext_ = function(
1454 attributeName, dirtyElement) {
1455 var policyContext = {cssStyle: undefined};
1456 if (attributeName == 'style') {
1457 policyContext.cssStyle =
1458 goog.html.sanitizer.noclobber.getElementStyle(dirtyElement);
1459 }
1460 return policyContext;
1461 };
1462
1463
1464 /**
1465 * Sanitizes a HTML string using a sanitizer with default options.
1466 * @param {string} unsanitizedHtml
1467 * @return {!goog.html.SafeHtml} sanitizedHtml
1468 */
1469 goog.html.sanitizer.HtmlSanitizer.sanitize = function(unsanitizedHtml) {
1470 var sanitizer = new goog.html.sanitizer.HtmlSanitizer.Builder().build();
1471 return sanitizer.sanitize(unsanitizedHtml);
1472 };