External variable 'template_path' used in file path
76 win_year, win_half_year = _get_trading_periods(periods_per_year)
77
78 tpl = ""
79 with open(template_path or __file__[:-4] + ".html") as f: 80 tpl = f.read()
81 f.close()
82
Description
Python's open()
function can take in a relative or absolute path and read its file contents.
If a user is provided direct access to the path that is opened, it can have serious security risks.
Bad practice
def read_file(path):
with open(os.path.join('some/path', path)) as f:
f.read()
# Someone can exploit `read_file` and see your secrets this way:
read_file('../../../secrets.txt')
Recommended
Either use a static path:
def read_file(path):
with open('some/path/to/file.txt') as f:
f.read()
Or, do some kind of validation to make sure you're not allowing arbitrary file access:
def read_file(filename):
if filename not in ('x.txt', 'y.txt'):
return 'Invalid filename'
with open(os.path.join('some/path', path)) as f:
f.read()
References
- OWASP Top 10 2021 Category A01 - Broken Access Control
- OWASP Top 10 2021 Category A04 - Insecure Design
- CWE-73 External Control of File Name or Path