2

I'm looking to store CSS in a mySql database (LAMP setup). I'd like to do an input field with the following:

body{ background: url("http://google.com/image.jpg") no-repeat; color: orange; }
#someDiv {width: 50%;}

... you get the idea. How would I best sanitize this data to allow it in the database? Thanks for the help, I can't seem to find a good solution on SO yet.

ingage
  • 220
  • 2
  • 14
  • 1
    Sanitize it? I'm not sure what you're asking. – Jay Blanchard Oct 10 '14 at 15:20
  • 2
    It's just text. Treat it like any OTHER text you'd be inserting into the database: use a prepared statement and placeholders. In other words, read this: http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php – Marc B Oct 10 '14 at 15:22
  • 6
    You mean to prevent `BOOBIES` ? – Alex K. Oct 10 '14 at 15:23
  • 1
    Is this text entered by a user? You will have to double check the input; 1. make it safe against SQL-inject (should be easy) 2. Make shure it is properly escaped against XSS. https://www.owasp.org/index.php/XSS – Christian Kuetbach Oct 10 '14 at 15:24
  • @ChristianKuetbach Escaping won't prevent XSS attacks, since he's allowing users to determine they're own remote resources to load through CSS rules using URL(). All he can really do is validate the CSS and possibly limit the set of rules allowed. – Logan Bailey Oct 10 '14 at 15:28
  • 1
    @LoganBailey Well ... right. I think this "feature" is really hard to implement. There is a nice tutorial for escaping CSS: https://www.owasp.org/index.php/XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet#RULE_.234_-_CSS_Escape_And_Strictly_Validate_Before_Inserting_Untrusted_Data_into_HTML_Style_Property_Values – Christian Kuetbach Oct 10 '14 at 15:32

1 Answers1

3
<style type="text/css">
   @import '/yourcssgenerator.php;
</style>

yourcssgenerator.php can serve the CSS with components pulled from wherever you like, be it a database or scraping it from stackoverflow.com. By keeping CSS in its own resource you don't have to worry about malicious stuff being injected.

Stylesheets don't have to have a .css extension. You can even create you own CSS templating layer this way and allow individual users, co-branded clients etc to have their own version of the CSS.

Check this question for implementation details.

Community
  • 1
  • 1
cdonner
  • 37,019
  • 22
  • 105
  • 153