Debian Codegraph @

closure-library/closure/goog/html/safestyle.js

raw
1 // Copyright 2014 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 The SafeStyle type and its builders.
17 *
18 * TODO(xtof): Link to document stating type contract.
19 */
20
21 goog.provide('goog.html.SafeStyle');
22
23 goog.require('goog.array');
24 goog.require('goog.asserts');
25 goog.require('goog.html.SafeUrl');
26 goog.require('goog.string');
27 goog.require('goog.string.Const');
28 goog.require('goog.string.TypedString');
29
30
31
32 /**
33 * A string-like object which represents a sequence of CSS declarations
34 * ({@code propertyName1: propertyvalue1; propertyName2: propertyValue2; ...})
35 * and that carries the security type contract that its value, as a string,
36 * will not cause untrusted script execution (XSS) when evaluated as CSS in a
37 * browser.
38 *
39 * Instances of this type must be created via the factory methods
40 * ({@code goog.html.SafeStyle.create} or
41 * {@code goog.html.SafeStyle.fromConstant}) and not by invoking its
42 * constructor. The constructor intentionally takes no parameters and the type
43 * is immutable; hence only a default instance corresponding to the empty string
44 * can be obtained via constructor invocation.
45 *
46 * SafeStyle's string representation can safely be:
47 * <ul>
48 * <li>Interpolated as the content of a *quoted* HTML style attribute.
49 * However, the SafeStyle string *must be HTML-attribute-escaped* before
50 * interpolation.
51 * <li>Interpolated as the content of a {}-wrapped block within a stylesheet.
52 * '<' characters in the SafeStyle string *must be CSS-escaped* before
53 * interpolation. The SafeStyle string is also guaranteed not to be able
54 * to introduce new properties or elide existing ones.
55 * <li>Interpolated as the content of a {}-wrapped block within an HTML
56 * <style> element. '<' characters in the SafeStyle string
57 * *must be CSS-escaped* before interpolation.
58 * <li>Assigned to the style property of a DOM node. The SafeStyle string
59 * should not be escaped before being assigned to the property.
60 * </ul>
61 *
62 * A SafeStyle may never contain literal angle brackets. Otherwise, it could
63 * be unsafe to place a SafeStyle into a &lt;style&gt; tag (where it can't
64 * be HTML escaped). For example, if the SafeStyle containing
65 * "{@code font: 'foo &lt;style/&gt;&lt;script&gt;evil&lt;/script&gt;'}" were
66 * interpolated within a &lt;style&gt; tag, this would then break out of the
67 * style context into HTML.
68 *
69 * A SafeStyle may contain literal single or double quotes, and as such the
70 * entire style string must be escaped when used in a style attribute (if
71 * this were not the case, the string could contain a matching quote that
72 * would escape from the style attribute).
73 *
74 * Values of this type must be composable, i.e. for any two values
75 * {@code style1} and {@code style2} of this type,
76 * {@code goog.html.SafeStyle.unwrap(style1) +
77 * goog.html.SafeStyle.unwrap(style2)} must itself be a value that satisfies
78 * the SafeStyle type constraint. This requirement implies that for any value
79 * {@code style} of this type, {@code goog.html.SafeStyle.unwrap(style)} must
80 * not end in a "property value" or "property name" context. For example,
81 * a value of {@code background:url("} or {@code font-} would not satisfy the
82 * SafeStyle contract. This is because concatenating such strings with a
83 * second value that itself does not contain unsafe CSS can result in an
84 * overall string that does. For example, if {@code javascript:evil())"} is
85 * appended to {@code background:url("}, the resulting string may result in
86 * the execution of a malicious script.
87 *
88 * TODO(mlourenco): Consider whether we should implement UTF-8 interchange
89 * validity checks and blacklisting of newlines (including Unicode ones) and
90 * other whitespace characters (\t, \f). Document here if so and also update
91 * SafeStyle.fromConstant().
92 *
93 * The following example values comply with this type's contract:
94 * <ul>
95 * <li><pre>width: 1em;</pre>
96 * <li><pre>height:1em;</pre>
97 * <li><pre>width: 1em;height: 1em;</pre>
98 * <li><pre>background:url('http://url');</pre>
99 * </ul>
100 * In addition, the empty string is safe for use in a CSS attribute.
101 *
102 * The following example values do NOT comply with this type's contract:
103 * <ul>
104 * <li><pre>background: red</pre> (missing a trailing semi-colon)
105 * <li><pre>background:</pre> (missing a value and a trailing semi-colon)
106 * <li><pre>1em</pre> (missing an attribute name, which provides context for
107 * the value)
108 * </ul>
109 *
110 * @see goog.html.SafeStyle#create
111 * @see goog.html.SafeStyle#fromConstant
112 * @see http://www.w3.org/TR/css3-syntax/
113 * @constructor
114 * @final
115 * @struct
116 * @implements {goog.string.TypedString}
117 */
118 goog.html.SafeStyle = function() {
119 /**
120 * The contained value of this SafeStyle. The field has a purposely
121 * ugly name to make (non-compiled) code that attempts to directly access this
122 * field stand out.
123 * @private {string}
124 */
125 this.privateDoNotAccessOrElseSafeStyleWrappedValue_ = '';
126
127 /**
128 * A type marker used to implement additional run-time type checking.
129 * @see goog.html.SafeStyle#unwrap
130 * @const {!Object}
131 * @private
132 */
133 this.SAFE_STYLE_TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ =
134 goog.html.SafeStyle.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_;
135 };
136
137
138 /**
139 * @override
140 * @const
141 */
142 goog.html.SafeStyle.prototype.implementsGoogStringTypedString = true;
143
144
145 /**
146 * Type marker for the SafeStyle type, used to implement additional
147 * run-time type checking.
148 * @const {!Object}
149 * @private
150 */
151 goog.html.SafeStyle.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ = {};
152
153
154 /**
155 * Creates a SafeStyle object from a compile-time constant string.
156 *
157 * {@code style} should be in the format
158 * {@code name: value; [name: value; ...]} and must not have any < or >
159 * characters in it. This is so that SafeStyle's contract is preserved,
160 * allowing the SafeStyle to correctly be interpreted as a sequence of CSS
161 * declarations and without affecting the syntactic structure of any
162 * surrounding CSS and HTML.
163 *
164 * This method performs basic sanity checks on the format of {@code style}
165 * but does not constrain the format of {@code name} and {@code value}, except
166 * for disallowing tag characters.
167 *
168 * @param {!goog.string.Const} style A compile-time-constant string from which
169 * to create a SafeStyle.
170 * @return {!goog.html.SafeStyle} A SafeStyle object initialized to
171 * {@code style}.
172 */
173 goog.html.SafeStyle.fromConstant = function(style) {
174 var styleString = goog.string.Const.unwrap(style);
175 if (styleString.length === 0) {
176 return goog.html.SafeStyle.EMPTY;
177 }
178 goog.html.SafeStyle.checkStyle_(styleString);
179 goog.asserts.assert(
180 goog.string.endsWith(styleString, ';'),
181 'Last character of style string is not \';\': ' + styleString);
182 goog.asserts.assert(
183 goog.string.contains(styleString, ':'),
184 'Style string must contain at least one \':\', to ' +
185 'specify a "name: value" pair: ' + styleString);
186 return goog.html.SafeStyle.createSafeStyleSecurityPrivateDoNotAccessOrElse(
187 styleString);
188 };
189
190
191 /**
192 * Checks if the style definition is valid.
193 * @param {string} style
194 * @private
195 */
196 goog.html.SafeStyle.checkStyle_ = function(style) {
197 goog.asserts.assert(
198 !/[<>]/.test(style), 'Forbidden characters in style string: ' + style);
199 };
200
201
202 /**
203 * Returns this SafeStyle's value as a string.
204 *
205 * IMPORTANT: In code where it is security relevant that an object's type is
206 * indeed {@code SafeStyle}, use {@code goog.html.SafeStyle.unwrap} instead of
207 * this method. If in doubt, assume that it's security relevant. In particular,
208 * note that goog.html functions which return a goog.html type do not guarantee
209 * the returned instance is of the right type. For example:
210 *
211 * <pre>
212 * var fakeSafeHtml = new String('fake');
213 * fakeSafeHtml.__proto__ = goog.html.SafeHtml.prototype;
214 * var newSafeHtml = goog.html.SafeHtml.htmlEscape(fakeSafeHtml);
215 * // newSafeHtml is just an alias for fakeSafeHtml, it's passed through by
216 * // goog.html.SafeHtml.htmlEscape() as fakeSafeHtml
217 * // instanceof goog.html.SafeHtml.
218 * </pre>
219 *
220 * @see goog.html.SafeStyle#unwrap
221 * @override
222 */
223 goog.html.SafeStyle.prototype.getTypedStringValue = function() {
224 return this.privateDoNotAccessOrElseSafeStyleWrappedValue_;
225 };
226
227
228 if (goog.DEBUG) {
229 /**
230 * Returns a debug string-representation of this value.
231 *
232 * To obtain the actual string value wrapped in a SafeStyle, use
233 * {@code goog.html.SafeStyle.unwrap}.
234 *
235 * @see goog.html.SafeStyle#unwrap
236 * @override
237 */
238 goog.html.SafeStyle.prototype.toString = function() {
239 return 'SafeStyle{' + this.privateDoNotAccessOrElseSafeStyleWrappedValue_ +
240 '}';
241 };
242 }
243
244
245 /**
246 * Performs a runtime check that the provided object is indeed a
247 * SafeStyle object, and returns its value.
248 *
249 * @param {!goog.html.SafeStyle} safeStyle The object to extract from.
250 * @return {string} The safeStyle object's contained string, unless
251 * the run-time type check fails. In that case, {@code unwrap} returns an
252 * innocuous string, or, if assertions are enabled, throws
253 * {@code goog.asserts.AssertionError}.
254 */
255 goog.html.SafeStyle.unwrap = function(safeStyle) {
256 // Perform additional Run-time type-checking to ensure that
257 // safeStyle is indeed an instance of the expected type. This
258 // provides some additional protection against security bugs due to
259 // application code that disables type checks.
260 // Specifically, the following checks are performed:
261 // 1. The object is an instance of the expected type.
262 // 2. The object is not an instance of a subclass.
263 // 3. The object carries a type marker for the expected type. "Faking" an
264 // object requires a reference to the type marker, which has names intended
265 // to stand out in code reviews.
266 if (safeStyle instanceof goog.html.SafeStyle &&
267 safeStyle.constructor === goog.html.SafeStyle &&
268 safeStyle.SAFE_STYLE_TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ ===
269 goog.html.SafeStyle.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_) {
270 return safeStyle.privateDoNotAccessOrElseSafeStyleWrappedValue_;
271 } else {
272 goog.asserts.fail('expected object of type SafeStyle, got \'' +
273 safeStyle + '\' of type ' + goog.typeOf(safeStyle));
274 return 'type_error:SafeStyle';
275 }
276 };
277
278
279 /**
280 * Package-internal utility method to create SafeStyle instances.
281 *
282 * @param {string} style The string to initialize the SafeStyle object with.
283 * @return {!goog.html.SafeStyle} The initialized SafeStyle object.
284 * @package
285 */
286 goog.html.SafeStyle.createSafeStyleSecurityPrivateDoNotAccessOrElse = function(
287 style) {
288 return new goog.html.SafeStyle().initSecurityPrivateDoNotAccessOrElse_(style);
289 };
290
291
292 /**
293 * Called from createSafeStyleSecurityPrivateDoNotAccessOrElse(). This
294 * method exists only so that the compiler can dead code eliminate static
295 * fields (like EMPTY) when they're not accessed.
296 * @param {string} style
297 * @return {!goog.html.SafeStyle}
298 * @private
299 */
300 goog.html.SafeStyle.prototype.initSecurityPrivateDoNotAccessOrElse_ = function(
301 style) {
302 this.privateDoNotAccessOrElseSafeStyleWrappedValue_ = style;
303 return this;
304 };
305
306
307 /**
308 * A SafeStyle instance corresponding to the empty string.
309 * @const {!goog.html.SafeStyle}
310 */
311 goog.html.SafeStyle.EMPTY =
312 goog.html.SafeStyle.createSafeStyleSecurityPrivateDoNotAccessOrElse('');
313
314
315 /**
316 * The innocuous string generated by goog.html.SafeStyle.create when passed
317 * an unsafe value.
318 * @const {string}
319 */
320 goog.html.SafeStyle.INNOCUOUS_STRING = 'zClosurez';
321
322
323 /**
324 * A single property value.
325 * @typedef {string|!goog.string.Const|!goog.html.SafeUrl}
326 */
327 goog.html.SafeStyle.PropertyValue;
328
329
330 /**
331 * Mapping of property names to their values.
332 * We don't support numbers even though some values might be numbers (e.g.
333 * line-height or 0 for any length). The reason is that most numeric values need
334 * units (e.g. '1px') and allowing numbers could cause users forgetting about
335 * them.
336 * @typedef {!Object<string, ?goog.html.SafeStyle.PropertyValue|
337 * ?Array<!goog.html.SafeStyle.PropertyValue>>}
338 */
339 goog.html.SafeStyle.PropertyMap;
340
341
342 /**
343 * Creates a new SafeStyle object from the properties specified in the map.
344 * @param {goog.html.SafeStyle.PropertyMap} map Mapping of property names to
345 * their values, for example {'margin': '1px'}. Names must consist of
346 * [-_a-zA-Z0-9]. Values might be strings consisting of
347 * [-,.'"%_!# a-zA-Z0-9], where " and ' must be properly balanced. We also
348 * allow simple functions like rgb() and url() which sanitizes its contents.
349 * Other values must be wrapped in goog.string.Const. URLs might be passed
350 * as goog.html.SafeUrl which will be wrapped into url(""). We also support
351 * array whose elements are joined with ' '. Null value causes skipping the
352 * property.
353 * @return {!goog.html.SafeStyle}
354 * @throws {Error} If invalid name is provided.
355 * @throws {goog.asserts.AssertionError} If invalid value is provided. With
356 * disabled assertions, invalid value is replaced by
357 * goog.html.SafeStyle.INNOCUOUS_STRING.
358 */
359 goog.html.SafeStyle.create = function(map) {
360 var style = '';
361 for (var name in map) {
362 if (!/^[-_a-zA-Z0-9]+$/.test(name)) {
363 throw new Error('Name allows only [-_a-zA-Z0-9], got: ' + name);
364 }
365 var value = map[name];
366 if (value == null) {
367 continue;
368 }
369 if (goog.isArray(value)) {
370 value = goog.array.map(value, goog.html.SafeStyle.sanitizePropertyValue_)
371 .join(' ');
372 } else {
373 value = goog.html.SafeStyle.sanitizePropertyValue_(value);
374 }
375 style += name + ':' + value + ';';
376 }
377 if (!style) {
378 return goog.html.SafeStyle.EMPTY;
379 }
380 goog.html.SafeStyle.checkStyle_(style);
381 return goog.html.SafeStyle.createSafeStyleSecurityPrivateDoNotAccessOrElse(
382 style);
383 };
384
385
386 /**
387 * Checks and converts value to string.
388 * @param {!goog.html.SafeStyle.PropertyValue} value
389 * @return {string}
390 * @private
391 */
392 goog.html.SafeStyle.sanitizePropertyValue_ = function(value) {
393 if (value instanceof goog.html.SafeUrl) {
394 var url = goog.html.SafeUrl.unwrap(value);
395 return 'url("' + url.replace(/</g, '%3c').replace(/[\\"]/g, '\\$&') + '")';
396 }
397 var result = value instanceof goog.string.Const ?
398 goog.string.Const.unwrap(value) :
399 goog.html.SafeStyle.sanitizePropertyValueString_(String(value));
400 // These characters can be used to change context and we don't want that even
401 // with const values.
402 goog.asserts.assert(!/[{;}]/.test(result), 'Value does not allow [{;}].');
403 return result;
404 };
405
406
407 /**
408 * Checks string value.
409 * @param {string} value
410 * @return {string}
411 * @private
412 */
413 goog.html.SafeStyle.sanitizePropertyValueString_ = function(value) {
414 var valueWithoutFunctions =
415 value.replace(goog.html.SafeUrl.FUNCTIONS_RE_, '$1')
416 .replace(goog.html.SafeUrl.URL_RE_, 'url');
417 if (!goog.html.SafeStyle.VALUE_RE_.test(valueWithoutFunctions)) {
418 goog.asserts.fail(
419 'String value allows only ' + goog.html.SafeStyle.VALUE_ALLOWED_CHARS_ +
420 ' and simple functions, got: ' + value);
421 return goog.html.SafeStyle.INNOCUOUS_STRING;
422 } else if (!goog.html.SafeStyle.hasBalancedQuotes_(value)) {
423 goog.asserts.fail('String value requires balanced quotes, got: ' + value);
424 return goog.html.SafeStyle.INNOCUOUS_STRING;
425 }
426 return goog.html.SafeStyle.sanitizeUrl_(value);
427 };
428
429
430 /**
431 * Checks that quotes (" and ') are properly balanced inside a string. Assumes
432 * that neither escape (\) nor any other character that could result in
433 * breaking out of a string parsing context are allowed;
434 * see http://www.w3.org/TR/css3-syntax/#string-token-diagram.
435 * @param {string} value Untrusted CSS property value.
436 * @return {boolean} True if property value is safe with respect to quote
437 * balancedness.
438 * @private
439 */
440 goog.html.SafeStyle.hasBalancedQuotes_ = function(value) {
441 var outsideSingle = true;
442 var outsideDouble = true;
443 for (var i = 0; i < value.length; i++) {
444 var c = value.charAt(i);
445 if (c == "'" && outsideDouble) {
446 outsideSingle = !outsideSingle;
447 } else if (c == '"' && outsideSingle) {
448 outsideDouble = !outsideDouble;
449 }
450 }
451 return outsideSingle && outsideDouble;
452 };
453
454
455 /**
456 * Characters allowed in goog.html.SafeStyle.VALUE_RE_.
457 * @private {string}
458 */
459 goog.html.SafeStyle.VALUE_ALLOWED_CHARS_ = '[-,."\'%_!# a-zA-Z0-9]';
460
461
462 /**
463 * Regular expression for safe values.
464 *
465 * Quotes (" and ') are allowed, but a check must be done elsewhere to ensure
466 * they're balanced.
467 *
468 * ',' allows multiple values to be assigned to the same property
469 * (e.g. background-attachment or font-family) and hence could allow
470 * multiple values to get injected, but that should pose no risk of XSS.
471 *
472 * The expression checks only for XSS safety, not for CSS validity.
473 * @const {!RegExp}
474 * @private
475 */
476 goog.html.SafeStyle.VALUE_RE_ =
477 new RegExp('^' + goog.html.SafeStyle.VALUE_ALLOWED_CHARS_ + '+$');
478
479
480 /**
481 * Regular expression for url(). We support URLs allowed by
482 * https://www.w3.org/TR/css-syntax-3/#url-token-diagram without using escape
483 * sequences. Use percent-encoding if you need to use special characters like
484 * backslash.
485 * @private @const {!RegExp}
486 */
487 goog.html.SafeUrl.URL_RE_ = new RegExp(
488 '\\b(url\\([ \t\n]*)(' +
489 '\'[ -&(-\\[\\]-~]*\'' + // Printable characters except ' and \.
490 '|"[ !#-\\[\\]-~]*"' + // Printable characters except " and \.
491 '|[!#-&*-\\[\\]-~]*' + // Printable characters except [ "'()\\].
492 ')([ \t\n]*\\))',
493 'g');
494
495
496 /**
497 * Regular expression for simple functions.
498 * @private @const {!RegExp}
499 */
500 goog.html.SafeUrl.FUNCTIONS_RE_ = new RegExp(
501 '\\b(hsl|hsla|rgb|rgba|(rotate|scale|translate)(X|Y|Z|3d)?)' +
502 '\\([-0-9a-z.%, ]+\\)',
503 'g');
504
505
506 /**
507 * Sanitize URLs inside url().
508 *
509 * NOTE: We could also consider using CSS.escape once that's available in the
510 * browsers. However, loosely matching URL e.g. with url\(.*\) and then escaping
511 * the contents would result in a slightly different language than CSS leading
512 * to confusion of users. E.g. url(")") is valid in CSS but it would be invalid
513 * as seen by our parser. On the other hand, url(\) is invalid in CSS but our
514 * parser would be fine with it.
515 *
516 * @param {string} value Untrusted CSS property value.
517 * @return {string}
518 * @private
519 */
520 goog.html.SafeStyle.sanitizeUrl_ = function(value) {
521 return value.replace(
522 goog.html.SafeUrl.URL_RE_, function(match, before, url, after) {
523 var quote = '';
524 url = url.replace(/^(['"])(.*)\1$/, function(match, start, inside) {
525 quote = start;
526 return inside;
527 });
528 var sanitized = goog.html.SafeUrl.sanitize(url).getTypedStringValue();
529 return before + quote + sanitized + quote + after;
530 });
531 };
532
533
534 /**
535 * Creates a new SafeStyle object by concatenating the values.
536 * @param {...(!goog.html.SafeStyle|!Array<!goog.html.SafeStyle>)} var_args
537 * SafeStyles to concatenate.
538 * @return {!goog.html.SafeStyle}
539 */
540 goog.html.SafeStyle.concat = function(var_args) {
541 var style = '';
542
543 /**
544 * @param {!goog.html.SafeStyle|!Array<!goog.html.SafeStyle>} argument
545 */
546 var addArgument = function(argument) {
547 if (goog.isArray(argument)) {
548 goog.array.forEach(argument, addArgument);
549 } else {
550 style += goog.html.SafeStyle.unwrap(argument);
551 }
552 };
553
554 goog.array.forEach(arguments, addArgument);
555 if (!style) {
556 return goog.html.SafeStyle.EMPTY;
557 }
558 return goog.html.SafeStyle.createSafeStyleSecurityPrivateDoNotAccessOrElse(
559 style);
560 };