xml.py 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. #
  2. # SPDX-License-Identifier: Apache-2.0
  3. r"""
  4. =============
  5. XML Formatter
  6. =============
  7. This formatter outputs the issues as XML.
  8. :Example:
  9. .. code-block:: xml
  10. <?xml version='1.0' encoding='utf-8'?>
  11. <testsuite name="bandit" tests="1"><testcase
  12. classname="examples/yaml_load.py" name="blacklist_calls"><error
  13. message="Use of unsafe yaml load. Allows instantiation of arbitrary
  14. objects. Consider yaml.safe_load().&#10;" type="MEDIUM"
  15. more_info="https://bandit.readthedocs.io/en/latest/">Test ID: B301
  16. Severity: MEDIUM Confidence: HIGH
  17. CWE: CWE-20 (https://cwe.mitre.org/data/definitions/20.html) Use of unsafe
  18. yaml load.
  19. Allows instantiation of arbitrary objects. Consider yaml.safe_load().
  20. Location examples/yaml_load.py:5</error></testcase></testsuite>
  21. .. versionadded:: 0.12.0
  22. .. versionchanged:: 1.5.0
  23. New field `more_info` added to output
  24. .. versionchanged:: 1.7.3
  25. New field `CWE` added to output
  26. """
  27. import logging
  28. import sys
  29. from xml.etree import cElementTree as ET
  30. from bandit.core import docs_utils
  31. LOG = logging.getLogger(__name__)
  32. def report(manager, fileobj, sev_level, conf_level, lines=-1):
  33. """Prints issues in XML format
  34. :param manager: the bandit manager object
  35. :param fileobj: The output file object, which may be sys.stdout
  36. :param sev_level: Filtering severity level
  37. :param conf_level: Filtering confidence level
  38. :param lines: Number of lines to report, -1 for all
  39. """
  40. issues = manager.get_issue_list(sev_level=sev_level, conf_level=conf_level)
  41. root = ET.Element("testsuite", name="bandit", tests=str(len(issues)))
  42. for issue in issues:
  43. test = issue.test
  44. testcase = ET.SubElement(
  45. root, "testcase", classname=issue.fname, name=test
  46. )
  47. text = (
  48. "Test ID: %s Severity: %s Confidence: %s\nCWE: %s\n%s\n"
  49. "Location %s:%s"
  50. )
  51. text = text % (
  52. issue.test_id,
  53. issue.severity,
  54. issue.confidence,
  55. issue.cwe,
  56. issue.text,
  57. issue.fname,
  58. issue.lineno,
  59. )
  60. ET.SubElement(
  61. testcase,
  62. "error",
  63. more_info=docs_utils.get_url(issue.test_id),
  64. type=issue.severity,
  65. message=issue.text,
  66. ).text = text
  67. tree = ET.ElementTree(root)
  68. if fileobj.name == sys.stdout.name:
  69. fileobj = sys.stdout.buffer
  70. elif fileobj.mode == "w":
  71. fileobj.close()
  72. fileobj = open(fileobj.name, "wb")
  73. with fileobj:
  74. tree.write(fileobj, encoding="utf-8", xml_declaration=True)
  75. if fileobj.name != sys.stdout.name:
  76. LOG.info("XML output written to file: %s", fileobj.name)