general_hardcoded_tmp.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. #
  2. # Copyright 2014 Hewlett-Packard Development Company, L.P.
  3. #
  4. # SPDX-License-Identifier: Apache-2.0
  5. r"""
  6. ===================================================
  7. B108: Test for insecure usage of tmp file/directory
  8. ===================================================
  9. Safely creating a temporary file or directory means following a number of rules
  10. (see the references for more details). This plugin test looks for strings
  11. starting with (configurable) commonly used temporary paths, for example:
  12. - /tmp
  13. - /var/tmp
  14. - /dev/shm
  15. - etc
  16. **Config Options:**
  17. This test plugin takes a similarly named config block,
  18. `hardcoded_tmp_directory`. The config block provides a Python list, `tmp_dirs`,
  19. that lists string fragments indicating possible temporary file paths. Any
  20. string starting with one of these fragments will report a MEDIUM confidence
  21. issue.
  22. .. code-block:: yaml
  23. hardcoded_tmp_directory:
  24. tmp_dirs: ['/tmp', '/var/tmp', '/dev/shm']
  25. :Example:
  26. .. code-block: none
  27. >> Issue: Probable insecure usage of temp file/directory.
  28. Severity: Medium Confidence: Medium
  29. CWE: CWE-377 (https://cwe.mitre.org/data/definitions/377.html)
  30. Location: ./examples/hardcoded-tmp.py:1
  31. 1 f = open('/tmp/abc', 'w')
  32. 2 f.write('def')
  33. .. seealso::
  34. - https://security.openstack.org/guidelines/dg_using-temporary-files-securely.html
  35. - https://cwe.mitre.org/data/definitions/377.html
  36. .. versionadded:: 0.9.0
  37. .. versionchanged:: 1.7.3
  38. CWE information added
  39. """ # noqa: E501
  40. import bandit
  41. from bandit.core import issue
  42. from bandit.core import test_properties as test
  43. def gen_config(name):
  44. if name == "hardcoded_tmp_directory":
  45. return {"tmp_dirs": ["/tmp", "/var/tmp", "/dev/shm"]}
  46. @test.takes_config
  47. @test.checks("Str")
  48. @test.test_id("B108")
  49. def hardcoded_tmp_directory(context, config):
  50. if config is not None and "tmp_dirs" in config:
  51. tmp_dirs = config["tmp_dirs"]
  52. else:
  53. tmp_dirs = ["/tmp", "/var/tmp", "/dev/shm"]
  54. if any(context.string_val.startswith(s) for s in tmp_dirs):
  55. return bandit.Issue(
  56. severity=bandit.MEDIUM,
  57. confidence=bandit.MEDIUM,
  58. cwe=issue.Cwe.INSECURE_TEMP_FILE,
  59. text="Probable insecure usage of temp file/directory.",
  60. )