Debian Codegraph @

closure-library/closure/goog/html/sanitizer/csssanitizer.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 * @fileoverview
17 * JavaScript support for client-side CSS sanitization.
18 *
19 * @author [email protected] (Danesh Irani)
20 * @author [email protected] (Mike Samuel)
21 */
22
23 goog.provide('goog.html.sanitizer.CssSanitizer');
24
25 goog.require('goog.array');
26 goog.require('goog.dom');
27 goog.require('goog.dom.TagName');
28 goog.require('goog.html.CssSpecificity');
29 goog.require('goog.html.SafeStyle');
30 goog.require('goog.html.SafeStyleSheet');
31 goog.require('goog.html.SafeUrl');
32 goog.require('goog.html.sanitizer.noclobber');
33 goog.require('goog.html.uncheckedconversions');
34 goog.require('goog.object');
35 goog.require('goog.string');
36 goog.require('goog.userAgent');
37 goog.require('goog.userAgent.product');
38
39
40 /**
41 * The set of characters that need to be normalized inside url("...").
42 * We normalize newlines because they are not allowed inside quoted strings,
43 * normalize quote characters, angle-brackets, and asterisks because they
44 * could be used to break out of the URL or introduce targets for CSS
45 * error recovery. We normalize parentheses since they delimit unquoted
46 * URLs and calls and could be a target for error recovery.
47 * @const @private {!RegExp}
48 */
49 goog.html.sanitizer.CssSanitizer.NORM_URL_REGEXP_ = /[\n\f\r\"\'()*<>]/g;
50
51
52 /**
53 * The replacements for NORM_URL_REGEXP.
54 * @private @const {!Object<string, string>}
55 */
56 goog.html.sanitizer.CssSanitizer.NORM_URL_REPLACEMENTS_ = {
57 '\n': '%0a',
58 '\f': '%0c',
59 '\r': '%0d',
60 '"': '%22',
61 '\'': '%27',
62 '(': '%28',
63 ')': '%29',
64 '*': '%2a',
65 '<': '%3c',
66 '>': '%3e'
67 };
68
69
70 /**
71 * A regular expression to match each selector in a CSS rule. Selectors are
72 * separated by commas, but can have strings within them (e.g. foo[name="bar"])
73 * that can contain commas and escaped quotes.
74 * @private {?RegExp}
75 */
76 goog.html.sanitizer.CssSanitizer.SELECTOR_REGEX_ =
77 // Don't even evaluate it on older browsers (IE8 and IE9), it throws a
78 // syntax error and we don't use it anyway.
79 !(goog.userAgent.IE && document.documentMode < 10) ?
80 new RegExp(
81 '\\s*' + // Discard initial space
82 '([^\\s\'",]+' + // Beginning of the match. Anything but a comma,
83 // spaces or a string delimiter. This is the only
84 // non-optional component of the regex.
85 '[^\'",]*' + // Spaces are fine afterwards (e.g. "a > b").
86 ('(' + // A series of optional strings with matching delimiters
87 // that can contain anything, and optional non-quoted text
88 // without commas.
89 '(\'([^\'\\r\\n\\f\\\\]|\\\\[^])*\')|' + // Optional single-quoted
90 // string.
91 '("([^"\\r\\n\\f\\\\]|\\\\[^])*")|' + // Optional double-quoted
92 // string.
93 '[^\'",]' + // Optional non-string content.
94 ')*') + // String and non-string
95 // content can come in any
96 // order.
97 ')', // End of the match.
98 'g') :
99 null;
100
101
102 /**
103 * Normalizes a character for use in a url() directive.
104 * @param {string} ch Character to be normalized.
105 * @return {?string} Normalized character.
106 * @private
107 */
108 goog.html.sanitizer.CssSanitizer.normalizeUrlChar_ = function(ch) {
109 return goog.html.sanitizer.CssSanitizer.NORM_URL_REPLACEMENTS_[ch] || null;
110 };
111
112
113 /**
114 * Constructs a safe URI from a given URI and prop using a given uriRewriter
115 * function.
116 * @param {string} uri URI to be sanitized.
117 * @param {string} propName Property name which contained the URI.
118 * @param {?function(string, string):?goog.html.SafeUrl} uriRewriter A URI
119 * rewriter that returns a goog.html.SafeUrl.
120 * @return {?string} Safe URI for use in CSS.
121 * @private
122 */
123 goog.html.sanitizer.CssSanitizer.getSafeUri_ = function(
124 uri, propName, uriRewriter) {
125 if (!uriRewriter) {
126 return null;
127 }
128 var safeUri = uriRewriter(uri, propName);
129 if (safeUri &&
130 goog.html.SafeUrl.unwrap(safeUri) != goog.html.SafeUrl.INNOCUOUS_STRING) {
131 return 'url("' +
132 goog.html.SafeUrl.unwrap(safeUri).replace(
133 goog.html.sanitizer.CssSanitizer.NORM_URL_REGEXP_,
134 goog.html.sanitizer.CssSanitizer.normalizeUrlChar_) +
135 '")';
136 }
137 return null;
138 };
139
140
141 /**
142 * Used to detect the beginning of the argument list of a CSS property value
143 * containing a CSS function call.
144 * @private @const {string}
145 */
146 goog.html.sanitizer.CssSanitizer.FUNCTION_ARGUMENTS_BEGIN_ = '(';
147
148
149 /**
150 * Used to detect the end of the argument list of a CSS property value
151 * containing a CSS function call.
152 * @private @const {string}
153 */
154 goog.html.sanitizer.CssSanitizer.FUNCTION_ARGUMENTS_END_ = ')';
155
156
157 /**
158 * Allowed CSS functions
159 * @const @private {!Array<string>}
160 */
161 goog.html.sanitizer.CssSanitizer.ALLOWED_FUNCTIONS_ = [
162 'rgb',
163 'rgba',
164 'alpha',
165 'rect',
166 'image',
167 'linear-gradient',
168 'radial-gradient',
169 'repeating-linear-gradient',
170 'repeating-radial-gradient',
171 'cubic-bezier',
172 'matrix',
173 'perspective',
174 'rotate',
175 'rotate3d',
176 'rotatex',
177 'rotatey',
178 'steps',
179 'rotatez',
180 'scale',
181 'scale3d',
182 'scalex',
183 'scaley',
184 'scalez',
185 'skew',
186 'skewx',
187 'skewy',
188 'translate',
189 'translate3d',
190 'translatex',
191 'translatey',
192 'translatez'
193 ];
194
195
196 /**
197 * Removes a vendor prefix from a property name.
198 * @param {string} propName A property name.
199 * @return {string} A property name without vendor prefixes.
200 * @private
201 */
202 goog.html.sanitizer.CssSanitizer.withoutVendorPrefix_ = function(propName) {
203 // http://stackoverflow.com/a/5411098/20394 has a fairly extensive list
204 // of vendor prefices. Blink has not declared a vendor prefix distinct from
205 // -webkit- and http://css-tricks.com/tldr-on-vendor-prefix-drama/ discusses
206 // how Mozilla recognizes some -webkit- prefixes.
207 // http://wiki.csswg.org/spec/vendor-prefixes talks more about
208 // cross-implementation, and lists other prefixes.
209 return propName.replace(
210 /^-(?:apple|css|epub|khtml|moz|mso?|o|rim|wap|webkit|xv)-(?=[a-z])/i, '');
211 };
212
213
214 /**
215 * Sanitizes the value for a given a browser-parsed CSS value.
216 * @param {string} propName A property name.
217 * @param {string} propValue Value of the property as parsed by the browser.
218 * @param {function(string, string):?goog.html.SafeUrl=} opt_uriRewriter A URI
219 * rewriter that returns an unwrapped goog.html.SafeUrl.
220 * @return {?string} Sanitized property value or null.
221 * @private
222 */
223 goog.html.sanitizer.CssSanitizer.sanitizeProperty_ = function(
224 propName, propValue, opt_uriRewriter) {
225 var outputPropValue = goog.string.trim(propValue);
226 if (outputPropValue == '') {
227 return null;
228 }
229
230 if (goog.string.caseInsensitiveStartsWith(outputPropValue, 'url(')) {
231 // Urls are rewritten according to the policy implemented in
232 // opt_uriRewriter.
233 // TODO(pelizzi): use HtmlSanitizerUrlPolicy for opt_uriRewriter.
234 if (!opt_uriRewriter) {
235 return null;
236 }
237 // TODO(danesh): Check if we need to resolve this URI.
238 var uri = goog.string.stripQuotes(
239 outputPropValue.substring(4, outputPropValue.length - 1), '"\'');
240
241 return goog.html.sanitizer.CssSanitizer.getSafeUri_(
242 uri, propName, opt_uriRewriter);
243 } else if (outputPropValue.indexOf('(') > 0) {
244 // Functions are filtered through a whitelist. Nesting whitelisted functions
245 // is not supported.
246 if (goog.string.countOf(
247 outputPropValue,
248 goog.html.sanitizer.CssSanitizer.FUNCTION_ARGUMENTS_BEGIN_) > 1 ||
249 !(goog.array.contains(
250 goog.html.sanitizer.CssSanitizer.ALLOWED_FUNCTIONS_,
251 outputPropValue
252 .substring(
253 0,
254 outputPropValue.indexOf(goog.html.sanitizer.CssSanitizer
255 .FUNCTION_ARGUMENTS_BEGIN_))
256 .toLowerCase()) &&
257 goog.string.endsWith(
258 outputPropValue,
259 goog.html.sanitizer.CssSanitizer.FUNCTION_ARGUMENTS_END_))) {
260 // TODO(b/34222379): Handle functions that may need recursing or that may
261 // appear in the middle of a string. For now, just allow functions which
262 // aren't nested.
263 return null;
264 }
265 return outputPropValue;
266 } else {
267 // Everything else is allowed.
268 return outputPropValue;
269 }
270 };
271
272
273 /**
274 * Sanitizes a {@link CSSStyleSheet}.
275 * @param {!CSSStyleSheet} cssStyleSheet
276 * @param {?string} containerId An ID to restrict the scope of the rules being
277 * sanitized. If null, no restriction is applied.
278 * @param {function(string, string):?goog.html.SafeUrl|undefined} uriRewriter A
279 * URI rewriter that returns a goog.html.SafeUrl.
280 * @return {!goog.html.SafeStyleSheet}
281 * @private
282 */
283 goog.html.sanitizer.CssSanitizer.sanitizeStyleSheet_ = function(
284 cssStyleSheet, containerId, uriRewriter) {
285 var sanitizedRules = [];
286 var cssRules = goog.html.sanitizer.CssSanitizer.getOnlyStyleRules_(
287 goog.array.toArray(cssStyleSheet.cssRules));
288 goog.array.forEach(cssRules, function(cssRule) {
289 if (containerId && !/[a-zA-Z][\w-:\.]*/.test(containerId)) {
290 // Sanity check on the element ID that will confine the new CSS rules.
291 throw new Error('Invalid container id');
292 }
293 if (containerId && goog.userAgent.product.IE &&
294 document.documentMode == 10 && /\\['"]/.test(cssRule.selectorText)) {
295 // If a container ID was specified, drop selectors with escaped quotes in
296 // strings on IE 10 due to a regex bug.
297 return;
298 }
299 // If a container ID was specified, restrict all selectors in this rule to
300 // be descendants of the node with such an ID. Use a regex to exclude commas
301 // within selector strings.
302 var scopedSelector = containerId ?
303 cssRule.selectorText.replace(
304 goog.html.sanitizer.CssSanitizer.SELECTOR_REGEX_,
305 '#' + containerId + ' $1') :
306 cssRule.selectorText;
307 sanitizedRules.push(goog.html.SafeStyleSheet.createRule(
308 scopedSelector,
309 goog.html.sanitizer.CssSanitizer.sanitizeInlineStyle(
310 cssRule.style, uriRewriter)));
311 });
312 return goog.html.SafeStyleSheet.concat(sanitizedRules);
313 };
314
315
316 /**
317 * Used to filter out at-rules like @media, @font, etc. Currently, none of these
318 * are supported.
319 * @param {!Array<!CSSRule>} cssRules
320 * @return {!Array<!CSSStyleRule>}
321 * @private
322 */
323 // TODO(pelizzi): some of these at-rules are safe, consider adding partial
324 // support for them.
325 goog.html.sanitizer.CssSanitizer.getOnlyStyleRules_ = function(cssRules) {
326 return /** @type {!Array<!CSSStyleRule>} */ (
327 goog.array.filter(cssRules, function(cssRule) {
328 return cssRule instanceof CSSStyleRule ||
329 cssRule.type == CSSRule.STYLE_RULE;
330 }));
331 };
332
333
334 /**
335 * Sanitizes the contents of a STYLE tag.
336 * @param {string} textContent The textual content of the STYLE tag.
337 * @param {?string=} opt_containerId The ID of a node that will contain the
338 * STYLE tag that includes the sanitized content, to restrict the effects of
339 * the rules being sanitized to descendants of this node.
340 * @param {function(string, string):?goog.html.SafeUrl=} opt_uriRewriter A URI
341 * rewriter that returns a goog.html.SafeUrl.
342 * @return {!goog.html.SafeStyleSheet}
343 * @supported IE 10+, Chrome 26+, Firefox 22+, Safari 7.1+, Opera 15+. On IE10,
344 * support for escaped quotes inside quoted strings (e.g. `a[name="it\'s"]`)
345 * is unreliable, and some (but not all!) rules containing these are
346 * silently dropped.
347 */
348 goog.html.sanitizer.CssSanitizer.sanitizeStyleSheetString = function(
349 textContent, opt_containerId, opt_uriRewriter) {
350 var styleTag =
351 goog.html.sanitizer.CssSanitizer.safeParseHtmlAndGetInertElement(
352 '<style>' + textContent + '</style>');
353 if (styleTag == null) {
354 return goog.html.SafeStyleSheet.EMPTY;
355 }
356 var containerId = opt_containerId != undefined ? opt_containerId : null;
357 return goog.html.sanitizer.CssSanitizer.sanitizeStyleSheet_(
358 styleTag.sheet, containerId, opt_uriRewriter);
359 };
360
361
362 /**
363 * Returns an inert DOM tree produced by parsing the provided html using
364 * DOMParser. "Inert" here means that merely parsing the string won't execute
365 * scripts or load images. If you attach this tree to a non-inert document, it
366 * will execute these side effects! In this package we prefer using the TEMPLATE
367 * tag over DOMParser to produce inert trees, but at least on Chrome the inert
368 * STYLE tag does not have a CSSStyleSheet object attached to it.
369 * @param {string} html
370 * @return {?Element}
371 * @package
372 */
373 goog.html.sanitizer.CssSanitizer.safeParseHtmlAndGetInertElement = function(
374 html) {
375 if ((goog.userAgent.IE && !goog.userAgent.isVersionOrHigher(10)) ||
376 typeof goog.global.DOMParser != 'function') {
377 return null;
378 }
379 var parser = new DOMParser();
380 return parser
381 .parseFromString(
382 '<html><head></head><body>' + html + '</body></html>', 'text/html')
383 .body.children[0];
384 };
385
386
387 /**
388 * Sanitizes an inline style attribute. Short-hand attributes are expanded to
389 * their individual elements. Note: The sanitizer does not output vendor
390 * prefixed styles.
391 * @param {?CSSStyleDeclaration} cssStyle A CSS style object.
392 * @param {function(string, string):?goog.html.SafeUrl=} opt_uriRewriter A URI
393 * rewriter that returns a goog.html.SafeUrl.
394 * @return {!goog.html.SafeStyle} A sanitized inline cssText.
395 */
396 goog.html.sanitizer.CssSanitizer.sanitizeInlineStyle = function(
397 cssStyle, opt_uriRewriter) {
398 if (!cssStyle) {
399 return goog.html.SafeStyle.EMPTY;
400 }
401
402 var cleanCssStyle = document.createElement('div').style;
403 var cssPropNames =
404 goog.html.sanitizer.CssSanitizer.getCssPropNames_(cssStyle);
405
406 for (var i = 0; i < cssPropNames.length; i++) {
407 var propName =
408 goog.html.sanitizer.CssSanitizer.withoutVendorPrefix_(cssPropNames[i]);
409 if (!goog.html.sanitizer.CssSanitizer.isDisallowedPropertyName_(propName)) {
410 var propValue = goog.html.sanitizer.noclobber.getCssPropertyValue(
411 cssStyle, propName, true /* opt_allowClobbering */);
412
413 var sanitizedValue = goog.html.sanitizer.CssSanitizer.sanitizeProperty_(
414 propName, propValue, opt_uriRewriter);
415 if (sanitizedValue != null) {
416 goog.html.sanitizer.noclobber.setCssProperty(
417 cleanCssStyle, propName, sanitizedValue,
418 true /* opt_allowClobbering */);
419 }
420 }
421 }
422 return goog.html.uncheckedconversions
423 .safeStyleFromStringKnownToSatisfyTypeContract(
424 goog.string.Const.from('Output of CSS sanitizer'),
425 cleanCssStyle.cssText || '');
426 };
427
428
429 /**
430 * Sanitizes inline CSS text and returns it as a SafeStyle object. When adequate
431 * browser support is not available, such as for IE9 and below, a
432 * SafeStyle-wrapped empty string is returned.
433 * @param {string} cssText CSS text to be sanitized.
434 * @param {function(string, string):?goog.html.SafeUrl=} opt_uriRewriter A URI
435 * rewriter that returns a goog.html.SafeUrl.
436 * @return {!goog.html.SafeStyle} A sanitized inline cssText.
437 */
438 goog.html.sanitizer.CssSanitizer.sanitizeInlineStyleString = function(
439 cssText, opt_uriRewriter) {
440 // same check as in goog.html.sanitizer.HTML_SANITIZER_SUPPORTED_
441 if (goog.userAgent.IE && document.documentMode < 10) {
442 return new goog.html.SafeStyle();
443 }
444
445 var div = goog.html.sanitizer.CssSanitizer
446 .createInertDocument_()
447 .createElement('DIV');
448 div.style.cssText = cssText;
449 return goog.html.sanitizer.CssSanitizer.sanitizeInlineStyle(
450 div.style, opt_uriRewriter);
451 };
452
453
454 /**
455 * Converts rules in STYLE tags into style attributes on the tags they apply to.
456 * Modifies the provided DOM subtree in-place.
457 * @param {!Element} element
458 * @package
459 */
460 goog.html.sanitizer.CssSanitizer.inlineStyleRules = function(element) {
461 // Note that Webkit used to offer the perfect function for the job:
462 // getMatchedCSSRules. Unfortunately, it was never supported cross-browser and
463 // is deprecated now. On the other hand, getComputedStyle cannot be used to
464 // differentiate property values that are set by a style sheet from those set
465 // by a style attribute or default values. This algorithm with
466 // O(nr_of_elements * nr_of_rules) complexity that has to manually sort
467 // selectors by specificity is the best we can do.
468
469 // Extract all rules from STYLE tags found in the subtree.
470 /** @type {!Array<!HTMLStyleElement>} */
471 var styleTags =
472 goog.html.sanitizer.noclobber.getElementsByTagName(element, 'STYLE');
473 var cssRules = goog.array.concatMap(styleTags, function(styleTag) {
474 return goog.array.toArray(
475 goog.html.sanitizer.noclobber.getElementStyleSheet(styleTag).cssRules);
476 });
477 cssRules = goog.html.sanitizer.CssSanitizer.getOnlyStyleRules_(cssRules);
478 // Sort the rules by descending specificity.
479 cssRules.sort(function(a, b) {
480 var aSpecificity = goog.html.CssSpecificity.getSpecificity(a.selectorText);
481 var bSpecificity = goog.html.CssSpecificity.getSpecificity(b.selectorText);
482 return -goog.array.compare3(aSpecificity, bSpecificity);
483 });
484 // For each element, apply the matching rules to the element style attribute.
485 // If a property is already explicitly defined, do not update it. This
486 // guarantees that the rule with selectors with the highest priority (or the
487 // properties defined in the style attribute itself) have precedence over
488 // lower priority ones.
489 var subTreeWalker = document.createTreeWalker(
490 element, NodeFilter.SHOW_ELEMENT, null /* filter */,
491 false /* entityReferenceExpansion */);
492 var currentElement;
493 while (currentElement = /** @type {!Element} */ (subTreeWalker.nextNode())) {
494 goog.array.forEach(cssRules, function(rule) {
495 if (!goog.html.sanitizer.noclobber.elementMatches(
496 currentElement, rule.selectorText)) {
497 return;
498 }
499 if (!rule.style) {
500 return;
501 }
502 goog.html.sanitizer.CssSanitizer.mergeStyleDeclarations_(
503 currentElement, rule.style);
504 });
505 }
506 // Delete the STYLE tags.
507 goog.array.forEach(styleTags, goog.dom.removeNode);
508 };
509
510
511 /**
512 * Merges style properties from {@code styleDeclaration} into
513 * {@code element.style}.
514 * @param {!Element} element
515 * @param {!CSSStyleDeclaration} styleDeclaration
516 * @private
517 */
518 goog.html.sanitizer.CssSanitizer.mergeStyleDeclarations_ = function(
519 element, styleDeclaration) {
520 var existingPropNames =
521 goog.html.sanitizer.CssSanitizer.getCssPropNames_(element.style);
522 var newPropNames =
523 goog.html.sanitizer.CssSanitizer.getCssPropNames_(styleDeclaration);
524
525 goog.array.forEach(newPropNames, function(propName) {
526 if (existingPropNames.indexOf(propName) >= 0) {
527 // This was either a property set by the style attribute or a stylesheet
528 // rule with a higher priority. Leave the existing value.
529 return;
530 }
531 var propValue = goog.html.sanitizer.noclobber.getCssPropertyValue(
532 styleDeclaration, propName);
533 goog.html.sanitizer.noclobber.setCssProperty(
534 element.style, propName, propValue);
535 });
536 };
537
538
539 /**
540 * Creates an DOM Document object that will not execute scripts or make
541 * network requests while parsing HTML.
542 * @return {!Document}
543 * @private
544 */
545 goog.html.sanitizer.CssSanitizer.createInertDocument_ = function() {
546 // Documents created using window.document.implementation.createHTMLDocument()
547 // use the same custom component registry as their parent document. This means
548 // that parsing arbitrary HTML can result in calls to user-defined JavaScript.
549 // This is worked around by creating a template element and its content's
550 // document. See https://github.com/cure53/DOMPurify/issues/47.
551 var doc = document;
552 if (typeof HTMLTemplateElement === 'function') {
553 doc =
554 goog.dom.createElement(goog.dom.TagName.TEMPLATE).content.ownerDocument;
555 }
556 return doc.implementation.createHTMLDocument('');
557 };
558
559
560 /**
561 * Provides a cross-browser way to get a CSS property names.
562 * @param {!CSSStyleDeclaration} cssStyle A CSS style object.
563 * @return {!Array<string>} CSS property names.
564 * @private
565 */
566 goog.html.sanitizer.CssSanitizer.getCssPropNames_ = function(cssStyle) {
567 var propNames = [];
568 if (goog.isArrayLike(cssStyle)) {
569 // Gets property names via item().
570 // https://drafts.csswg.org/cssom/#dom-cssstyledeclaration-item
571 propNames = goog.array.toArray(cssStyle);
572 } else {
573 // In IE8 and other older browsers we have to iterate over all the property
574 // names. We skip cssText because it contains the unsanitized CSS, which
575 // defeats the purpose.
576 propNames = goog.object.getKeys(cssStyle);
577 goog.array.remove(propNames, 'cssText');
578 }
579 return propNames;
580 };
581
582
583 /**
584 * Checks whether the property name specified should be disallowed.
585 * @param {string} propName A property name.
586 * @return {boolean} Whether the property name is disallowed.
587 * @private
588 */
589 goog.html.sanitizer.CssSanitizer.isDisallowedPropertyName_ = function(
590 propName) {
591 // getPropertyValue doesn't deal with custom variables properly and will NOT
592 // decode CSS escapes (but the browser will do so silently). Simply disallow
593 // custom variables (http://www.w3.org/TR/css-variables/#defining-variables).
594 return goog.string.startsWith(propName, '--') ||
595 goog.string.startsWith(propName, 'var');
596 };