test_security.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  1. # -*- coding: utf-8 -*-
  2. import pytest
  3. from jinja2 import Environment
  4. from jinja2 import escape
  5. from jinja2 import Markup
  6. from jinja2._compat import text_type
  7. from jinja2.exceptions import SecurityError
  8. from jinja2.exceptions import TemplateRuntimeError
  9. from jinja2.exceptions import TemplateSyntaxError
  10. from jinja2.nodes import EvalContext
  11. from jinja2.sandbox import ImmutableSandboxedEnvironment
  12. from jinja2.sandbox import SandboxedEnvironment
  13. from jinja2.sandbox import unsafe
  14. class PrivateStuff(object):
  15. def bar(self):
  16. return 23
  17. @unsafe
  18. def foo(self):
  19. return 42
  20. def __repr__(self):
  21. return "PrivateStuff"
  22. class PublicStuff(object):
  23. def bar(self):
  24. return 23
  25. def _foo(self):
  26. return 42
  27. def __repr__(self):
  28. return "PublicStuff"
  29. class TestSandbox(object):
  30. def test_unsafe(self, env):
  31. env = SandboxedEnvironment()
  32. pytest.raises(
  33. SecurityError, env.from_string("{{ foo.foo() }}").render, foo=PrivateStuff()
  34. )
  35. assert env.from_string("{{ foo.bar() }}").render(foo=PrivateStuff()) == "23"
  36. pytest.raises(
  37. SecurityError, env.from_string("{{ foo._foo() }}").render, foo=PublicStuff()
  38. )
  39. assert env.from_string("{{ foo.bar() }}").render(foo=PublicStuff()) == "23"
  40. assert env.from_string("{{ foo.__class__ }}").render(foo=42) == ""
  41. assert env.from_string("{{ foo.func_code }}").render(foo=lambda: None) == ""
  42. # security error comes from __class__ already.
  43. pytest.raises(
  44. SecurityError,
  45. env.from_string("{{ foo.__class__.__subclasses__() }}").render,
  46. foo=42,
  47. )
  48. def test_immutable_environment(self, env):
  49. env = ImmutableSandboxedEnvironment()
  50. pytest.raises(SecurityError, env.from_string("{{ [].append(23) }}").render)
  51. pytest.raises(SecurityError, env.from_string("{{ {1:2}.clear() }}").render)
  52. def test_restricted(self, env):
  53. env = SandboxedEnvironment()
  54. pytest.raises(
  55. TemplateSyntaxError,
  56. env.from_string,
  57. "{% for item.attribute in seq %}...{% endfor %}",
  58. )
  59. pytest.raises(
  60. TemplateSyntaxError,
  61. env.from_string,
  62. "{% for foo, bar.baz in seq %}...{% endfor %}",
  63. )
  64. def test_markup_operations(self, env):
  65. # adding two strings should escape the unsafe one
  66. unsafe = '<script type="application/x-some-script">alert("foo");</script>'
  67. safe = Markup("<em>username</em>")
  68. assert unsafe + safe == text_type(escape(unsafe)) + text_type(safe)
  69. # string interpolations are safe to use too
  70. assert Markup("<em>%s</em>") % "<bad user>" == "<em>&lt;bad user&gt;</em>"
  71. assert (
  72. Markup("<em>%(username)s</em>") % {"username": "<bad user>"}
  73. == "<em>&lt;bad user&gt;</em>"
  74. )
  75. # an escaped object is markup too
  76. assert type(Markup("foo") + "bar") is Markup
  77. # and it implements __html__ by returning itself
  78. x = Markup("foo")
  79. assert x.__html__() is x
  80. # it also knows how to treat __html__ objects
  81. class Foo(object):
  82. def __html__(self):
  83. return "<em>awesome</em>"
  84. def __unicode__(self):
  85. return "awesome"
  86. assert Markup(Foo()) == "<em>awesome</em>"
  87. assert (
  88. Markup("<strong>%s</strong>") % Foo() == "<strong><em>awesome</em></strong>"
  89. )
  90. # escaping and unescaping
  91. assert escape("\"<>&'") == "&#34;&lt;&gt;&amp;&#39;"
  92. assert Markup("<em>Foo &amp; Bar</em>").striptags() == "Foo & Bar"
  93. assert Markup("&lt;test&gt;").unescape() == "<test>"
  94. def test_template_data(self, env):
  95. env = Environment(autoescape=True)
  96. t = env.from_string(
  97. "{% macro say_hello(name) %}"
  98. "<p>Hello {{ name }}!</p>{% endmacro %}"
  99. '{{ say_hello("<blink>foo</blink>") }}'
  100. )
  101. escaped_out = "<p>Hello &lt;blink&gt;foo&lt;/blink&gt;!</p>"
  102. assert t.render() == escaped_out
  103. assert text_type(t.module) == escaped_out
  104. assert escape(t.module) == escaped_out
  105. assert t.module.say_hello("<blink>foo</blink>") == escaped_out
  106. assert (
  107. escape(t.module.say_hello(EvalContext(env), "<blink>foo</blink>"))
  108. == escaped_out
  109. )
  110. assert escape(t.module.say_hello("<blink>foo</blink>")) == escaped_out
  111. def test_attr_filter(self, env):
  112. env = SandboxedEnvironment()
  113. tmpl = env.from_string('{{ cls|attr("__subclasses__")() }}')
  114. pytest.raises(SecurityError, tmpl.render, cls=int)
  115. def test_binary_operator_intercepting(self, env):
  116. def disable_op(left, right):
  117. raise TemplateRuntimeError("that operator so does not work")
  118. for expr, ctx, rv in ("1 + 2", {}, "3"), ("a + 2", {"a": 2}, "4"):
  119. env = SandboxedEnvironment()
  120. env.binop_table["+"] = disable_op
  121. t = env.from_string("{{ %s }}" % expr)
  122. assert t.render(ctx) == rv
  123. env.intercepted_binops = frozenset(["+"])
  124. t = env.from_string("{{ %s }}" % expr)
  125. with pytest.raises(TemplateRuntimeError):
  126. t.render(ctx)
  127. def test_unary_operator_intercepting(self, env):
  128. def disable_op(arg):
  129. raise TemplateRuntimeError("that operator so does not work")
  130. for expr, ctx, rv in ("-1", {}, "-1"), ("-a", {"a": 2}, "-2"):
  131. env = SandboxedEnvironment()
  132. env.unop_table["-"] = disable_op
  133. t = env.from_string("{{ %s }}" % expr)
  134. assert t.render(ctx) == rv
  135. env.intercepted_unops = frozenset(["-"])
  136. t = env.from_string("{{ %s }}" % expr)
  137. with pytest.raises(TemplateRuntimeError):
  138. t.render(ctx)
  139. class TestStringFormat(object):
  140. def test_basic_format_safety(self):
  141. env = SandboxedEnvironment()
  142. t = env.from_string('{{ "a{0.__class__}b".format(42) }}')
  143. assert t.render() == "ab"
  144. def test_basic_format_all_okay(self):
  145. env = SandboxedEnvironment()
  146. t = env.from_string('{{ "a{0.foo}b".format({"foo": 42}) }}')
  147. assert t.render() == "a42b"
  148. def test_safe_format_safety(self):
  149. env = SandboxedEnvironment()
  150. t = env.from_string('{{ ("a{0.__class__}b{1}"|safe).format(42, "<foo>") }}')
  151. assert t.render() == "ab&lt;foo&gt;"
  152. def test_safe_format_all_okay(self):
  153. env = SandboxedEnvironment()
  154. t = env.from_string('{{ ("a{0.foo}b{1}"|safe).format({"foo": 42}, "<foo>") }}')
  155. assert t.render() == "a42b&lt;foo&gt;"
  156. @pytest.mark.skipif(
  157. not hasattr(str, "format_map"), reason="requires str.format_map method"
  158. )
  159. class TestStringFormatMap(object):
  160. def test_basic_format_safety(self):
  161. env = SandboxedEnvironment()
  162. t = env.from_string('{{ "a{x.__class__}b".format_map({"x":42}) }}')
  163. assert t.render() == "ab"
  164. def test_basic_format_all_okay(self):
  165. env = SandboxedEnvironment()
  166. t = env.from_string('{{ "a{x.foo}b".format_map({"x":{"foo": 42}}) }}')
  167. assert t.render() == "a42b"
  168. def test_safe_format_all_okay(self):
  169. env = SandboxedEnvironment()
  170. t = env.from_string(
  171. '{{ ("a{x.foo}b{y}"|safe).format_map({"x":{"foo": 42}, "y":"<foo>"}) }}'
  172. )
  173. assert t.render() == "a42b&lt;foo&gt;"