Skip to content

Commit

Permalink
Python: Use a Jinja2 sandboxed env to prevent running unsafe code. (m…
Browse files Browse the repository at this point in the history
…icrosoft#6163)

### Motivation and Context

The `Jinja2PromptTemplate` allows users to integrate `Jinja2` as `Prompt
engine` within a `semantic-kernel` structure LLM application.
Nevertheless, `Jinja2PromptTemplate` directly takes **sandbox-less**
`jinja2.Environment` as `Jinja2 Environment`, allowing attackers to
escape and call arbitrary `__builtins__` methods such as `os.Popen`,
resulting possible RCE or further exploitations.

<!-- Thank you for your contribution to the semantic-kernel repo!
Please help reviewers and future users, providing the following
information:
  1. Why is this change required?
  2. What problem does it solve?
  3. What scenario does it contribute to?
  4. If it fixes an open issue, please link to the issue here.
-->

### Description

This PR fixes this by implementing a SandboxedEnvironment to prevent
users from being able to run malicious code.
- All tests passing.

<!-- Describe your changes, the overall approach, the underlying design.
These notes will help understanding how your code works. Thanks! -->

### Contribution Checklist

<!-- Before submitting this PR, please make sure: -->

- [X] The code builds clean without any errors or warnings
- [X] The PR follows the [SK Contribution
Guidelines](https:/microsoft/semantic-kernel/blob/main/CONTRIBUTING.md)
and the [pre-submission formatting
script](https:/microsoft/semantic-kernel/blob/main/CONTRIBUTING.md#development-scripts)
raises no violations
- [X] All unit tests pass, and I have added new tests where possible
- [X] I didn't break anyone 😄
  • Loading branch information
moonbox3 authored May 8, 2024
1 parent 6ff750c commit a983855
Showing 1 changed file with 4 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@
import logging
from typing import TYPE_CHECKING, Any, Optional

from jinja2 import BaseLoader, Environment, TemplateError
from jinja2 import BaseLoader, TemplateError
from jinja2.sandbox import ImmutableSandboxedEnvironment
from pydantic import PrivateAttr, field_validator

from semantic_kernel.exceptions import Jinja2TemplateRenderException, Jinja2TemplateSyntaxError
Expand Down Expand Up @@ -43,7 +44,7 @@ class Jinja2PromptTemplate(PromptTemplateBase):
Jinja2TemplateSyntaxError: If there is a syntax error in the Jinja2 template.
"""

_env: Environment = PrivateAttr()
_env: ImmutableSandboxedEnvironment = PrivateAttr()

@field_validator("prompt_template_config")
@classmethod
Expand All @@ -57,7 +58,7 @@ def model_post_init(self, __context: Any) -> None:
self._env = None
return
try:
self._env = Environment(loader=BaseLoader())
self._env = ImmutableSandboxedEnvironment(loader=BaseLoader())
except TemplateError as e:
logger.error(f"Invalid jinja2 template: {self.prompt_template_config.template}")
raise Jinja2TemplateSyntaxError(f"Invalid jinja2 template: {self.prompt_template_config.template}") from e
Expand Down

0 comments on commit a983855

Please sign in to comment.