elapouya / python-docx-template

Use a docx as a jinja2 template
GNU Lesser General Public License v2.1
1.92k stars 378 forks source link

Remote Code Execution over Server-Side Template Injection #549

Open StevenMapes opened 1 week ago

StevenMapes commented 1 week ago

Describe the bug

The use of from jinja2 import Environment over from jinja2.sandbox import SandboxedEnvironment by default means that this package suffers from a Remote Code Execution (RCE) vulnerability through Server-Side Template Injection (SSTI) allowing an attacker to execute arbitrary code on the server by exploiting the template system used to render dynamic content. This vulnerability arises when a server allows untrusted data input into a template without proper validation or sanitization.

To Reproduce

Create a docx template file and add the following entry {{ ''.__class__.__mro__[1].__subclasses__()[389](['id'], stdout=-1).communicate()[0].decode('utf-8') }}

{ get_flashed_messages.__class__.__mro__[1].__subclasses__()[90] }}

Expected behavior

A SecurityError should be raised.

Additional context

You can resolve this by passing the SandboxedEnvironment into the render method of the DocxTemplate class. By doing this Jinja2 will then raise a SecurityError but please consider swapping the default use of Environment over to use the Sandboxed one or add instructions and warnings to the project relating to this,

Jinja2 reference: https://jinja.palletsprojects.com/en/3.1.x/sandbox/#security-considerations.