File size: 39,178 Bytes
4d2a9bf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
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
489
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
532
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
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
diff --git a/src/Core/XssSanitiser.php b/src/Core/XssSanitiser.php
new file mode 100644
index 00000000000..5ffdb224b95
--- /dev/null
+++ b/src/Core/XssSanitiser.php
@@ -0,0 +1,213 @@
+<?php
+
+namespace SilverStripe\Core;
+
+use DOMAttr;
+use DOMElement;
+use SilverStripe\Core\Injector\Injectable;
+use SilverStripe\View\Parsers\HTMLValue;
+
+/**
+ * Sanitises HTML to prevent XSS attacks.
+ */
+class XssSanitiser
+{
+    use Injectable;
+
+    /**
+     * Attributes which will be removed from any element.
+     * If an asterisk is at the start of the attribute name, all attributes ending with this name will be removed.
+     * If an asterisk is at the end of the attribute name, all attributes starting with this name will be removed.
+     * For example `on*` will remove `onerror`, `onmouseover`, etc
+     */
+    private array $attributesToRemove = [
+        'on*',
+        'accesskey',
+    ];
+
+    private array $elementsToRemove = [
+        'embed',
+        'object',
+        'script',
+        'style',
+        'svg',
+    ];
+
+    private bool $keepInnerHtmlOnRemoveElement = true;
+
+    private bool $removeDataSvg = true;
+
+    private bool $removeSvgFile = true;
+
+    /**
+     * Remove XSS attack vectors from an HTML fragment string
+     */
+    public function sanitiseString(string $html): string
+    {
+        $htmlValue = HTMLValue::create($html);
+        $this->sanitiseHtmlValue($htmlValue);
+        return $htmlValue->getContent();
+    }
+
+    /**
+     * Remove XSS attack vectors from HTMLValue content
+     */
+    public function sanitiseHtmlValue(HTMLValue $html): void
+    {
+        foreach ($html->query('//*') as $element) {
+            if (!is_a($element, DOMElement::class)) {
+                continue;
+            }
+            $this->sanitiseElement($element);
+        }
+    }
+
+    /**
+     * Remove XSS attack vectors from a DOMElement
+     */
+    public function sanitiseElement(DOMElement $element): void
+    {
+        // Remove elements first - if we remove the element, we don't have any attributes to check so exit early
+        $removed = $this->stripElement($element);
+        if ($removed) {
+            return;
+        }
+        $this->stripAttributes($element);
+        $this->stripAttributeContents($element);
+    }
+
+    /**
+     * Get the names of elements which will be removed.
+     */
+    public function getElementsToRemove(): array
+    {
+        return $this->elementsToRemove;
+    }
+
+    /**
+     * Set the names of elements which will be removed.
+     * Note that allowing the elements which are included in the default list could result in XSS vulnerabilities.
+     */
+    public function setElementsToRemove(array $elements): static
+    {
+        $this->elementsToRemove = $elements;
+        return $this;
+    }
+
+    /**
+     * Get the names of attributes which will be removed from any elements that have them.
+     */
+    public function getAttributesToRemove(): array
+    {
+        return $this->attributesToRemove;
+    }
+
+    /**
+     * Set the names of attributes which will be removed from any elements that have them.
+     * Note that allowing the attributes which are included in the default list could result in XSS vulnerabilities.
+     */
+    public function setAttributesToRemove(array $attributes): static
+    {
+        $this->attributesToRemove = $attributes;
+        return $this;
+    }
+
+    /**
+     * Get whether the inner contents of an element will be kept for elements that get removed.
+     */
+    public function getKeepInnerHtmlOnRemoveElement(): bool
+    {
+        return $this->keepInnerHtmlOnRemoveElement;
+    }
+
+    /**
+     * Set whether to keep the inner contents of an element if it gets removed.
+     */
+    public function setKeepInnerHtmlOnRemoveElement(bool $keep): static
+    {
+        $this->keepInnerHtmlOnRemoveElement = $keep;
+        return $this;
+    }
+
+    /**
+     * If $element is one of the elements in $elementsToRemove, replace it
+     * with a text node.
+     */
+    private function stripElement(DOMElement $element): bool
+    {
+        if (!in_array($element->tagName, $this->getElementsToRemove())) {
+            return false;
+        }
+        // Make sure we don't remove any child nodes
+        $parentNode = $element->parentNode;
+        if ($this->getKeepInnerHtmlOnRemoveElement() && $parentNode && $element->hasChildNodes()) {
+            // We can't just iterate through $node->childNodes because that seems to skip some children
+            while ($element->hasChildNodes()) {
+                $parentNode->insertBefore($element->firstChild, $element);
+            }
+        }
+        $element->remove();
+        return true;
+    }
+
+    /**
+     * Remove all attributes in $attributesToRemove from the element.
+     */
+    private function stripAttributes(DOMElement $element): void
+    {
+        $attributesToRemove = $this->getAttributesToRemove();
+        if (empty($attributesToRemove)) {
+            return;
+        }
+        $attributes = $element->attributes;
+        for ($i = count($attributes) - 1; $i >= 0; $i--) {
+            /** @var DOMAttr $attr */
+            $attr = $attributes->item($i);
+            foreach ($attributesToRemove as $toRemove) {
+                if (str_starts_with($toRemove, '*') && str_ends_with($attr->name, str_replace('*', '', $toRemove))) {
+                    $element->removeAttributeNode($attr);
+                } elseif (str_ends_with($toRemove, '*') && str_starts_with($attr->name, str_replace('*', '', $toRemove))) {
+                    $element->removeAttributeNode($attr);
+                } elseif (!str_contains($toRemove, '*') && $attr->name === $toRemove) {
+                    $element->removeAttributeNode($attr);
+                }
+            }
+        }
+    }
+
+    /**
+     * Strip out attributes which have dangerous content which might otherwise execute javascript.
+     * This is content that we will always remove regardless of whether the attributes and elements in question
+     * are otherwise allowed, e.g. via WYSIWYG configuration.
+     */
+    private function stripAttributeContents(DOMElement $element): void
+    {
+        $regex = $this->getStripAttributeContentsRegex();
+        foreach (['lowsrc', 'src', 'href', 'data'] as $dangerAttribute) {
+            if ($element->hasAttribute($dangerAttribute)) {
+                $attrContent = $element->getAttribute($dangerAttribute);
+                if (preg_match($regex, $attrContent)) {
+                    $element->removeAttribute($dangerAttribute);
+                }
+            }
+        }
+    }
+
+    private function getStripAttributeContentsRegex(): string
+    {
+        $regexes = [
+            $this->splitWithWhitespaceRegex('javascript:'),
+            $this->splitWithWhitespaceRegex('data:text/html'),
+            $this->splitWithWhitespaceRegex('vbscript:'),
+        ];
+        // Regex is "starts with any of these, with optional whitespace at the start, case insensitive"
+        return '#^\s*(' . implode('|', $regexes) . ')#iu';
+    }
+
+    private function splitWithWhitespaceRegex(string $string): string
+    {
+        // Note that `\s` explicitly includes ALL invisible characters when used with the `u` modifier.
+        // That includes unicode characters like the non-breaking space.
+        return implode('\s*', str_split($string));
+    }
+}
diff --git a/src/Forms/FormMessage.php b/src/Forms/FormMessage.php
index ce18ee153a6..8a6d85b74a3 100644
--- a/src/Forms/FormMessage.php
+++ b/src/Forms/FormMessage.php
@@ -3,6 +3,7 @@
 namespace SilverStripe\Forms;
 
 use InvalidArgumentException;
+use SilverStripe\Core\XssSanitiser;
 use SilverStripe\ORM\ValidationResult;
 use SilverStripe\View\ViewableData;
 
@@ -33,6 +34,7 @@ trait FormMessage
 
     /**
      * Returns the field message, used by form validation.
+     * If the current cast is ValidationResult::CAST_HTML, the message will be sanitised.
      *
      * Use {@link setError()} to set this property.
      *
@@ -40,7 +42,11 @@ trait FormMessage
      */
     public function getMessage()
     {
-        return $this->message;
+        $message = $this->message;
+        if ($this->getMessageCast() === ValidationResult::CAST_HTML) {
+            $message = XssSanitiser::create()->sanitiseString($message);
+        }
+        return $message;
     }
 
     /**
diff --git a/src/Forms/HTMLEditor/HTMLEditorSanitiser.php b/src/Forms/HTMLEditor/HTMLEditorSanitiser.php
index c056bca10f3..49eda400afa 100644
--- a/src/Forms/HTMLEditor/HTMLEditorSanitiser.php
+++ b/src/Forms/HTMLEditor/HTMLEditorSanitiser.php
@@ -6,6 +6,7 @@
 use DOMElement;
 use SilverStripe\Core\Config\Configurable;
 use SilverStripe\Core\Injector\Injectable;
+use SilverStripe\Core\XssSanitiser;
 use SilverStripe\View\Parsers\HTMLValue;
 use stdClass;
 
@@ -289,6 +290,10 @@ public function sanitise(HTMLValue $html)
     {
         $linkRelValue = $this->config()->get('link_rel_value');
         $doc = $html->getDocument();
+        // Get a sanitiser but don't deny any specific attributes or elements, since that's
+        // handled as part of the element rules.
+        $xssSanitiser = XssSanitiser::create();
+        $xssSanitiser->setElementsToRemove([])->setAttributesToRemove([]);
 
         /** @var DOMElement $el */
         foreach ($html->query('//body//*') as $el) {
@@ -342,16 +347,8 @@ public function sanitise(HTMLValue $html)
                     $el->setAttribute($attr, $forced);
                 }
 
-                // Matches "javascript:" with any arbitrary linebreaks inbetween the characters.
-                $regex = '#^\s*(' . implode('\s*', str_split('javascript:')) . '|' . implode('\s*', str_split('data:text/html;')) . ')#i';
-                // Strip out javascript execution in href or src attributes.
-                foreach (['src', 'href', 'data'] as $dangerAttribute) {
-                    if ($el->hasAttribute($dangerAttribute)) {
-                        if (preg_match($regex, $el->getAttribute($dangerAttribute))) {
-                            $el->removeAttribute($dangerAttribute);
-                        }
-                    }
-                }
+                // Explicit XSS sanitisation for anything that there's really no sensible use case for in a WYSIWYG
+                $xssSanitiser->sanitiseElement($el);
             }
 
             if ($el->tagName === 'a' && $linkRelValue !== null) {
diff --git a/tests/php/Core/XssSanitiserTest.php b/tests/php/Core/XssSanitiserTest.php
new file mode 100644
index 00000000000..0d1ef959447
--- /dev/null
+++ b/tests/php/Core/XssSanitiserTest.php
@@ -0,0 +1,463 @@
+<?php
+
+namespace SilverStripe\Core\Tests;
+
+use DOMElement;
+use SilverStripe\Core\XssSanitiser;
+use SilverStripe\Dev\SapphireTest;
+use SilverStripe\View\Parsers\HTMLValue;
+
+class XssSanitiserTest extends SapphireTest
+{
+    protected $usesDatabase = false;
+
+    public function provideSanitise(): array
+    {
+        // Most of these scenarios are inspired by Symfony's HtmlSanitizerAllTest scenarios
+        return [
+            // Text
+            [
+                'input' => '',
+                'expected' => '',
+            ],
+            [
+                'input' => 'hello world',
+                'expected' => 'hello world',
+            ],
+            [
+                'input' => '&lt;hello world&gt;',
+                'expected' => '&lt;hello world&gt;',
+            ],
+            [
+                'input' => '< Hello',
+                'expected' => ' Hello',
+            ],
+            [
+                'input' => 'Lorem & Ipsum',
+                'expected' => 'Lorem &amp; Ipsum',
+            ],
+            // Unknown tag
+            [
+                'input' => '<unknown>Lorem ipsum</unknown>',
+                'expected' => '<unknown>Lorem ipsum</unknown>',
+            ],
+            // Scripts
+            [
+                'input' => '<script>alert(\'ok\');</script>',
+                'expected' => 'alert(\'ok\');',
+            ],
+            [
+                'input' => 'javascript:/*--></title></style></textarea></script></xmp><svg/onload=\'+/"/+/onmouseover=1/+/[*/[]/+alert(1)//\'>',
+                'expected' => 'javascript:/*--&gt;',
+            ],
+            [
+                // Not exploitable XSS
+                'input' => '<scr<script>ipt>alert(1)</script>',
+                'expected' => '<scr>ipt&gt;alert(1)</scr>',
+            ],
+            [
+                // Not exploitable XSS
+                'input' => '<scr<a>ipt>alert(1)</script>',
+                'expected' => '<scr><a>ipt&gt;alert(1)</a></scr>',
+            ],
+            [
+                // Not exploitable XSS
+                'input' => '<noscript>Lorem ipsum</noscript>',
+                'expected' => '<noscript>Lorem ipsum</noscript>',
+            ],
+            [
+                'input' => '<div>Lorem ipsum dolor sit amet, consectetur adipisicing elit.<script>alert(\'ok\');</script></div>',
+                'expected' => '<div>Lorem ipsum dolor sit amet, consectetur adipisicing elit.alert(\'ok\');</div>',
+            ],
+            [
+                'input' => '<a href="javascript:alert(\'ok\')">Lorem ipsum dolor sit amet, consectetur adipisicing elit.</a>',
+                'expected' => '<a>Lorem ipsum dolor sit amet, consectetur adipisicing elit.</a>',
+            ],
+            [
+                // Not exploitable XSS
+                'input' => '<<a href="javascript:evil"/>a href="javascript:evil"/>',
+                'expected' => '<a>a href="javascript:evil"/&gt;</a>',
+            ],
+            [
+                'input' => '<a href="javascript:alert(\'ok\')">Test</a>',
+                'expected' => '<a>Test</a>',
+            ],
+            [
+                'input' => '<a href="javascript://%0Aalert(document.cookie)">Test</a>',
+                'expected' => '<a>Test</a>',
+            ],
+            [
+                'input' => '<a href="&#106;&#97;&#118;&#97;&#115;&#99;&#114;&#105;&#112;&#116;&#58;&#97;&#108;&#101;&#114;&#116;&#40;&#39;&#88;&#83;&#83;&#39;&#41;">Lorem ipsum</a>',
+                'expected' => '<a>Lorem ipsum</a>',
+            ],
+            [
+                // Note this includes U+200A, U+202F, U+205F, U+2000, U+2001, U+2002, U+2003, U+2004, U+2005, U+2006, U+2007, U+2008, U+2009, U+3000
+                'input' => "<a href=\"ja\tva\v\r\n sc     r i        pt:alert('foo')\">Lorem ipsum</a>",
+                'expected' => '<a>Lorem ipsum</a>',
+            ],
+            [
+                // Not exploitable XSS
+                'input' => '<a href= onmouseover="alert(\\\'XSS\\\');">Lorem ipsum</a>',
+                'expected' => '<a href="onmouseover=&quot;alert(\&#039;XSS\&#039;);&quot;">Lorem ipsum</a>',
+            ],
+            [
+                'input' => '<a href="http://example.com" onclick="alert(\'ok\')">Test</a>',
+                'expected' => '<a href="http://example.com">Test</a>',
+            ],
+            [
+                'input' => '<a href="javascript:" title="Link title">Lorem ipsum</a>',
+                'expected' => '<a title="Link title">Lorem ipsum</a>',
+            ],
+            [
+                // Not exploitable XSS
+                'input' => '<figure><img src="https://example.com/img/example.jpg" onclick="alert(\'ok\')" /></figure>',
+                'expected' => '<figure><img src="https://example.com/img/example.jpg"></figure>',
+            ],
+            [
+                // Not exploitable XSS
+                'input' => '<img src= onmouseover="alert(\'XSS\');">',
+                'expected' => '<img src="onmouseover=&quot;alert(&#039;XSS&#039;);&quot;">',
+            ],
+            [
+                // Not exploitable XSS
+                'input' => '<<img src="javascript:evil"/>iframe src="javascript:evil"/>',
+                'expected' => '<img>iframe src="javascript:evil"/&gt;',
+            ],
+            [
+                // Not exploitable XSS
+                'input' => '<<img src="javascript:evil"/>img src="javascript:evil"/>',
+                'expected' => '<img>img src="javascript:evil"/&gt;',
+            ],
+            [
+                'input' => '<IMG SRC="javascript:alert(\'XSS\');">',
+                'expected' => '<img>',
+            ],
+            [
+                'input' => '<IMG SRC=javascript:alert(\'XSS\')>',
+                'expected' => '<img>',
+            ],
+            [
+                'input' => '<IMG SRC=JaVaScRiPt:alert(\'XSS\')>',
+                'expected' => '<img>',
+            ],
+            [
+                'input' => '<IMG SRC=javascript:alert(&quot;XSS&quot;)>',
+                'expected' => '<img>',
+            ],
+            [
+                // Not exploitable XSS
+                'input' => '<IMG SRC=`javascript:alert("RSnake says, \'XSS\'")`>',
+                'expected' => '<img src="`javascript:alert(&quot;RSnake">',
+            ],
+            [
+                'input' => '<IMG """><SCRIPT>alert("XSS")</SCRIPT>"\>',
+                'expected' => '<img>alert("XSS")"\&gt;',
+            ],
+            [
+                'input' => '<IMG SRC=javascript:alert(String.fromCharCode(88,83,83))>',
+                'expected' => '<img>',
+            ],
+            [
+                'input' => '<IMG SRC=# onmouseover="alert(\'xxs\')">',
+                'expected' => '<img src="#">',
+            ],
+            [
+                'input' => '<img src=x onerror="&#0000106&#0000097&#0000118&#0000097&#0000115&#0000099&#0000114&#0000105&#0000112&#0000116&#0000058&#0000097&#0000108&#0000101&#0000114&#0000116&#0000040&#0000039&#0000088&#0000083&#0000083&#0000039&#0000041">',
+                'expected' => '<img src="x">',
+            ],
+            [
+                // decodes to `javascript:alert('XSS')`
+                'input' => '<IMG SRC=&#106;&#97;&#118;&#97;&#115;&#99;&#114;&#105;&#112;&#116;&#58;&#97;&#108;&#101;&#114;&#116;&#40;&#39;&#88;&#83;&#83;&#39;&#41;>',
+                'expected' => '<img>',
+            ],
+            [
+                // Not exploitable XSS
+                'input' => '<IMG SRC=&#0000106&#0000097&#0000118&#0000097&#0000115&#0000099&#0000114&#0000105&#0000112&#0000116&#0000058&#0000097&#0000108&#0000101&#0000114&#0000116&#0000040&#0000039&#0000088&#0000083&#0000083&#0000039&#0000041>',
+                'expected' => '<img src="&amp;#0000106&amp;#0000097&amp;#0000118&amp;#0000097&amp;#0000115&amp;#0000099&amp;#0000114&amp;#0000105&amp;#0000112&amp;#0000116&amp;#0000058&amp;#0000097&amp;#0000108&amp;#0000101&amp;#0000114&amp;#0000116&amp;#0000040&amp;#0000039&amp;#0000088&amp;#0000083&amp;#0000083&amp;#0000039&amp;#0000041">',
+            ],
+            [
+                // Not exploitable XSS
+                'input' => '<IMG SRC=&#x6A&#x61&#x76&#x61&#x73&#x63&#x72&#x69&#x70&#x74&#x3A&#x61&#x6C&#x65&#x72&#x74&#x28&#x27&#x58&#x53&#x53&#x27&#x29>',
+                'expected' => '<img src="&amp;#x6A&amp;#x61&amp;#x76&amp;#x61&amp;#x73&amp;#x63&amp;#x72&amp;#x69&amp;#x70&amp;#x74&amp;#x3A&amp;#x61&amp;#x6C&amp;#x65&amp;#x72&amp;#x74&amp;#x28&amp;#x27&amp;#x58&amp;#x53&amp;#x53&amp;#x27&amp;#x29">',
+            ],
+            [
+                // Decodes to a SVG with `<script type="text/ecmascript">alert("XSS");</script>` inside it
+                // But that's not actually exploitable XSS
+                'input' => '<IMG SRC="data:image/svg+xml;base64,PHN2ZyB4bWxuczpzdmc9Imh0dH A6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcv MjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hs aW5rIiB2ZXJzaW9uPSIxLjAiIHg9IjAiIHk9IjAiIHdpZHRoPSIxOTQiIGhlaWdodD0iMjAw IiBpZD0ieHNzIj48c2NyaXB0IHR5cGU9InRleHQvZWNtYXNjcmlwdCI+YWxlcnQoIlh TUyIpOzwvc2NyaXB0Pjwvc3ZnPg==">',
+                'expected' => '<img src="data:image/svg+xml;base64,PHN2ZyB4bWxuczpzdmc9Imh0dH A6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcv MjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hs aW5rIiB2ZXJzaW9uPSIxLjAiIHg9IjAiIHk9IjAiIHdpZHRoPSIxOTQiIGhlaWdodD0iMjAw IiBpZD0ieHNzIj48c2NyaXB0IHR5cGU9InRleHQvZWNtYXNjcmlwdCI+YWxlcnQoIlh TUyIpOzwvc2NyaXB0Pjwvc3ZnPg==">',
+            ],
+            [
+                'input' => '<IMG LOWSRC="javascript:alert(\'XSS\')">',
+                'expected' => '<img>',
+            ],
+            [
+                'input' => '<IMG SRC=\'vbscript:msgbox(\"XSS")\'>',
+                'expected' => '<img>',
+            ],
+            [
+                'input' => '<img src="javascript:" alt="Image alternative text" title="Image title">',
+                'expected' => '<img alt="Image alternative text" title="Image title">',
+            ],
+            [
+                'input' => '<svg/onload=alert(\'XSS\')>',
+                'expected' => '',
+            ],
+            [
+                'input' => '<BGSOUND SRC="javascript:alert(\'XSS\');">',
+                'expected' => '<bgsound></bgsound>',
+            ],
+            [
+                // Not exploitable XSS
+                'input' => '<BR SIZE="&{alert(\'XSS\')}">',
+                'expected' => '<br size="&amp;{alert(&#039;XSS&#039;)}">',
+            ],
+            [
+                'input' => '<BR></br>',
+                'expected' => '<br><br>',
+            ],
+
+            [
+                'input' => '<OBJECT TYPE="text/x-scriptlet" DATA="http://xss.rocks/scriptlet.html"></OBJECT>',
+                'expected' => '',
+            ],
+            [
+                // Decodes to a SVG with `<script type="text/ecmascript">alert("XSS");</script>` inside it
+                'input' => '<EMBED SRC="data:image/svg+xml;base64,PHN2ZyB4bWxuczpzdmc9Imh0dH A6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcv MjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hs aW5rIiB2ZXJzaW9uPSIxLjAiIHg9IjAiIHk9IjAiIHdpZHRoPSIxOTQiIGhlaWdodD0iMjAw IiBpZD0ieHNzIj48c2NyaXB0IHR5cGU9InRleHQvZWNtYXNjcmlwdCI+YWxlcnQoIlh TUyIpOzwvc2NyaXB0Pjwvc3ZnPg==" type="image/svg+xml" AllowScriptAccess="always"></EMBED>',
+                'expected' => '',
+            ],
+            [
+                // Not exploitable XSS
+                'input' => '!<textarea>&lt;/textarea&gt;&lt;svg/onload=prompt`xs`&gt;</textarea>!',
+                'expected' => '!<textarea>&lt;/textarea&gt;&lt;svg/onload=prompt`xs`&gt;</textarea>!',
+            ],
+            [
+                'input' => '!<textarea></textarea><svg/onload=prompt`xs`></textarea>!',
+                'expected' => '!<textarea></textarea>!',
+            ],
+            [
+                'input' => '"><svg/onload=confirm(1)>"@x.y',
+                'expected' => '"&gt;"@x.y',
+            ],
+            [
+                'input' => '<div class="some-class"><img src="https://example.com/image.jpg"><span id="something025">one</span><script>2</script>two<span id="something026">three</span></div>',
+                'expected' => '<div class="some-class"><img src="https://example.com/image.jpg"><span id="something025">one</span>2two<span id="something026">three</span></div>',
+            ],
+            // Styles
+            [
+                'input' => '<style>body { background: red; }</style>',
+                'expected' => 'body { background: red; }',
+            ],
+            [
+                'input' => '<div>Lorem ipsum dolor sit amet, consectetur.<style>body { background: red; }</style></div>',
+                'expected' => '<div>Lorem ipsum dolor sit amet, consectetur.body { background: red; }</div>',
+            ],
+            [
+                'input' => '<img src="https://example.com/img/example.jpg" style="position:absolute;top:0;left:0;width:9000px;height:9000px;">',
+                'expected' => '<img src="https://example.com/img/example.jpg" style="position:absolute;top:0;left:0;width:9000px;height:9000px;">',
+            ],
+            [
+                'input' => '<a style="font-size: 40px; color: red;">Lorem ipsum dolor sit amet, consectetur.</a>',
+                'expected' => '<a style="font-size: 40px; color: red;">Lorem ipsum dolor sit amet, consectetur.</a>',
+            ],
+            // Comments
+            [
+                // Not exploitable XSS
+                'input' => 'Lorem ipsum dolor sit amet, consectetur<!--if[true]> <script>alert(1337)</script> -->',
+                'expected' => 'Lorem ipsum dolor sit amet, consectetur<!--if[true]> <script>alert(1337)</script> -->',
+            ],
+            [
+                'input' => 'Lorem ipsum<![CDATA[ <!-- ]]> <script>alert(1337)</script> <!-- -->',
+                'expected' => 'Lorem ipsum <!--  alert(1337) <!-- -->',
+            ],
+            // Normal tags (just checking they don't get mangled)
+            [
+                'input' => '<a>Lorem ipsum</a>',
+                'expected' => '<a>Lorem ipsum</a>',
+            ],
+            [
+                'input' => '<a href="/img/example.jpg" title="Link title">Lorem ipsum</a>',
+                'expected' => '<a href="/img/example.jpg" title="Link title">Lorem ipsum</a>',
+            ],
+            [
+                'input' => '<a href="http://example.com/index.html#this:stuff">Lorem ipsum</a>',
+                'expected' => '<a href="http://example.com/index.html#this:stuff">Lorem ipsum</a>',
+            ],
+            [
+                'input' => '<a href="mailto:test@example.com" title="Link title">Lorem ipsum</a>',
+                'expected' => '<a href="mailto:test@example.com" title="Link title">Lorem ipsum</a>',
+            ],
+            [
+                'input' => '<img src="/img/example.jpg" onanything="" alt="Image alternative text" title="Image title" height="150" width="300">',
+                'expected' => '<img src="/img/example.jpg" alt="Image alternative text" title="Image title" height="150" width="300">',
+            ],
+            [
+                'input' => '<img src="http://example.com/img/examp:le.jpg" alt="Image alternative text" title="Image title">',
+                'expected' => '<img src="http://example.com/img/examp:le.jpg" alt="Image alternative text" title="Image title">',
+            ],
+            [
+                'input' => '<img>',
+                'expected' => '<img>',
+            ],
+            [
+                'input' => '<div class="some-class"><img src="https://example.com/image.jpg"><span id="something025">one</span>two<span id="something026">three</span></div>',
+                'expected' => '<div class="some-class"><img src="https://example.com/image.jpg"><span id="something025">one</span>two<span id="something026">three</span></div>',
+            ],
+        ];
+    }
+
+    /**
+     * @dataProvider provideSanitise
+     */
+    public function testSanitiseString(string $input, string $expected): void
+    {
+        $sanitiser = new XssSanitiser();
+        $this->assertSame($expected, $sanitiser->sanitiseString($input));
+    }
+
+    /**
+     * @dataProvider provideSanitise
+     */
+    public function testSanitiseHtmlValue(string $input, string $expected): void
+    {
+        $sanitiser = new XssSanitiser();
+        $htmlValue = new HTMLValue($input);
+        $sanitiser->sanitiseHtmlValue($htmlValue);
+        $this->assertSame($expected, $htmlValue->getContent());
+    }
+
+    /**
+     * @dataProvider provideSanitise
+     */
+    public function testSanitiseElement(string $input, string $expected): void
+    {
+        $sanitiser = new XssSanitiser();
+        $htmlValue = new HTMLValue($input);
+        foreach ($htmlValue->query('//*') as $element) {
+            if (!is_a($element, DOMElement::class)) {
+                continue;
+            }
+            $element = $sanitiser->sanitiseElement($element);
+        }
+        $this->assertSame($expected, $htmlValue->getContent());
+    }
+
+    public function provideSanitiseElementsAllowed(): array
+    {
+        return [
+            'disallow these by default' => [
+                'input' => '<script>alert("one");</script><svg><circle cx="50" cy="50" r="40" /></svg><embed src="image.jpg"></embed><object data="image.jpg"></object>',
+                'removeElements' => null,
+                'expected' => 'alert("one");<circle cx="50" cy="50" r="40"></circle>',
+            ],
+            'allow all' => [
+                'input' => '<script>alert("one");</script><svg><circle cx="50" cy="50" r="40" /></svg><embed src="image.jpg"></embed><object data="image.jpg"></object>',
+                'removeElements' => [],
+                'expected' => '<script>alert("one");</script><svg><circle cx="50" cy="50" r="40"></circle></svg><embed src="image.jpg"></embed><object data="image.jpg"></object>',
+            ],
+            'disallow circle' => [
+                'input' => '<script>alert("one");</script><svg><circle cx="50" cy="50" r="40" /></svg><embed src="image.jpg"></embed><object data="image.jpg"></object>',
+                'removeElements' => ['circle'],
+                'expected' => '<script>alert("one");</script><svg></svg><embed src="image.jpg"></embed><object data="image.jpg"></object>',
+            ],
+        ];
+    }
+
+    /**
+     * @dataProvider provideSanitiseElementsAllowed
+     */
+    public function testSanitiseElementsAllowed(string $input, ?array $removeElements, string $expected): void
+    {
+        $sanitiser = new XssSanitiser();
+        if ($removeElements !== null) {
+            $sanitiser->setElementsToRemove($removeElements);
+        }
+        $this->assertSame($expected, $sanitiser->sanitiseString($input));
+    }
+
+    public function provideSanitiseAttributesAllowed(): array
+    {
+        return [
+            'disallow these by default' => [
+                'input' => '<span class="my-class" onanything onerror onclick onetc="anything" accesskey="A">abcd</span>',
+                'removeAttributes' => null,
+                'expected' => '<span class="my-class">abcd</span>',
+            ],
+            'allow all' => [
+                'input' => '<span class="my-class" onanything onerror onclick onetc="anything" accesskey="A">abcd</span>',
+                'removeAttributes' => [],
+                'expected' => '<span class="my-class" onanything="" onerror="" onclick="" onetc="anything" accesskey="A">abcd</span>',
+            ],
+            'disallow class' => [
+                'input' => '<span class="my-class" onanything onerror onclick onetc="anything" accesskey="A">abcd</span>',
+                'removeAttributes' => ['class'],
+                'expected' => '<span onanything="" onerror="" onclick="" onetc="anything" accesskey="A">abcd</span>',
+            ],
+            'wildcard attributes' => [
+                'input' => '<span class="my-class" title="my title" cattle="something" car="a thing" clap="nope" clop="yep" disabled="true">abcd</span>',
+                'removeAttributes' => [
+                    'cla*',
+                    '*tle',
+                    // this one specifically won't do anything
+                    'di*ed',
+                ],
+                'expected' => '<span car="a thing" clop="yep" disabled>abcd</span>',
+            ],
+            // Not sure why you'd do this, but this functionality is a natural consequence of how `*something` and `something*` are implemented.
+            'remove all attributes' => [
+                'input' => '<span class="my-class" title="my title" cattle="something" car="a thing" clap="nope" clop="yep" disabled="true">abcd</span>',
+                'removeAttributes' => [
+                    '*',
+                ],
+                'expected' => '<span>abcd</span>',
+            ],
+        ];
+    }
+
+    /**
+     * @dataProvider provideSanitiseAttributesAllowed
+     */
+    public function testSanitiseAttributesAllowed(string $input, ?array $removeAttributes, string $expected): void
+    {
+        $sanitiser = new XssSanitiser();
+        if ($removeAttributes !== null) {
+            $sanitiser->setAttributesToRemove($removeAttributes);
+        }
+        $this->assertSame($expected, $sanitiser->sanitiseString($input));
+    }
+
+    public function provideSanitiseNoKeepInnerHtml(): array
+    {
+        return [
+            'keeps inner html' => [
+                'input' => '<section>something first<div>Keep this<span>and this</span></div><span>something last</span></section>',
+                'keepInnerHtml' => true,
+                'expected' => '<section>something firstKeep this<span>and this</span><span>something last</span></section>',
+            ],
+            'discards inner html' => [
+                'input' => '<section>something first<div>Keep this<span>and this</span></div><span>something last</span></section>',
+                'keepInnerHtml' => false,
+                'expected' => '<section>something first<span>something last</span></section>',
+            ],
+            'multiple and nested disallowed elements (keep inner html)' => [
+                'input' => '<section>something<div></div><div><div><div>nested </div><div>nested2</div></div></div><span>last</span></section>',
+                'keepInnerHtml' => true,
+                'expected' => '<section>somethingnested nested2<span>last</span></section>',
+            ],
+            'multiple and nested disallowed elements (discard inner html)' => [
+                'input' => '<section>something<div></div><div><div><div>nested </div><div>nested2</div></div></div><span>last</span></section>',
+                'keepInnerHtml' => false,
+                'expected' => '<section>something<span>last</span></section>',
+            ],
+        ];
+    }
+
+    /**
+     * @dataProvider provideSanitiseNoKeepInnerHtml
+     */
+    public function testSanitiseNoKeepInnerHtml(string $input, bool $keepInnerHtml, string $expected): void
+    {
+        $sanitiser = new XssSanitiser();
+        $sanitiser->setElementsToRemove(['div'])->setKeepInnerHtmlOnRemoveElement($keepInnerHtml);
+        $this->assertSame($expected, $sanitiser->sanitiseString($input));
+    }
+}
diff --git a/tests/php/Forms/FormMessageTest.php b/tests/php/Forms/FormMessageTest.php
new file mode 100644
index 00000000000..02f689a7378
--- /dev/null
+++ b/tests/php/Forms/FormMessageTest.php
@@ -0,0 +1,100 @@
+<?php
+
+namespace SilverStripe\Forms\Tests;
+
+use SilverStripe\Core\Injector\Injector;
+use SilverStripe\Core\XssSanitiser;
+use SilverStripe\Dev\SapphireTest;
+use SilverStripe\Forms\Tests\FormMessageTest\TestFormMessage;
+use SilverStripe\ORM\ValidationResult;
+
+class FormMessageTest extends SapphireTest
+{
+    protected $usesDatabase = false;
+
+    public function provideGetMessage(): array
+    {
+        return [
+            'empty HTML' => [
+                'message' => '',
+                'type' => '',
+                'casting' => ValidationResult::CAST_HTML,
+                'expected' => '',
+            ],
+            'empty plain text' => [
+                'message' => '',
+                'type' => '',
+                'casting' => ValidationResult::CAST_TEXT,
+                'expected' => '',
+            ],
+            'plain HTML' => [
+                'message' => 'just some text',
+                'type' => '',
+                'casting' => ValidationResult::CAST_HTML,
+                'expected' => 'just some text',
+            ],
+            'plain plain text' => [
+                'message' => 'just some text',
+                'type' => '',
+                'casting' => ValidationResult::CAST_TEXT,
+                'expected' => 'just some text',
+            ],
+            'HTML in HTML' => [
+                'message' => '<div class="js-my-div"><a href="https://example.com">link</a></div>',
+                'type' => '',
+                'casting' => ValidationResult::CAST_HTML,
+                'expected' => '<div class="js-my-div"><a href="https://example.com">link</a></div>',
+            ],
+            'HTML in plain text' => [
+                'message' => '<div class="js-my-div"><a href="https://example.com">link</a></div>',
+                'type' => '',
+                'casting' => ValidationResult::CAST_TEXT,
+                'expected' => '<div class="js-my-div"><a href="https://example.com">link</a></div>',
+            ],
+            'Type doesnt matter HTML' => [
+                'message' => '<div class="js-my-div"><a href="https://example.com">link</a></div>',
+                'type' => 'an arbitrary string here',
+                'casting' => ValidationResult::CAST_HTML,
+                'expected' => '<div class="js-my-div"><a href="https://example.com">link</a></div>',
+            ],
+            'Type doesnt matter text' => [
+                'message' => '<div class="js-my-div"><a href="https://example.com">link</a></div>',
+                'type' => 'an arbitrary string here',
+                'casting' => ValidationResult::CAST_TEXT,
+                'expected' => '<div class="js-my-div"><a href="https://example.com">link</a></div>',
+            ],
+        ];
+    }
+
+    /**
+     * Test that getMessage() generally works and calls the sanitiser as appropriate.
+     * Note we don't actually test the sanitisation here, as that is handled by the sanitiser's unit tests.
+     * @dataProvider provideGetMessage
+     */
+    public function testGetMessage(string $message, string $type, string $casting, string $expected): void
+    {
+        $mockSanitiserClass = get_class(new class extends XssSanitiser {
+            public static int $called = 0;
+            public function sanitiseString(string $html): string
+            {
+                static::$called++;
+                return parent::sanitiseString($html);
+            }
+        });
+        Injector::inst()->load([
+            XssSanitiser::class => [
+                'class' => $mockSanitiserClass,
+            ],
+        ]);
+        $expectedSanitisationCount = $casting === ValidationResult::CAST_HTML ? 1 : 0;
+
+        try {
+            $formMessage = new TestFormMessage();
+            $formMessage->setMessage($message, $type, $casting);
+            $this->assertSame($expected, $formMessage->getMessage());
+            $this->assertSame($expectedSanitisationCount, $mockSanitiserClass::$called);
+        } finally {
+            $mockSanitiserClass::$called = 0;
+        }
+    }
+}
diff --git a/tests/php/Forms/FormMessageTest/TestFormMessage.php b/tests/php/Forms/FormMessageTest/TestFormMessage.php
new file mode 100644
index 00000000000..a77dfcd347b
--- /dev/null
+++ b/tests/php/Forms/FormMessageTest/TestFormMessage.php
@@ -0,0 +1,14 @@
+<?php
+
+namespace SilverStripe\Forms\Tests\FormMessageTest;
+
+use SilverStripe\Dev\TestOnly;
+use SilverStripe\Forms\FormMessage;
+
+/**
+ * FormMessage is a trait, so we need a class that uses it to test it.
+ */
+class TestFormMessage implements TestOnly
+{
+    use FormMessage;
+}