csssecuritypenetration-testing

What is CSS injection and how to prevent it?


I have heard my friend talking about this vulnerability called "CSS Injections" However, I have no idea what this is and as soon as I heard it I thought, how could one possibly do any malicious activity or an attack using CSS?

So I wanted to know what is this "CSS Injections" vulnerability and how does one prevent it.


Solution

  • What is it?

    CSS injection means that an attacker manages to upload malicious CSS code to your website which will run on your visitors' browsers.

    Is it dangerous?

    Writing this in 2022, NO, CSS injection is almost not affecting anyone since browsers have overcome this, but note that some users using old browsers may get affected by this.

    Should I do something?

    Yes you should, even though it is not currently a real risk, you should prevent attackers from injecting your website with malicious CSS and JavaScript, JavaScript is very important because some exploits were batched recently and most users didn't update their browsers to the latest version yet.

    How to protect?

    You should always filter user input from malicious injections but an extra layer of protection is:

    a solution to all this is using CSP Header (Content-Security-Policy) which allows you to prevent browsers from executing malicious code on your website.

    in apache htaccess file add the following but mod_headers should be enabled

    Header set Content-Security-Policy "default-src 'self';script-src 'self';style-src 'self'; object-src 'none'; frame-ancestors 'none'; form-action 'self';  base-uri 'self';"
    

    Note that you can't use the code above if you use CSS or JavaScript from another domain.

    For more info and to understand what each word in the code does visit MDN CSP

    EDIT:

    The simplest example of CSS injection is when an attacker manages to inject your website with a CSS code that loads an external asset such as in backgrounds and those assets are payloads, luckily most browsers have overcome such vulnerability.

    background: url(http://somehackerdomain.com/payload...)
    

    Another simple example of CSS injection which still affects all modern browsers is that in case your website JavaScript uses a CSS property value, then the attacker could set a new value for this property as a JavaScript code which may steal cookies, etc.

    Those are only some of the simple examples.

    For more about CSS injection see C-SHARP-CORNER CSS Injection

    A third layer of protection to protect cookies is to use HttpOnly which prevents JavaScript from accessing them. for more about HttpOnly visit HttpOnly