Reputation: 3523
I'm providing a way for my users to change the CSS of their user pages by entering some CSS in their settings page. Here is the HTML:
<textarea class="code" name="Settings[css]"></textarea>
In the controller:
$model = new Profile;
$model->css = $_POST['Settings']['css'];
I currently don't validate the input for the CSS field. I was wondering if I could filter the CSS so that they couldn't put harmful code in to the page. For example, they could do:
</style>
Now I can put bad code in to your page
I don't think purifying css with HTMLpurifier would be appropriate because CSS usually contains special characters, but correct me if I'm wrong.
Thanks
Upvotes: 1
Views: 497
Reputation: 9567
You could try a php css parser like this:
https://github.com/sabberworm/PHP-CSS-Parser
But I can't tell you anything about the quality of code it produces or how it handles problems with input.
What I do know is that LESS has good debugging usually.
If you use the LESS php class you could build a system where the $_POST['Settings']['css']
is used to create valid CSS. Or if errors occur you can catch them and return that to the browser.
Yes this effectively enables you to use LESS syntax in the field but I don't see the harm in that. LESS is in some ways stricter in the syntax of CSS through, requiring semicolons regardless of if its the last property in the list and extra characters can also trigger errors.
The debugging information for the javascript version is pretty solid though, I can't personally vouch for the PHP class since I only use the JS, but from what I hear its the second best thing after the JS.
Upvotes: 1
Reputation:
strip_tags()
can remove html tags from the input, though I don't think it's the only thing you have to worry about.
An easier solution may be to load this style through an external stylesheet (<link rel="stylesheet" type="text/css" href="userstyle.php?uid=1235" />
) instead of an inline style block, that way there's no way to break out.
Upvotes: 1
Reputation: 58444
This has nothing to do with Yii in any shape of form.
The "invalid code" that you provided in example could be easily removed, if you include the User CSS as an external file.
And that is not all they can do with CSS. You should manually remove following entries:
behavior: url( .. )
!important
is used#ads
and #logo
Upvotes: 2