mako_templates.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. #
  2. # SPDX-License-Identifier: Apache-2.0
  3. r"""
  4. ====================================
  5. B702: Test for use of mako templates
  6. ====================================
  7. Mako is a Python templating system often used to build web applications. It is
  8. the default templating system used in Pylons and Pyramid. Unlike Jinja2 (an
  9. alternative templating system), Mako has no environment wide variable escaping
  10. mechanism. Because of this, all input variables must be carefully escaped
  11. before use to prevent possible vulnerabilities to Cross Site Scripting (XSS)
  12. attacks.
  13. :Example:
  14. .. code-block:: none
  15. >> Issue: Mako templates allow HTML/JS rendering by default and are
  16. inherently open to XSS attacks. Ensure variables in all templates are
  17. properly sanitized via the 'n', 'h' or 'x' flags (depending on context).
  18. For example, to HTML escape the variable 'data' do ${ data |h }.
  19. Severity: Medium Confidence: High
  20. CWE: CWE-80 (https://cwe.mitre.org/data/definitions/80.html)
  21. Location: ./examples/mako_templating.py:10
  22. 9
  23. 10 mako.template.Template("hern")
  24. 11 template.Template("hern")
  25. .. seealso::
  26. - https://www.makotemplates.org/
  27. - `OWASP XSS <https://owasp.org/www-community/attacks/xss/>`_
  28. - https://security.openstack.org/guidelines/dg_cross-site-scripting-xss.html
  29. - https://cwe.mitre.org/data/definitions/80.html
  30. .. versionadded:: 0.10.0
  31. .. versionchanged:: 1.7.3
  32. CWE information added
  33. """
  34. import bandit
  35. from bandit.core import issue
  36. from bandit.core import test_properties as test
  37. @test.checks("Call")
  38. @test.test_id("B702")
  39. def use_of_mako_templates(context):
  40. # check type just to be safe
  41. if isinstance(context.call_function_name_qual, str):
  42. qualname_list = context.call_function_name_qual.split(".")
  43. func = qualname_list[-1]
  44. if "mako" in qualname_list and func == "Template":
  45. # unlike Jinja2, mako does not have a template wide autoescape
  46. # feature and thus each variable must be carefully sanitized.
  47. return bandit.Issue(
  48. severity=bandit.MEDIUM,
  49. confidence=bandit.HIGH,
  50. cwe=issue.Cwe.BASIC_XSS,
  51. text="Mako templates allow HTML/JS rendering by default and "
  52. "are inherently open to XSS attacks. Ensure variables "
  53. "in all templates are properly sanitized via the 'n', "
  54. "'h' or 'x' flags (depending on context). For example, "
  55. "to HTML escape the variable 'data' do ${ data |h }.",
  56. )