Affected versions
Twig versions >=3.15.0, <3.31.0 are affected by this security issue.
The issue has been fixed in Twig 3.31.0.
Description
The guard tag compiles only one of its branches, depending on whether a callable exists. The other branch was still parsed, though. The extends, use, macro and block tags in it registered their effects on the template. The sandbox doesn't see these tags, since that branch isn't compiled. A sandboxed template allowed to use guard could therefore extend a template, import blocks and define macros, while the policy doesn't allow these tags:
1
{% guard filter upper %}{% else %}{% extends "parent.html" %}{% endguard %}
The templates reached this way come from the loader of the sandbox, and they are sandboxed too.
Resolution
What the branch that isn't selected registers on the parser is now discarded.
The patch for this issue is available here for branch 3.x.
Credits
We would like to thank Fabien Potencier for reporting the issue and providing the fix.