1

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

1
  • I removed the 'yii' tag from your question, because this is not Yii-specific. Commented Apr 22, 2012 at 10:12

3 Answers 3

2

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:

  • line containing behavior: url( .. )
  • all instances where !important is used
  • entries which contain selectors to specific ID, like #ads and #logo
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.