Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 87d2750

Browse files
committed
[1.4.x] Prevented arbitrary file inclusion with {% ssi %} tag and relative paths.
Thanks Rainer Koirikivi for the report and draft patch. This is a security fix; disclosure to follow shortly. Backport of 7fe5b65 from master
1 parent 9ab7ed9 commit 87d2750

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed

django/template/defaulttags.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
"""Default tags used by the template system, available to all templates."""
22

3+
import os
34
import sys
45
import re
56
from datetime import datetime
@@ -309,6 +310,7 @@ def render(self, context):
309310
return ''
310311

311312
def include_is_allowed(filepath):
313+
filepath = os.path.abspath(filepath)
312314
for root in settings.ALLOWED_INCLUDE_ROOTS:
313315
if filepath.startswith(root):
314316
return True

tests/regressiontests/templates/tests.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1764,3 +1764,34 @@ def test_include_only(self):
17641764
template.Template('{% include "child" only %}').render(ctx),
17651765
'none'
17661766
)
1767+
1768+
1769+
class SSITests(unittest.TestCase):
1770+
def setUp(self):
1771+
self.this_dir = os.path.dirname(os.path.abspath(__file__))
1772+
self.ssi_dir = os.path.join(self.this_dir, "templates", "first")
1773+
1774+
def render_ssi(self, path):
1775+
# the path must exist for the test to be reliable
1776+
self.assertTrue(os.path.exists(path))
1777+
return template.Template('{%% ssi %s %%}' % path).render(Context())
1778+
1779+
def test_allowed_paths(self):
1780+
acceptable_path = os.path.join(self.ssi_dir, "..", "first", "test.html")
1781+
with override_settings(ALLOWED_INCLUDE_ROOTS=(self.ssi_dir,)):
1782+
self.assertEqual(self.render_ssi(acceptable_path), 'First template\n')
1783+
1784+
def test_relative_include_exploit(self):
1785+
"""
1786+
May not bypass ALLOWED_INCLUDE_ROOTS with relative paths
1787+
1788+
e.g. if ALLOWED_INCLUDE_ROOTS = ("/var/www",), it should not be
1789+
possible to do {% ssi "/var/www/../../etc/passwd" %}
1790+
"""
1791+
disallowed_paths = [
1792+
os.path.join(self.ssi_dir, "..", "ssi_include.html"),
1793+
os.path.join(self.ssi_dir, "..", "second", "test.html"),
1794+
]
1795+
with override_settings(ALLOWED_INCLUDE_ROOTS=(self.ssi_dir,)):
1796+
for path in disallowed_paths:
1797+
self.assertEqual(self.render_ssi(path), '')

0 commit comments

Comments
 (0)