Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Content Security Policy - style-src does not prevent inline styles

I have the following CSP in meta:

<!doctype html>
<html lang="en">
   <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width,initial-scale=1,shrink-to-fit=no">
      <meta http-equiv="Content-Security-Policy" content="base-uri 'self'; object-src 'none'; script-src 'self'; style-src 'self'; default-src 'self'; connect-src http://localhost:3000/ https://localhost:5001/ https://localhost:6001/; frame-src https://localhost:6001/ http://localhost:3000/">
      <meta name="theme-color" content="#000000">
      <base href="/">
      <link rel="manifest" href="/manifest.json">
      <link rel="shortcut icon" href="/favicon.ico">
      <title>Stack Underflow</title>
      <link href="/static/css/2.67123b20.chunk.css" rel="stylesheet">
   </head>
   <body>
      <noscript>You need to enable JavaScript to run this app.</noscript>
      <div id="root"></div>
      <script src="/static/js/runtime-main.ee376b76.js"></script><script src="/static/js/2.17f1251a.chunk.js"></script><script src="/static/js/main.69a64aff.chunk.js"></script>
   </body>
</html>

React is used to add stuff to the page.

const MyComponent = () => {
    return (
        <div style={{ borderStyle: "solid", borderColor: "green" }}>
        ...
        </div>
    );
};

However, the below line is still accepted and no error is shown in the console:

<div style="border-style: solid; border-color: red;">...</div>

When I manually hardcode the above <div> in index.html then CSP works fine.

Tested in:

  • Chrome 88.0.4324.150
  • Microsoft Edge 88.0.705.74
  • Firefox 69.0.3
like image 610
Robotronx Avatar asked Mar 08 '26 22:03

Robotronx


1 Answers

That's possible only if you placed <meta http-equiv="Content-Security-Policy" ...> not in <head> section - it does not work in this case.

Or the <div style="border-style: solid; border-color: red;">...</div> is within <iframe> - CSP of parent page does not acts inside nested browsing contexts except sandbox directive.

Another option is that you did set the meta tag by javascript after <div style='...'> has already been inserted into the DOM. Еhe meta has no retroactive effect.

UPDATED
After showing the code, it's cleat that React inserts styles via Element.style.property = 'value'; (i.e. div.style.borderStyle="solid", div.style.borderColor="green").

This is allowed method, it do not cause CSP violation. Using the setAttrubute("style", ...) - is disallowed and will throws violation.

like image 176
granty Avatar answered Mar 10 '26 15:03

granty



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!