Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Security policy wildcard support for methods/properties #3901

Open
wants to merge 8 commits into
base: 2.x
Choose a base branch
from
Open
79 changes: 79 additions & 0 deletions src/Sandbox/MemberMatcher.php
@@ -0,0 +1,79 @@
<?php

/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Twig\Sandbox;

/**
* Allows for flexible wildcard support in allowedMethods and allowedProperties in SecurityPolicy.
* - Class can be specified as wildcard `* => [...]` in order to allow those methods/properties for all classes.
* - Method/property can be specified as wildcard eg. `\DateTime => '*'` in order to allow all methods/properties for that class.
* - Method/property can also be specified with a trailing wildcard to allow all methods/properties with a certain prefix, eg. `\DateTime => ['get*', ...]` in order to allow all methods/properties that start with `get`.
*
* @author Yaakov Saxon <ysaxon@gmail.com>
*/
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's mark this class as@internal.

final class MemberMatcher
{
private $allowedMembers;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
private $allowedMembers;
private array $allowedMembers;

private $cache = [];
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
private $cache = [];
private array $cache = [];


public function __construct(array $allowedMembers)
{
$normalizedMembers = [];
foreach ($allowedMembers as $class => $members) {
if (!\is_array($members)) {
$normalizedMembers[$class][] = strtolower($members);
} else {
foreach ($members as $index => $member) {
$normalizedMembers[$class][$index] = strtolower($member);
}
}
}
$this->allowedMembers = $normalizedMembers;
}

public function isAllowed($obj, string $member): bool
{
$cacheKey = get_class($obj) . "::" . $member;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
$cacheKey = get_class($obj) . "::" . $member;
$cacheKey = get_class($obj).'::'.$member;


// Check cache first
if (isset($this->cache[$cacheKey])) {
return true;
}

$member = strtolower($member); // normalize member name

foreach ($this->allowedMembers as $class => $members) {
if ('*' === $class || $obj instanceof $class) {
foreach ($members as $allowedMember) {
if ('*' === $allowedMember) {
$this->cache[$cacheKey] = true;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
$this->cache[$cacheKey] = true;
return $this->cache[$cacheKey];

Same below


return true;
}
if ($allowedMember === $member) {
$this->cache[$cacheKey] = true;

return true;
}
// if allowedMember ends with a *, check if the member starts with the allowedMember
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why do we only allow *to be at the end?

if ('*' === substr($allowedMember, -1) && substr($member, 0, \strlen($allowedMember) - 1) === rtrim($allowedMember, '*')) {
$this->cache[$cacheKey] = true;

return true;
}
}
}
}

// If we reach here, the member is not allowed
return false;
}
}
31 changes: 6 additions & 25 deletions src/Sandbox/SecurityPolicy.php
Expand Up @@ -32,7 +32,7 @@ public function __construct(array $allowedTags = [], array $allowedFilters = [],
$this->allowedTags = $allowedTags;
$this->allowedFilters = $allowedFilters;
$this->setAllowedMethods($allowedMethods);
$this->allowedProperties = $allowedProperties;
$this->setAllowedProperties($allowedProperties);
$this->allowedFunctions = $allowedFunctions;
}

Expand All @@ -48,15 +48,12 @@ public function setAllowedFilters(array $filters)

public function setAllowedMethods(array $methods)
{
$this->allowedMethods = [];
foreach ($methods as $class => $m) {
$this->allowedMethods[$class] = array_map(function ($value) { return strtr($value, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'); }, \is_array($m) ? $m : [$m]);
}
$this->allowedMethods = new MemberMatcher($methods);
}

public function setAllowedProperties(array $properties)
{
$this->allowedProperties = $properties;
$this->allowedProperties = new MemberMatcher($properties);
}

public function setAllowedFunctions(array $functions)
Expand Down Expand Up @@ -91,32 +88,16 @@ public function checkMethodAllowed($obj, $method)
return;
}

$allowed = false;
$method = strtr($method, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz');
foreach ($this->allowedMethods as $class => $methods) {
if ($obj instanceof $class && \in_array($method, $methods)) {
$allowed = true;
break;
}
}

if (!$allowed) {
if (!$this->allowedMethods->isAllowed($obj, $method)) {
$class = \get_class($obj);
$method = strtr($method, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz');
throw new SecurityNotAllowedMethodError(sprintf('Calling "%s" method on a "%s" object is not allowed.', $method, $class), $class, $method);
}
}

public function checkPropertyAllowed($obj, $property)
{
$allowed = false;
foreach ($this->allowedProperties as $class => $properties) {
if ($obj instanceof $class && \in_array($property, \is_array($properties) ? $properties : [$properties])) {
$allowed = true;
break;
}
}

if (!$allowed) {
if (!$this->allowedProperties->isAllowed($obj, $property)) {
$class = \get_class($obj);
throw new SecurityNotAllowedPropertyError(sprintf('Calling "%s" property on a "%s" object is not allowed.', $property, $class), $class, $property);
}
Expand Down
81 changes: 81 additions & 0 deletions tests/Extension/SandboxTest.php
Expand Up @@ -449,6 +449,87 @@ public function testMultipleClassMatchesViaInheritanceInAllowedMethods()
}
}

public function testSandboxAllowedWildcardMethod()
{
$allowedMethods = ['Twig\Tests\Extension\FooObject' => ['*']];
$twig = $this->getEnvironment(true, [], self::$templates, [], [], $allowedMethods);

// This should pass without throwing an exception
$result = $twig->load('1_basic1')->render(self::$params);
$this->assertEquals('foo', $result);
$result = $twig->load('1_basic8')->render(self::$params);
$this->assertEquals('foobarfoobar', $result);

}

public function testSandboxAllowedWildcardSuffixMethod()
{
$allowedMethods = ['Twig\Tests\Extension\FooObject' => ['get*']];
$twig = $this->getEnvironment(true, [], self::$templates, [], [], $allowedMethods);

// This should pass without throwing an exception
$result = $twig->load('1_basic8')->render(self::$params);
$this->assertEquals('foobarfoobar', $result);
}

public function testSandboxUnallowedPrefixWildcardSuffixMethod()
{
$allowedMethods = ['Twig\Tests\Extension\FooObject' => ['get*']];
$twig = $this->getEnvironment(true, [], self::$templates, [], [], $allowedMethods);

try {
$twig->load('1_basic1')->render(self::$params);
$this->fail('Sandbox should block method not matching method prefix');
} catch (SecurityError $e) {
$this->assertInstanceOf(SecurityNotAllowedMethodError::class, $e);
$this->assertEquals('foo', $e->getMethodName());
}
}

public function testSandboxAllowedWildcardClassMethod()
{
$allowedMethods = ['*' => ['foo']];
$twig = $this->getEnvironment(true, [], self::$templates, [], [], $allowedMethods);

// This should pass without throwing an exception
$result = $twig->load('1_basic1')->render(self::$params);
$this->assertEquals('foo', $result);
}

public function testSandboxUnallowedWildcardClassMethod()
{
$allowedMethods = ['*' => ['foo']];
$twig = $this->getEnvironment(true, [], self::$templates, [], [], $allowedMethods);

try {
$twig->load('1_basic8')->render(self::$params);
$this->fail('Sandbox should block non matching method despite class wildcard');
} catch (SecurityError $e) {
$this->assertInstanceOf(SecurityNotAllowedMethodError::class, $e);
$this->assertEquals('getfoobar', $e->getMethodName());
}
}

public function testSandboxAllowedWildcardClassWildcardSuffixMethod()
{
$allowedMethods = ['*' => ['get*']];
$twig = $this->getEnvironment(true, [], self::$templates, [], [], $allowedMethods);

// This should pass without throwing an exception
$result = $twig->load('1_basic8')->render(self::$params);
$this->assertEquals('foobarfoobar', $result);
}

public function testSandboxAllowedWildcardClassWildcardSuffixProperty()
{
$allowedProperties = ['*' => ['b*']];
$twig = $this->getEnvironment(true, [], self::$templates, [], [], [], $allowedProperties);

// This should pass without throwing an exception
$result = $twig->load('1_basic4')->render(self::$params);
$this->assertEquals('bar', $result);
}

protected function getEnvironment($sandboxed, $options, $templates, $tags = [], $filters = [], $methods = [], $properties = [], $functions = [])
{
$loader = new ArrayLoader($templates);
Expand Down