I am working on a site and I would like to make a user able to enter custom CSS into that will be publicly displayed.
However, seeing as a good deal of XSS attacks can be preformed through CSS, I would like to be able to find a way to "clean" the CSS output, similar to how HTML Purifier works, by parsing the CSS, running the parsed CSS against a whitelist, and then outputting a new stylesheet based on the parsed and whitelisted CSS.
Is there already a library like this out there? If not, is there a CSS parsing library that can be used to create a custom implementation?
Using htmlspecialchars() function – The htmlspecialchars() function converts special characters to HTML entities. For a majority of web-apps, we can use this method and this is one of the most popular methods to prevent XSS. This process is also known as HTML Escaping.
Cross-site scripting (XSS) is a computer security vulnerability that allows malicious attackers to inject client-side script into web pages viewed by other users. You can use the Cross-site Scripting Filter setting to check all HTTP GET requests sent to IBM® OpenPages® with Watson™.
Content security policy (CSP) is a browser mechanism that aims to mitigate the impact of cross-site scripting and some other vulnerabilities.
A very big portion of web applications are using HTML Entity Encoding to handle untrusted data, and this method is robust enough to protect them from XSS attack for most of the time.
I guess you're going to write your own CSS parser and filter, so here's what I'd consider, although I've never done such a thing:
color
, font-family
.background
, at least in the beginning, so that you can easily parse the values. Require that they explicitly write background-color
, background-image
.When parsing, the hardest part would be the parsing of complex CSS selectors. But you can impose your own subset here too.
Here's some (pseudo)code, maybe it will help you somehow:
<?php
function tokenizeCSS() {
return array(
array(
'selector' => '#foo .bar',
'properties' => array(
'background-color' => 'transparent',
'color' => '#fff',
),
);
);
}
function colorValidator($color)
{}
/**
* This is basically the white list. Keys are accepted CSS properties
* and values are the validator callbacks.
*/
$propertyValidators = array(
'background-color' => 'colorValidator',
'color' => 'colorValidator',
);
$filteredRules = array();
foreach (tokenizeCSS() as $rule) {
if (! validSelector($rule['selector'])) {
continue;
}
foreach ($rule['properties'] as $property => $value) {
/**
* Check property is in white list
*/
if (! isset($propertyValidators[$property]) {
continue;
}
/**
* Check property is valid
*/
if (! $propertyValidators[$property]($value)) {
continue;
}
/**
* Valid rule
*/
$filteredRules[$rule['selector']][$property] = $value;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With