safestylesheet.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  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. * @fileoverview The SafeStyleSheet type and its builders.
  16. *
  17. * TODO(xtof): Link to document stating type contract.
  18. */
  19. goog.provide('goog.html.SafeStyleSheet');
  20. goog.require('goog.array');
  21. goog.require('goog.asserts');
  22. goog.require('goog.html.SafeStyle');
  23. goog.require('goog.object');
  24. goog.require('goog.string');
  25. goog.require('goog.string.Const');
  26. goog.require('goog.string.TypedString');
  27. /**
  28. * A string-like object which represents a CSS style sheet and that carries the
  29. * security type contract that its value, as a string, will not cause untrusted
  30. * script execution (XSS) when evaluated as CSS in a browser.
  31. *
  32. * Instances of this type must be created via the factory method
  33. * {@code goog.html.SafeStyleSheet.fromConstant} and not by invoking its
  34. * constructor. The constructor intentionally takes no parameters and the type
  35. * is immutable; hence only a default instance corresponding to the empty string
  36. * can be obtained via constructor invocation.
  37. *
  38. * A SafeStyleSheet's string representation can safely be interpolated as the
  39. * content of a style element within HTML. The SafeStyleSheet string should
  40. * not be escaped before interpolation.
  41. *
  42. * Values of this type must be composable, i.e. for any two values
  43. * {@code styleSheet1} and {@code styleSheet2} of this type,
  44. * {@code goog.html.SafeStyleSheet.unwrap(styleSheet1) +
  45. * goog.html.SafeStyleSheet.unwrap(styleSheet2)} must itself be a value that
  46. * satisfies the SafeStyleSheet type constraint. This requirement implies that
  47. * for any value {@code styleSheet} of this type,
  48. * {@code goog.html.SafeStyleSheet.unwrap(styleSheet1)} must end in
  49. * "beginning of rule" context.
  50. * A SafeStyleSheet can be constructed via security-reviewed unchecked
  51. * conversions. In this case producers of SafeStyleSheet must ensure themselves
  52. * that the SafeStyleSheet does not contain unsafe script. Note in particular
  53. * that {@code <} is dangerous, even when inside CSS strings, and so should
  54. * always be forbidden or CSS-escaped in user controlled input. For example, if
  55. * {@code </style><script>evil</script>"} were interpolated
  56. * inside a CSS string, it would break out of the context of the original
  57. * style element and {@code evil} would execute. Also note that within an HTML
  58. * style (raw text) element, HTML character references, such as
  59. * {@code <}, are not allowed. See
  60. *
  61. http://www.w3.org/TR/html5/scripting-1.html#restrictions-for-contents-of-script-elements
  62. * (similar considerations apply to the style element).
  63. *
  64. * @see goog.html.SafeStyleSheet#fromConstant
  65. * @constructor
  66. * @final
  67. * @struct
  68. * @implements {goog.string.TypedString}
  69. */
  70. goog.html.SafeStyleSheet = function() {
  71. /**
  72. * The contained value of this SafeStyleSheet. The field has a purposely
  73. * ugly name to make (non-compiled) code that attempts to directly access this
  74. * field stand out.
  75. * @private {string}
  76. */
  77. this.privateDoNotAccessOrElseSafeStyleSheetWrappedValue_ = '';
  78. /**
  79. * A type marker used to implement additional run-time type checking.
  80. * @see goog.html.SafeStyleSheet#unwrap
  81. * @const {!Object}
  82. * @private
  83. */
  84. this.SAFE_STYLE_SHEET_TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ =
  85. goog.html.SafeStyleSheet.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_;
  86. };
  87. /**
  88. * @override
  89. * @const
  90. */
  91. goog.html.SafeStyleSheet.prototype.implementsGoogStringTypedString = true;
  92. /**
  93. * Type marker for the SafeStyleSheet type, used to implement additional
  94. * run-time type checking.
  95. * @const {!Object}
  96. * @private
  97. */
  98. goog.html.SafeStyleSheet.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ = {};
  99. /**
  100. * Creates a style sheet consisting of one selector and one style definition.
  101. * Use {@link goog.html.SafeStyleSheet.concat} to create longer style sheets.
  102. * This function doesn't support @import, @media and similar constructs.
  103. * @param {string} selector CSS selector, e.g. '#id' or 'tag .class, #id'. We
  104. * support CSS3 selectors: https://w3.org/TR/css3-selectors/#selectors.
  105. * @param {!goog.html.SafeStyle.PropertyMap|!goog.html.SafeStyle} style Style
  106. * definition associated with the selector.
  107. * @return {!goog.html.SafeStyleSheet}
  108. * @throws {Error} If invalid selector is provided.
  109. */
  110. goog.html.SafeStyleSheet.createRule = function(selector, style) {
  111. if (goog.string.contains(selector, '<')) {
  112. throw Error('Selector does not allow \'<\', got: ' + selector);
  113. }
  114. // Remove strings.
  115. var selectorToCheck =
  116. selector.replace(/('|")((?!\1)[^\r\n\f\\]|\\[\s\S])*\1/g, '');
  117. // Check characters allowed in CSS3 selectors.
  118. if (!/^[-_a-zA-Z0-9#.:* ,>+~[\]()=^$|]+$/.test(selectorToCheck)) {
  119. throw Error(
  120. 'Selector allows only [-_a-zA-Z0-9#.:* ,>+~[\\]()=^$|] and ' +
  121. 'strings, got: ' + selector);
  122. }
  123. // Check balanced () and [].
  124. if (!goog.html.SafeStyleSheet.hasBalancedBrackets_(selectorToCheck)) {
  125. throw Error('() and [] in selector must be balanced, got: ' + selector);
  126. }
  127. if (!(style instanceof goog.html.SafeStyle)) {
  128. style = goog.html.SafeStyle.create(style);
  129. }
  130. var styleSheet = selector + '{' + goog.html.SafeStyle.unwrap(style) + '}';
  131. return goog.html.SafeStyleSheet
  132. .createSafeStyleSheetSecurityPrivateDoNotAccessOrElse(styleSheet);
  133. };
  134. /**
  135. * Checks if a string has balanced () and [] brackets.
  136. * @param {string} s String to check.
  137. * @return {boolean}
  138. * @private
  139. */
  140. goog.html.SafeStyleSheet.hasBalancedBrackets_ = function(s) {
  141. var brackets = {'(': ')', '[': ']'};
  142. var expectedBrackets = [];
  143. for (var i = 0; i < s.length; i++) {
  144. var ch = s[i];
  145. if (brackets[ch]) {
  146. expectedBrackets.push(brackets[ch]);
  147. } else if (goog.object.contains(brackets, ch)) {
  148. if (expectedBrackets.pop() != ch) {
  149. return false;
  150. }
  151. }
  152. }
  153. return expectedBrackets.length == 0;
  154. };
  155. /**
  156. * Creates a new SafeStyleSheet object by concatenating values.
  157. * @param {...(!goog.html.SafeStyleSheet|!Array<!goog.html.SafeStyleSheet>)}
  158. * var_args Values to concatenate.
  159. * @return {!goog.html.SafeStyleSheet}
  160. */
  161. goog.html.SafeStyleSheet.concat = function(var_args) {
  162. var result = '';
  163. /**
  164. * @param {!goog.html.SafeStyleSheet|!Array<!goog.html.SafeStyleSheet>}
  165. * argument
  166. */
  167. var addArgument = function(argument) {
  168. if (goog.isArray(argument)) {
  169. goog.array.forEach(argument, addArgument);
  170. } else {
  171. result += goog.html.SafeStyleSheet.unwrap(argument);
  172. }
  173. };
  174. goog.array.forEach(arguments, addArgument);
  175. return goog.html.SafeStyleSheet
  176. .createSafeStyleSheetSecurityPrivateDoNotAccessOrElse(result);
  177. };
  178. /**
  179. * Creates a SafeStyleSheet object from a compile-time constant string.
  180. *
  181. * {@code styleSheet} must not have any &lt; characters in it, so that
  182. * the syntactic structure of the surrounding HTML is not affected.
  183. *
  184. * @param {!goog.string.Const} styleSheet A compile-time-constant string from
  185. * which to create a SafeStyleSheet.
  186. * @return {!goog.html.SafeStyleSheet} A SafeStyleSheet object initialized to
  187. * {@code styleSheet}.
  188. */
  189. goog.html.SafeStyleSheet.fromConstant = function(styleSheet) {
  190. var styleSheetString = goog.string.Const.unwrap(styleSheet);
  191. if (styleSheetString.length === 0) {
  192. return goog.html.SafeStyleSheet.EMPTY;
  193. }
  194. // > is a valid character in CSS selectors and there's no strict need to
  195. // block it if we already block <.
  196. goog.asserts.assert(
  197. !goog.string.contains(styleSheetString, '<'),
  198. "Forbidden '<' character in style sheet string: " + styleSheetString);
  199. return goog.html.SafeStyleSheet
  200. .createSafeStyleSheetSecurityPrivateDoNotAccessOrElse(styleSheetString);
  201. };
  202. /**
  203. * Returns this SafeStyleSheet's value as a string.
  204. *
  205. * IMPORTANT: In code where it is security relevant that an object's type is
  206. * indeed {@code SafeStyleSheet}, use {@code goog.html.SafeStyleSheet.unwrap}
  207. * instead of this method. If in doubt, assume that it's security relevant. In
  208. * particular, note that goog.html functions which return a goog.html type do
  209. * not guarantee 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.SafeStyleSheet#unwrap
  221. * @override
  222. */
  223. goog.html.SafeStyleSheet.prototype.getTypedStringValue = function() {
  224. return this.privateDoNotAccessOrElseSafeStyleSheetWrappedValue_;
  225. };
  226. if (goog.DEBUG) {
  227. /**
  228. * Returns a debug string-representation of this value.
  229. *
  230. * To obtain the actual string value wrapped in a SafeStyleSheet, use
  231. * {@code goog.html.SafeStyleSheet.unwrap}.
  232. *
  233. * @see goog.html.SafeStyleSheet#unwrap
  234. * @override
  235. */
  236. goog.html.SafeStyleSheet.prototype.toString = function() {
  237. return 'SafeStyleSheet{' +
  238. this.privateDoNotAccessOrElseSafeStyleSheetWrappedValue_ + '}';
  239. };
  240. }
  241. /**
  242. * Performs a runtime check that the provided object is indeed a
  243. * SafeStyleSheet object, and returns its value.
  244. *
  245. * @param {!goog.html.SafeStyleSheet} safeStyleSheet The object to extract from.
  246. * @return {string} The safeStyleSheet object's contained string, unless
  247. * the run-time type check fails. In that case, {@code unwrap} returns an
  248. * innocuous string, or, if assertions are enabled, throws
  249. * {@code goog.asserts.AssertionError}.
  250. */
  251. goog.html.SafeStyleSheet.unwrap = function(safeStyleSheet) {
  252. // Perform additional Run-time type-checking to ensure that
  253. // safeStyleSheet is indeed an instance of the expected type. This
  254. // provides some additional protection against security bugs due to
  255. // application code that disables type checks.
  256. // Specifically, the following checks are performed:
  257. // 1. The object is an instance of the expected type.
  258. // 2. The object is not an instance of a subclass.
  259. // 3. The object carries a type marker for the expected type. "Faking" an
  260. // object requires a reference to the type marker, which has names intended
  261. // to stand out in code reviews.
  262. if (safeStyleSheet instanceof goog.html.SafeStyleSheet &&
  263. safeStyleSheet.constructor === goog.html.SafeStyleSheet &&
  264. safeStyleSheet
  265. .SAFE_STYLE_SHEET_TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ ===
  266. goog.html.SafeStyleSheet.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_) {
  267. return safeStyleSheet.privateDoNotAccessOrElseSafeStyleSheetWrappedValue_;
  268. } else {
  269. goog.asserts.fail('expected object of type SafeStyleSheet, got \'' +
  270. safeStyleSheet + '\' of type ' + goog.typeOf(safeStyleSheet));
  271. return 'type_error:SafeStyleSheet';
  272. }
  273. };
  274. /**
  275. * Package-internal utility method to create SafeStyleSheet instances.
  276. *
  277. * @param {string} styleSheet The string to initialize the SafeStyleSheet
  278. * object with.
  279. * @return {!goog.html.SafeStyleSheet} The initialized SafeStyleSheet object.
  280. * @package
  281. */
  282. goog.html.SafeStyleSheet.createSafeStyleSheetSecurityPrivateDoNotAccessOrElse =
  283. function(styleSheet) {
  284. return new goog.html.SafeStyleSheet().initSecurityPrivateDoNotAccessOrElse_(
  285. styleSheet);
  286. };
  287. /**
  288. * Called from createSafeStyleSheetSecurityPrivateDoNotAccessOrElse(). This
  289. * method exists only so that the compiler can dead code eliminate static
  290. * fields (like EMPTY) when they're not accessed.
  291. * @param {string} styleSheet
  292. * @return {!goog.html.SafeStyleSheet}
  293. * @private
  294. */
  295. goog.html.SafeStyleSheet.prototype.initSecurityPrivateDoNotAccessOrElse_ =
  296. function(styleSheet) {
  297. this.privateDoNotAccessOrElseSafeStyleSheetWrappedValue_ = styleSheet;
  298. return this;
  299. };
  300. /**
  301. * A SafeStyleSheet instance corresponding to the empty string.
  302. * @const {!goog.html.SafeStyleSheet}
  303. */
  304. goog.html.SafeStyleSheet.EMPTY =
  305. goog.html.SafeStyleSheet
  306. .createSafeStyleSheetSecurityPrivateDoNotAccessOrElse('');