0

i want to offer customers a possibility to insert CSS into an Iframe for changing Colors and so on.

Is my Code a good way to do so? I already wrapped "GET" with htmlspecialchars in order to prevent an inject or closing tags, i.e. ?> in URL for running random new Code.

<?
$css_url = null;
if ( isset($_GET["css_url"]) ) {
 $css_url = "". htmlspecialchars($_GET["css_url"]);
}
if ($css-url != null && strlen($css_url) > 0) {
 echo('<link href="'.$css_url.'" rel="stylesheet" type="text/css"  />');
}
?>

Is it unsafe to run this? Any suggestions and explanations why?

Raphuu
  • 3
  • 3
  • Does this answer your question? [XSS filtering function in PHP](https://stackoverflow.com/questions/1336776/xss-filtering-function-in-php) – Triby Jan 31 '20 at 18:38

2 Answers2

0

First of all, to be clear, you're not injecting CSS rules here, but a link to an external CSS file that must be hosted somewhere. Is this really what you want?

  • Regarding the risk of XSS injection, you're fine with htmlspecialchars(), as long as you provide the correct encoding of your page as 3rd parameter;
  • You should, however, at the very least make a sanity check of the URL (check that it starts with http:// or https://, and that it's syntactically valid;
  • If your site is on https, you must only accept URLs starting with https, or you'll get an unsecure content warning in your browser;

Other than that, the risks should be very limited. If the link does not point to a valid CSS file, it will likely be ignored. The only real annoyance is the ability for an attacker to make visitors of your site trigger a GET request on any URL they want.


That being said, I would advise that you allow users to provide CSS rules instead, i.e. what goes inside a <style> tag. Now if you do this, it's a different story: you have to be sure that the provided CSS code does not contain </style>, or this opens the door to XSS injections.

If you're following this route, I would advise you to parse the CSS rules provided with a CSS parser such as this one. This way, you can ensure that only valid CSS can be given, which is good for both security and quality.

BenMorel
  • 34,448
  • 50
  • 182
  • 322
  • Hi, thank you! Yes its about parsing a CSS FILE (FULL URL) over Parameter. Not just some Arguments. – Raphuu Feb 01 '20 at 20:41
0

@Benjamin i edited Code with a friend. Any thoughts on this? We tried to insert your Suggestions:

$cssurl = null;
if ( isset($_GET["cssurl"]) ) {
    $cssurl = "". htmlspecialchars($_GET["cssurl"], ENT_COMPAT, "UTF-8");
}
if ($cssurl != null && strlen($cssurl) > 0) {
    if (strpos($cssurl, "https://") === 0) {
        if (strrpos($cssurl, ".css") === strlen($cssurl)-4) {
            echo('<link href="'.$cssurl.'" rel="stylesheet" type="text/css"  />');
        }
    }
}
Raphuu
  • 3
  • 3