3 namespace Drupal\Core\Template;
5 use Drupal\Core\Site\Settings;
8 * Default sandbox policy for Twig templates.
10 * Twig's sandbox extension is usually used to evaluate untrusted code by
11 * limiting access to potentially unsafe properties or methods. Since we do not
12 * use ViewModels when passing objects to Twig templates, we limit what those
13 * objects can do by whitelisting certain classes, method names, and method
14 * names with an allowed prefix. All object properties may be accessed.
16 class TwigSandboxPolicy implements \Twig_Sandbox_SecurityPolicyInterface {
19 * An array of whitelisted methods in the form of methodName => TRUE.
23 protected $whitelisted_methods;
26 * An array of whitelisted method prefixes -- any method starting with one of
27 * these prefixes will be allowed.
31 protected $whitelisted_prefixes;
34 * An array of class names for which any method calls are allowed.
38 protected $whitelisted_classes;
41 * Constructs a new TwigSandboxPolicy object.
43 public function __construct() {
44 // Allow settings.php to override our default whitelisted classes, methods,
46 $whitelisted_classes = Settings::get('twig_sandbox_whitelisted_classes', [
47 // Allow any operations on the Attribute object as it is intended to be
48 // changed from a Twig template, for example calling addClass().
49 'Drupal\Core\Template\Attribute',
51 // Flip the arrays so we can check using isset().
52 $this->whitelisted_classes = array_flip($whitelisted_classes);
54 $whitelisted_methods = Settings::get('twig_sandbox_whitelisted_methods', [
55 // Only allow idempotent methods.
63 $this->whitelisted_methods = array_flip($whitelisted_methods);
65 $this->whitelisted_prefixes = Settings::get('twig_sandbox_whitelisted_prefixes', [
75 public function checkSecurity($tags, $filters, $functions) {}
80 public function checkPropertyAllowed($obj, $property) {}
85 public function checkMethodAllowed($obj, $method) {
86 foreach ($this->whitelisted_classes as $class => $key) {
87 if ($obj instanceof $class) {
92 // Return quickly for an exact match of the method name.
93 if (isset($this->whitelisted_methods[$method])) {
97 // If the method name starts with a whitelisted prefix, allow it.
98 // Note: strpos() is between 3x and 7x faster than preg_match in this case.
99 foreach ($this->whitelisted_prefixes as $prefix) {
100 if (strpos($method, $prefix) === 0) {
105 throw new \Twig_Sandbox_SecurityError(sprintf('Calling "%s" method on a "%s" object is not allowed.', $method, get_class($obj)));