在PHP中清理用户定义的CSS [英] Sanitize user defined CSS in PHP

查看:122
本文介绍了在PHP中清理用户定义的CSS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想允许用户在我的论坛上为自己的个人资料使用自己的样式表,但我担心可能存在的安全漏洞。

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 sanitizing CSS?

基本过程:用户将CSS输入到表单 - >保存到数据库 - >输出为内联CSS

Basic process: User enters CSS into form -> Save to DB -> Output as inline CSS

推荐答案

HTMLPurifier CSSTidy 可以满足您的要求。

HTMLPurifier with CSSTidy does what you're looking for.

HTMLPurifier主要用于清理HTML,

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

HTMLPurifier文档中有一个示例(但是唉,每个帖子我已经用完了两个链接)。

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('<style>'.$input_css.'</style>');

// 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];

输出为:

body {
    margin:0;
    padding:0;
}

a {
    color:#ccc;
    text-decoration:none;
}

.banner {
}

这篇关于在PHP中清理用户定义的CSS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆