test_security.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  1. import pytest
  2. from markupsafe import escape
  3. from jinja2 import Environment
  4. from jinja2.exceptions import SecurityError
  5. from jinja2.exceptions import TemplateRuntimeError
  6. from jinja2.exceptions import TemplateSyntaxError
  7. from jinja2.nodes import EvalContext
  8. from jinja2.sandbox import ImmutableSandboxedEnvironment
  9. from jinja2.sandbox import SandboxedEnvironment
  10. from jinja2.sandbox import unsafe
  11. class PrivateStuff:
  12. def bar(self):
  13. return 23
  14. @unsafe
  15. def foo(self):
  16. return 42
  17. def __repr__(self):
  18. return "PrivateStuff"
  19. class PublicStuff:
  20. def bar(self):
  21. return 23
  22. def _foo(self):
  23. return 42
  24. def __repr__(self):
  25. return "PublicStuff"
  26. class TestSandbox:
  27. def test_unsafe(self, env):
  28. env = SandboxedEnvironment()
  29. pytest.raises(
  30. SecurityError, env.from_string("{{ foo.foo() }}").render, foo=PrivateStuff()
  31. )
  32. assert env.from_string("{{ foo.bar() }}").render(foo=PrivateStuff()) == "23"
  33. pytest.raises(
  34. SecurityError, env.from_string("{{ foo._foo() }}").render, foo=PublicStuff()
  35. )
  36. assert env.from_string("{{ foo.bar() }}").render(foo=PublicStuff()) == "23"
  37. assert env.from_string("{{ foo.__class__ }}").render(foo=42) == ""
  38. assert env.from_string("{{ foo.func_code }}").render(foo=lambda: None) == ""
  39. # security error comes from __class__ already.
  40. pytest.raises(
  41. SecurityError,
  42. env.from_string("{{ foo.__class__.__subclasses__() }}").render,
  43. foo=42,
  44. )
  45. def test_immutable_environment(self, env):
  46. env = ImmutableSandboxedEnvironment()
  47. pytest.raises(SecurityError, env.from_string("{{ [].append(23) }}").render)
  48. pytest.raises(SecurityError, env.from_string("{{ {1:2}.clear() }}").render)
  49. def test_restricted(self, env):
  50. env = SandboxedEnvironment()
  51. pytest.raises(
  52. TemplateSyntaxError,
  53. env.from_string,
  54. "{% for item.attribute in seq %}...{% endfor %}",
  55. )
  56. pytest.raises(
  57. TemplateSyntaxError,
  58. env.from_string,
  59. "{% for foo, bar.baz in seq %}...{% endfor %}",
  60. )
  61. def test_template_data(self, env):
  62. env = Environment(autoescape=True)
  63. t = env.from_string(
  64. "{% macro say_hello(name) %}"
  65. "<p>Hello {{ name }}!</p>{% endmacro %}"
  66. '{{ say_hello("<blink>foo</blink>") }}'
  67. )
  68. escaped_out = "<p>Hello &lt;blink&gt;foo&lt;/blink&gt;!</p>"
  69. assert t.render() == escaped_out
  70. assert str(t.module) == escaped_out
  71. assert escape(t.module) == escaped_out
  72. assert t.module.say_hello("<blink>foo</blink>") == escaped_out
  73. assert (
  74. escape(t.module.say_hello(EvalContext(env), "<blink>foo</blink>"))
  75. == escaped_out
  76. )
  77. assert escape(t.module.say_hello("<blink>foo</blink>")) == escaped_out
  78. def test_attr_filter(self, env):
  79. env = SandboxedEnvironment()
  80. tmpl = env.from_string('{{ cls|attr("__subclasses__")() }}')
  81. pytest.raises(SecurityError, tmpl.render, cls=int)
  82. def test_binary_operator_intercepting(self, env):
  83. def disable_op(left, right):
  84. raise TemplateRuntimeError("that operator so does not work")
  85. for expr, ctx, rv in ("1 + 2", {}, "3"), ("a + 2", {"a": 2}, "4"):
  86. env = SandboxedEnvironment()
  87. env.binop_table["+"] = disable_op
  88. t = env.from_string(f"{{{{ {expr} }}}}")
  89. assert t.render(ctx) == rv
  90. env.intercepted_binops = frozenset(["+"])
  91. t = env.from_string(f"{{{{ {expr} }}}}")
  92. with pytest.raises(TemplateRuntimeError):
  93. t.render(ctx)
  94. def test_unary_operator_intercepting(self, env):
  95. def disable_op(arg):
  96. raise TemplateRuntimeError("that operator so does not work")
  97. for expr, ctx, rv in ("-1", {}, "-1"), ("-a", {"a": 2}, "-2"):
  98. env = SandboxedEnvironment()
  99. env.unop_table["-"] = disable_op
  100. t = env.from_string(f"{{{{ {expr} }}}}")
  101. assert t.render(ctx) == rv
  102. env.intercepted_unops = frozenset(["-"])
  103. t = env.from_string(f"{{{{ {expr} }}}}")
  104. with pytest.raises(TemplateRuntimeError):
  105. t.render(ctx)
  106. class TestStringFormat:
  107. def test_basic_format_safety(self):
  108. env = SandboxedEnvironment()
  109. t = env.from_string('{{ "a{0.__class__}b".format(42) }}')
  110. assert t.render() == "ab"
  111. def test_basic_format_all_okay(self):
  112. env = SandboxedEnvironment()
  113. t = env.from_string('{{ "a{0.foo}b".format({"foo": 42}) }}')
  114. assert t.render() == "a42b"
  115. def test_safe_format_safety(self):
  116. env = SandboxedEnvironment()
  117. t = env.from_string('{{ ("a{0.__class__}b{1}"|safe).format(42, "<foo>") }}')
  118. assert t.render() == "ab&lt;foo&gt;"
  119. def test_safe_format_all_okay(self):
  120. env = SandboxedEnvironment()
  121. t = env.from_string('{{ ("a{0.foo}b{1}"|safe).format({"foo": 42}, "<foo>") }}')
  122. assert t.render() == "a42b&lt;foo&gt;"
  123. def test_empty_braces_format(self):
  124. env = SandboxedEnvironment()
  125. t1 = env.from_string('{{ ("a{}b{}").format("foo", "42")}}')
  126. t2 = env.from_string('{{ ("a{}b{}"|safe).format(42, "<foo>") }}')
  127. assert t1.render() == "afoob42"
  128. assert t2.render() == "a42b&lt;foo&gt;"
  129. class TestStringFormatMap:
  130. def test_basic_format_safety(self):
  131. env = SandboxedEnvironment()
  132. t = env.from_string('{{ "a{x.__class__}b".format_map({"x":42}) }}')
  133. assert t.render() == "ab"
  134. def test_basic_format_all_okay(self):
  135. env = SandboxedEnvironment()
  136. t = env.from_string('{{ "a{x.foo}b".format_map({"x":{"foo": 42}}) }}')
  137. assert t.render() == "a42b"
  138. def test_safe_format_all_okay(self):
  139. env = SandboxedEnvironment()
  140. t = env.from_string(
  141. '{{ ("a{x.foo}b{y}"|safe).format_map({"x":{"foo": 42}, "y":"<foo>"}) }}'
  142. )
  143. assert t.render() == "a42b&lt;foo&gt;"