XssTest.php 18 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
<?php

/**
 * @file
 * Contains \Drupal\Tests\Component\Utility\XssTest.
 */

namespace Drupal\Tests\Component\Utility;

use Drupal\Component\Utility\String;
11
use Drupal\Component\Utility\UrlHelper;
12
13
14
15
use Drupal\Component\Utility\Xss;
use Drupal\Tests\UnitTestCase;

/**
16
17
 * @coversDefaultClass \Drupal\Component\Utility\Xss
 * @group Utility
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
 *
 * Script injection vectors mostly adopted from http://ha.ckers.org/xss.html.
 *
 * Relevant CVEs:
 * - CVE-2002-1806, ~CVE-2005-0682, ~CVE-2005-2106, CVE-2005-3973,
 *   CVE-2006-1226 (= rev. 1.112?), CVE-2008-0273, CVE-2008-3740.
 */
class XssTest extends UnitTestCase {

  /**
   * {@inheritdoc}
   */
  protected function setUp() {
    parent::setUp();

    $allowed_protocols = array(
      'http',
      'https',
      'ftp',
      'news',
      'nntp',
      'telnet',
      'mailto',
      'irc',
      'ssh',
      'sftp',
      'webcal',
      'rtsp',
    );
47
    UrlHelper::setAllowedProtocols($allowed_protocols);
48
49
50
51
52
53
54
55
56
57
58
59
60
61
  }

  /**
   * Tests limiting allowed tags and XSS prevention.
   *
   * XSS tests assume that script is disallowed by default and src is allowed
   * by default, but on* and style attributes are disallowed.
   *
   * @param string $value
   *   The value to filter.
   * @param string $expected
   *   The expected result.
   * @param string $message
   *   The assertion message to display upon failure.
62
63
   * @param array $allowed_tags
   *   (optional) The allowed HTML tags to be passed to \Drupal\Component\Utility\Xss::filter().
64
65
66
   *
   * @dataProvider providerTestFilterXssNormalized
   */
67
68
69
70
71
72
73
74
  public function testFilterXssNormalized($value, $expected, $message, array $allowed_tags = NULL) {
    if ($allowed_tags === NULL) {
      $value = Xss::filter($value);
    }
    else {
      $value = Xss::filter($value, $allowed_tags);
    }
    $this->assertNormalized($value, $expected, $message);
75
76
77
78
79
80
81
82
83
84
85
86
  }

  /**
   * Data provider for testFilterXssNormalized().
   *
   * @see testFilterXssNormalized()
   *
   * @return array
   *   An array of arrays containing strings:
   *     - The value to filter.
   *     - The value to expect after filtering.
   *     - The assertion message.
87
88
   *     - (optional) The allowed HTML HTML tags array that should be passed to
   *       \Drupal\Component\Utility\Xss::filter().
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
   */
  public function providerTestFilterXssNormalized() {
    return array(
      array(
        "Who&#039;s Online",
        "who's online",
        'HTML filter -- html entity number',
      ),
      array(
        "Who&amp;#039;s Online",
        "who&#039;s online",
        'HTML filter -- encoded html entity number',
      ),
      array(
        "Who&amp;amp;#039; Online",
        "who&amp;#039; online",
        'HTML filter -- double encoded html entity number',
      ),
107
108
109
110
111
112
113
      // Custom elements with dashes in the tag name.
      array(
        "<test-element></test-element>",
        "<test-element></test-element>",
        'Custom element with dashes in tag name.',
        array('test-element'),
      ),
114
115
116
117
    );
  }

  /**
118
   * Tests limiting to allowed tags and XSS prevention.
119
120
121
122
123
124
125
   *
   * XSS tests assume that script is disallowed by default and src is allowed
   * by default, but on* and style attributes are disallowed.
   *
   * @param string $value
   *   The value to filter.
   * @param string $expected
126
   *   The string that is expected to be missing.
127
128
129
   * @param string $message
   *   The assertion message to display upon failure.
   * @param array $allowed_tags
130
   *   (optional) The allowed HTML tags to be passed to \Drupal\Component\Utility\Xss::filter().
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
   *
   * @dataProvider providerTestFilterXssNotNormalized
   */
  public function testFilterXssNotNormalized($value, $expected, $message, array $allowed_tags = NULL) {
    if ($allowed_tags === NULL) {
      $value = Xss::filter($value);
    }
    else {
      $value = Xss::filter($value, $allowed_tags);
    }
    $this->assertNotNormalized($value, $expected, $message);
  }

  /**
   * Data provider for testFilterXssNotNormalized().
   *
   * @see testFilterXssNotNormalized()
   *
   * @return array
   *   An array of arrays containing the following elements:
151
152
153
154
   *     - The value to filter.
   *     - The value to expect that's missing after filtering.
   *     - The assertion message.
   *     - (optional) The allowed HTML HTML tags array that should be passed to
155
   *       \Drupal\Component\Utility\Xss::filter().
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
   */
  public function providerTestFilterXssNotNormalized() {
    $cases = array(
      // Tag stripping, different ways to work around removal of HTML tags.
      array(
        '<script>alert(0)</script>',
        'script',
        'HTML tag stripping -- simple script without special characters.',
      ),
      array(
        '<script src="http://www.example.com" />',
        'script',
        'HTML tag stripping -- empty script with source.',
      ),
      array(
        '<ScRipt sRc=http://www.example.com/>',
        'script',
        'HTML tag stripping evasion -- varying case.',
      ),
      array(
        "<script\nsrc\n=\nhttp://www.example.com/\n>",
        'script',
        'HTML tag stripping evasion -- multiline tag.',
      ),
      array(
        '<script/a src=http://www.example.com/a.js></script>',
        'script',
        'HTML tag stripping evasion -- non whitespace character after tag name.',
      ),
      array(
        '<script/src=http://www.example.com/a.js></script>',
        'script',
        'HTML tag stripping evasion -- no space between tag and attribute.',
      ),
      // Null between < and tag name works at least with IE6.
      array(
        "<\0scr\0ipt>alert(0)</script>",
        'ipt',
        'HTML tag stripping evasion -- breaking HTML with nulls.',
      ),
      array(
        "<scrscriptipt src=http://www.example.com/a.js>",
        'script',
        'HTML tag stripping evasion -- filter just removing "script".',
      ),
      array(
        '<<script>alert(0);//<</script>',
        'script',
        'HTML tag stripping evasion -- double opening brackets.',
      ),
      array(
        '<script src=http://www.example.com/a.js?<b>',
        'script',
        'HTML tag stripping evasion -- no closing tag.',
      ),
      // DRUPAL-SA-2008-047: This doesn't seem exploitable, but the filter should
      // work consistently.
      array(
        '<script>>',
        'script',
        'HTML tag stripping evasion -- double closing tag.',
      ),
      array(
        '<script src=//www.example.com/.a>',
        'script',
        'HTML tag stripping evasion -- no scheme or ending slash.',
      ),
      array(
        '<script src=http://www.example.com/.a',
        'script',
        'HTML tag stripping evasion -- no closing bracket.',
      ),
      array(
        '<script src=http://www.example.com/ <',
        'script',
        'HTML tag stripping evasion -- opening instead of closing bracket.',
      ),
      array(
        '<nosuchtag attribute="newScriptInjectionVector">',
        'nosuchtag',
        'HTML tag stripping evasion -- unknown tag.',
      ),
      array(
        '<t:set attributeName="innerHTML" to="&lt;script defer&gt;alert(0)&lt;/script&gt;">',
        't:set',
        'HTML tag stripping evasion -- colon in the tag name (namespaces\' tricks).',
      ),
      array(
        '<img """><script>alert(0)</script>',
        'script',
        'HTML tag stripping evasion -- a malformed image tag.',
        array('img'),
      ),
      array(
        '<blockquote><script>alert(0)</script></blockquote>',
        'script',
        'HTML tag stripping evasion -- script in a blockqoute.',
        array('blockquote'),
      ),
      array(
        "<!--[if true]><script>alert(0)</script><![endif]-->",
        'script',
        'HTML tag stripping evasion -- script within a comment.',
      ),
      // Dangerous attributes removal.
      array(
        '<p onmouseover="http://www.example.com/">',
        'onmouseover',
        'HTML filter attributes removal -- events, no evasion.',
        array('p'),
      ),
      array(
        '<li style="list-style-image: url(javascript:alert(0))">',
        'style',
        'HTML filter attributes removal -- style, no evasion.',
        array('li'),
      ),
      array(
        '<img onerror   =alert(0)>',
        'onerror',
        'HTML filter attributes removal evasion -- spaces before equals sign.',
        array('img'),
      ),
      array(
        '<img onabort!#$%&()*~+-_.,:;?@[/|\]^`=alert(0)>',
        'onabort',
        'HTML filter attributes removal evasion -- non alphanumeric characters before equals sign.',
        array('img'),
      ),
      array(
        '<img oNmediAError=alert(0)>',
        'onmediaerror',
        'HTML filter attributes removal evasion -- varying case.',
        array('img'),
      ),
      // Works at least with IE6.
      array(
        "<img o\0nfocus\0=alert(0)>",
        'focus',
        'HTML filter attributes removal evasion -- breaking with nulls.',
        array('img'),
      ),
      // Only whitelisted scheme names allowed in attributes.
      array(
        '<img src="javascript:alert(0)">',
        'javascript',
        'HTML scheme clearing -- no evasion.',
        array('img'),
      ),
      array(
        '<img src=javascript:alert(0)>',
        'javascript',
        'HTML scheme clearing evasion -- no quotes.',
        array('img'),
      ),
      // A bit like CVE-2006-0070.
      array(
        '<img src="javascript:confirm(0)">',
        'javascript',
        'HTML scheme clearing evasion -- no alert ;)',
        array('img'),
      ),
      array(
        '<img src=`javascript:alert(0)`>',
        'javascript',
        'HTML scheme clearing evasion -- grave accents.',
        array('img'),
      ),
      array(
        '<img dynsrc="javascript:alert(0)">',
        'javascript',
        'HTML scheme clearing -- rare attribute.',
        array('img'),
      ),
      array(
        '<table background="javascript:alert(0)">',
        'javascript',
        'HTML scheme clearing -- another tag.',
        array('table'),
      ),
      array(
        '<base href="javascript:alert(0);//">',
        'javascript',
        'HTML scheme clearing -- one more attribute and tag.',
        array('base'),
      ),
      array(
        '<img src="jaVaSCriPt:alert(0)">',
        'javascript',
        'HTML scheme clearing evasion -- varying case.',
        array('img'),
      ),
      array(
        '<img src=&#106;&#97;&#118;&#97;&#115;&#99;&#114;&#105;&#112;&#116;&#58;&#97;&#108;&#101;&#114;&#116;&#40;&#48;&#41;>',
        'javascript',
        'HTML scheme clearing evasion -- UTF-8 decimal encoding.',
        array('img'),
      ),
      array(
        '<img src=&#00000106&#0000097&#00000118&#0000097&#00000115&#0000099&#00000114&#00000105&#00000112&#00000116&#0000058&#0000097&#00000108&#00000101&#00000114&#00000116&#0000040&#0000048&#0000041>',
        'javascript',
        'HTML scheme clearing evasion -- long UTF-8 encoding.',
        array('img'),
      ),
      array(
        '<img src=&#x6A&#x61&#x76&#x61&#x73&#x63&#x72&#x69&#x70&#x74&#x3A&#x61&#x6C&#x65&#x72&#x74&#x28&#x30&#x29>',
        'javascript',
        'HTML scheme clearing evasion -- UTF-8 hex encoding.',
        array('img'),
      ),
      array(
        "<img src=\"jav\tascript:alert(0)\">",
        'script',
        'HTML scheme clearing evasion -- an embedded tab.',
        array('img'),
      ),
      array(
        '<img src="jav&#x09;ascript:alert(0)">',
        'script',
        'HTML scheme clearing evasion -- an encoded, embedded tab.',
        array('img'),
      ),
      array(
        '<img src="jav&#x000000A;ascript:alert(0)">',
        'script',
        'HTML scheme clearing evasion -- an encoded, embedded newline.',
        array('img'),
      ),
      // With &#xD; this test would fail, but the entity gets turned into
      // &amp;#xD;, so it's OK.
      array(
        '<img src="jav&#x0D;ascript:alert(0)">',
        'script',
        'HTML scheme clearing evasion -- an encoded, embedded carriage return.',
        array('img'),
      ),
      array(
        "<img src=\"\n\n\nj\na\nva\ns\ncript:alert(0)\">",
        'cript',
        'HTML scheme clearing evasion -- broken into many lines.',
        array('img'),
      ),
      array(
        "<img src=\"jav\0a\0\0cript:alert(0)\">",
        'cript',
        'HTML scheme clearing evasion -- embedded nulls.',
        array('img'),
      ),
      array(
        '<img src="vbscript:msgbox(0)">',
        'vbscript',
        'HTML scheme clearing evasion -- another scheme.',
        array('img'),
      ),
      array(
        '<img src="nosuchscheme:notice(0)">',
        'nosuchscheme',
        'HTML scheme clearing evasion -- unknown scheme.',
        array('img'),
      ),
      // Netscape 4.x javascript entities.
      array(
        '<br size="&{alert(0)}">',
        'alert',
        'Netscape 4.x javascript entities.',
        array('br'),
      ),
      // DRUPAL-SA-2008-006: Invalid UTF-8, these only work as reflected XSS with
      // Internet Explorer 6.
      array(
        "<p arg=\"\xe0\">\" style=\"background-image: url(javascript:alert(0));\"\xe0<p>",
        'style',
        'HTML filter -- invalid UTF-8.',
        array('p'),
      ),
    );
    // @fixme This dataset currently fails under 5.4 because of
    //   https://drupal.org/node/1210798 . Restore after its fixed.
    if (version_compare(PHP_VERSION, '5.4.0', '<')) {
      $cases[] = array(
        '<img src=" &#14;  javascript:alert(0)">',
        'javascript',
        'HTML scheme clearing evasion -- spaces and metacharacters before scheme.',
        array('img'),
      );
    }
    return $cases;
  }

  /**
   * Checks that invalid multi-byte sequences are rejected.
   *
   * @param string $value
   *   The value to filter.
   * @param string $expected
   *   The expected result.
   * @param string $message
   *   The assertion message to display upon failure.
   *
   * @dataProvider providerTestInvalidMultiByte
   */
  public function testInvalidMultiByte($value, $expected, $message) {
    $this->assertEquals(Xss::filter($value), $expected, $message);
  }

  /**
   * Data provider for testInvalidMultiByte().
   *
   * @see testInvalidMultiByte()
   *
   * @return array
   *   An array of arrays containing strings:
   *     - The value to filter.
   *     - The value to expect after filtering.
   *     - The assertion message.
   */
  public function providerTestInvalidMultiByte() {
    return array(
      array("Foo\xC0barbaz", '', 'Xss::filter() accepted invalid sequence "Foo\xC0barbaz"'),
      array("Fooÿñ", "Fooÿñ", 'Xss::filter() rejects valid sequence Fooÿñ"'),
      array("\xc0aaa", '', 'HTML filter -- overlong UTF-8 sequences.'),
    );
  }

  /**
   * Checks that strings starting with a question sign are correctly processed.
   */
  public function testQuestionSign() {
    $value = Xss::filter('<?xml:namespace ns="urn:schemas-microsoft-com:time">');
    $this->assertTrue(stripos($value, '<?xml') === FALSE, 'HTML tag stripping evasion -- starting with a question sign (processing instructions).');
  }

  /**
489
   * Checks that \Drupal\Component\Utility\Xss::filterAdmin() correctly strips unallowed tags.
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
   */
  public function testFilterXSSAdmin() {
    $value = Xss::filterAdmin('<style /><iframe /><frame /><frameset /><meta /><link /><embed /><applet /><param /><layer />');
    $this->assertEquals($value, '', 'Admin HTML filter -- should never allow some tags.');
  }

  /**
   * Tests the loose, admin HTML filter.
   *
   * @param string $value
   *   The value to filter.
   * @param string $expected
   *   The expected result.
   * @param string $message
   *   The assertion message to display upon failure.
   *
   * @dataProvider providerTestFilterXssAdminNotNormalized
   */
  public function testFilterXssAdminNotNormalized($value, $expected, $message) {
    $this->assertNotNormalized(Xss::filterAdmin($value), $expected, $message);
  }

  /**
   * Data provider for testFilterXssAdminNotNormalized().
   *
   * @see testFilterXssAdminNotNormalized()
   *
   * @return array
   *   An array of arrays containing strings:
   *     - The value to filter.
   *     - The value to expect after filtering.
   *     - The assertion message.
   */
  public function providerTestFilterXssAdminNotNormalized() {
    return array(
      // DRUPAL-SA-2008-044
      array('<object />', 'object', 'Admin HTML filter -- should not allow object tag.'),
      array('<script />', 'script', 'Admin HTML filter -- should not allow script tag.'),
    );
  }

  /**
532
   * Asserts that a text transformed to lowercase with HTML entities decoded does contain a given string.
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
   *
   * Otherwise fails the test with a given message, similar to all the
   * SimpleTest assert* functions.
   *
   * Note that this does not remove nulls, new lines and other characters that
   * could be used to obscure a tag or an attribute name.
   *
   * @param string $haystack
   *   Text to look in.
   * @param string $needle
   *   Lowercase, plain text to look for.
   * @param string $message
   *   (optional) Message to display if failed. Defaults to an empty string.
   * @param string $group
   *   (optional) The group this message belongs to. Defaults to 'Other'.
   */
  protected function assertNormalized($haystack, $needle, $message = '', $group = 'Other') {
    $this->assertTrue(strpos(strtolower(String::decodeEntities($haystack)), $needle) !== FALSE, $message, $group);
  }

  /**
   * Asserts that text transformed to lowercase with HTML entities decoded does not contain a given string.
   *
   * Otherwise fails the test with a given message, similar to all the
   * SimpleTest assert* functions.
   *
   * Note that this does not remove nulls, new lines, and other character that
   * could be used to obscure a tag or an attribute name.
   *
   * @param string $haystack
   *   Text to look in.
   * @param string $needle
   *   Lowercase, plain text to look for.
   * @param string $message
   *   (optional) Message to display if failed. Defaults to an empty string.
   * @param string $group
   *   (optional) The group this message belongs to. Defaults to 'Other'.
   */
  protected function assertNotNormalized($haystack, $needle, $message = '', $group = 'Other') {
    $this->assertTrue(strpos(strtolower(String::decodeEntities($haystack)), $needle) === FALSE, $message, $group);
  }

}