Twig-沙盒安全策略不起作用

时间:2018-09-29 15:18:12

标签: php symfony twig sandbox twig-extension

我一直在尝试使它工作一段时间,但找不到太多文档。或在Symphony框架之外使用沙盒策略的任何用例。

我将Twig作为独立程序包使用,因此不能使用任何Symphony伪代码。

我启用了严格模式,因此沙箱会影响所有模板。除了可以调用一个类的模板之外,大多数模板都可以很好地渲染。但是我不知道如何允许它通过。

班级:

class GetThings {

    public function doStuff() {
        return array(
            'id'   => '...',
            'data' => '...'
        );
    }

}

...

嫩枝:

$allowedTags = ['if', 'else', 'elseif', 'endif', 'for', 'endfor'];
$allowedFilters = ['upper', 'escape'];
$allowedMethods = [
    'GetThings' => array('doStuff') // Possibly this may be wrong?
];
$allowedProperties = [
    'GetThings' => array('id', 'data') // Or this is wrong? But not sure the correct way.
];
$allowedFunctions = ['range'];

$policy = new Twig_Sandbox_SecurityPolicy($allowedTags, $allowedFilters, $allowedMethods, $allowedProperties, $allowedFunctions);
$sandbox = new Twig_Extension_Sandbox($policy, true);

...

模板:

{% for i in info %}
    {{ i.id }}       <- Code that raises securityPolicy exception.
    {{ i.data }}     <- Code that raises securityPolicy exception.
{% endfor %}

我相信它可能与允许的方法或属性有关,但是我找不到使用中的任何有效示例。我也尝试过完整的名称空间,什么也没有。

编辑: 因此,我更深入地研究了该错误,并发现了异常堆栈跟踪,由于某种原因,它认为我的类是StdClass而不是GetThings?不知道为什么。有什么想法吗?

Twig_Sandbox_SecurityNotAllowedPropertyError: Calling "id" property on a "stdClass" object is not allowed.

要实例化该类,我只需执行以下操作:

public function index() {
    $data = new GetThings();
    // echo get_class($data); // returns GetThings as expected...

    return $twig->render('index.twig', [
        'info' => $data->doStuff()
    ]);
}

如果我对允许的属性进行'StdClass' => array('id', 'data'),则页面工作正常。但是我觉得这不符合预期,因为StdClass可能是什么? GetThings应该可以,不是吗?

编辑

我想我明白了。因此,我允许的属性允许'GetThings' => [id, data]很好。 doStuff()使用\PDO选项返回\PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_OBJ对象数组,该选项使PDO将所有返回的值转换为StdClass对象。

有什么办法解决吗?我想保留该选项,但仍想将该策略引用为'GetThings' => [...]而不是'StdClass' => [...]

1 个答案:

答案 0 :(得分:0)

它按预期工作:

{% for i in info %}
    {{ i.id }}       <- Code that raises securityPolicy exception.
    {{ i.data }}     <- Code that raises securityPolicy exception.
{% endfor %}

这里i不是GetThings实例。无论您实例化为iddata键的值:

return array(
    'id'   => '...',
    'data' => '...'
);

Twig for标记将迭代info变量,该变量恰好是键控数组。因此,循环将遍历数组的值-在您的情况下,“ ...”和“ ...”,我猜这是stdClass实例。