Chris@0
|
1 # Escaping Cascading Style Sheets
|
Chris@0
|
2
|
Chris@0
|
3 CSS is similar to [escaping Javascript](escaping-javascript.md). CSS escaping
|
Chris@0
|
4 excludes only basic alphanumeric characters and escapes all other characters
|
Chris@0
|
5 into valid CSS hexadecimal escapes.
|
Chris@0
|
6
|
Chris@0
|
7 ## Example of Bad CSS Escaping
|
Chris@0
|
8
|
Chris@0
|
9 In most cases developers forget to escape CSS completely:
|
Chris@0
|
10
|
Chris@0
|
11 ```php
|
Chris@0
|
12 <?php header('Content-Type: application/xhtml+xml; charset=UTF-8'); ?>
|
Chris@0
|
13 <!DOCTYPE html>
|
Chris@0
|
14 <?php
|
Chris@0
|
15 $input = <<<INPUT
|
Chris@0
|
16 body {
|
Chris@0
|
17 background-image: url('http://example.com/foo.jpg?</style><script>alert(1)</script>');
|
Chris@0
|
18 }
|
Chris@0
|
19 INPUT;
|
Chris@0
|
20 ?>
|
Chris@0
|
21 <html xmlns="http://www.w3.org/1999/xhtml">
|
Chris@0
|
22 <head>
|
Chris@0
|
23 <title>Unescaped CSS</title>
|
Chris@0
|
24 <meta charset="UTF-8"/>
|
Chris@0
|
25 <style>
|
Chris@0
|
26 <?= $input ?>
|
Chris@0
|
27 </style>
|
Chris@0
|
28 </head>
|
Chris@0
|
29 <body>
|
Chris@0
|
30 <p>User controlled CSS needs to be properly escaped!</p>
|
Chris@0
|
31 </body>
|
Chris@0
|
32 </html>
|
Chris@0
|
33 ```
|
Chris@0
|
34
|
Chris@0
|
35 In the above example, by failing to escape the user provided CSS, an attacker
|
Chris@0
|
36 can execute an XSS attack fairly easily.
|
Chris@0
|
37
|
Chris@0
|
38 ## Example of Good CSS Escaping
|
Chris@0
|
39
|
Chris@0
|
40 By using `escapeCss()` method in the CSS context, such attacks can be prevented:
|
Chris@0
|
41
|
Chris@0
|
42 ```php
|
Chris@0
|
43 <?php header('Content-Type: application/xhtml+xml; charset=UTF-8'); ?>
|
Chris@0
|
44 <!DOCTYPE html>
|
Chris@0
|
45 <?php
|
Chris@0
|
46 $input = <<<INPUT
|
Chris@0
|
47 body {
|
Chris@0
|
48 background-image: url('http://example.com/foo.jpg?</style><script>alert(1)</script>');
|
Chris@0
|
49 }
|
Chris@0
|
50 INPUT;
|
Chris@0
|
51
|
Chris@0
|
52 $escaper = new Zend\Escaper\Escaper('utf-8');
|
Chris@0
|
53 $output = $escaper->escapeCss($input);
|
Chris@0
|
54 ?>
|
Chris@0
|
55 <html xmlns="http://www.w3.org/1999/xhtml">
|
Chris@0
|
56 <head>
|
Chris@0
|
57 <title>Escaped CSS</title>
|
Chris@0
|
58 <meta charset="UTF-8"/>
|
Chris@0
|
59 <style>
|
Chris@0
|
60 <?php
|
Chris@0
|
61 // output will look something like
|
Chris@0
|
62 // body\20 \7B \A \20 \20 \20 \20 background\2D image\3A \20 url\28 ...
|
Chris@0
|
63 echo $output;
|
Chris@0
|
64 ?>
|
Chris@0
|
65 </style>
|
Chris@0
|
66 </head>
|
Chris@0
|
67 <body>
|
Chris@0
|
68 <p>User controlled CSS needs to be properly escaped!</p>
|
Chris@0
|
69 </body>
|
Chris@0
|
70 </html>
|
Chris@0
|
71 ```
|
Chris@0
|
72
|
Chris@0
|
73 By properly escaping user controlled CSS, we can prevent XSS attacks in our web
|
Chris@0
|
74 applications.
|