escapeCSS escaped CSS (seems to be) ignored by browsers?

When I test the following code the CSS is escaped, but seems to be ignored by any browser I tested with on my Macbook Air M1 (Chrome, Safari, Firefox, Edge).

I don’t get any console or PHP errors.

The test code (based on the sample in the docs):

<?php header('Content-Type: application/xhtml+xml; charset=UTF-8'); ?>
<!DOCTYPE html>
<?php
require_once __DIR__ . '/vendor/autoload.php';
$input = <<<INPUT
body { color: blue; }
INPUT;
$escaper = new Laminas\Escaper\Escaper('utf-8');
$output = $escaper->escapeCss($input);
?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Escaped CSS</title>
    <meta charset="UTF-8"/>
    <style>
    <?php
    echo $output;
    ?>
    </style>
</head>
<body>
    <p>User controlled CSS needs to be properly escaped!</p>
</body>
</html>

The generated escaped style tag:

<style>
    body\20 \7B \20 color\3A \20 blue\3B \20 \7D     
</style>

The same happens with the original test code in the docs.
Why isn’t the escaped CSS ignored by the browsers?
What am I missing?

Cheers,
Benny

Hello and welcome to our forums! :smiley:

The example in the documentation is wrong because the escaping should not be applied to the whole CSS, only to fragments that are inserted into the CSS, like URLs – if it comes from non-trusted sources.

Compare:

<?php
$url = 'https://getlaminas.org/images/pictures/home-page.jpg</style><script>alert(1)</script>';
?>
<!doctype html>
<meta charset="utf-8">
<title>Escaped CSS</title>
<style>
body {
    background-image: url('<?= $url ?>');
}
</style>
<p>User controlled CSS needs to be properly escaped!</p>
<?php
require_once __DIR__ . '/vendor/autoload.php';

$url = 'https://getlaminas.org/images/pictures/home-page.jpg</style><script>alert(1)</script>';
?>
<!doctype html>
<meta charset="utf-8">
<title>Escaped CSS</title>
<style>
body {
    background-image: url('<?= (new Laminas\Escaper\Escaper())->escapeCss($url) ?>');
}
</style>
<p>User controlled CSS needs to be properly escaped!</p>
<?php
require_once __DIR__ . '/vendor/autoload.php';

$url = 'https://getlaminas.org/images/pictures/home-page.jpg';
?>
<!doctype html>
<meta charset="utf-8">
<title>Escaped CSS</title>
<style>
body {
    background-image: url('<?= (new Laminas\Escaper\Escaper())->escapeCss($url) ?>');
}
</style>
<p>User controlled CSS needs to be properly escaped!</p>

The goal is to prevent XSS, which in this example means that the JavaScript is not executed. This does not mean that the background image is also set correctly.

@froschdesign,

Thanks for clearing this up for me.

I submitted a new issue regarding this on Github: https://github.com/laminas/laminas-escaper/issues/16.

Do you maybe know of a component that parses a complete (user submitted) stylesheet and escapes it for safe output?

Anyways thank you for your answer and time!