86
87 """
88 fn_truncated = "%s/truncated_%i_%s" % (tmpdir, nline, os.path.basename(fn_orig))
89 with open(fn_orig) as f_orig, open(fn_truncated, "w") as f_truncated: 90 for counter, line in enumerate(f_orig):
91 if counter >= nline:
92 break
440
441 """
442 input_module = _select_input_module(filename, fmt)
443 with open(filename, "w") as fh:444 try:
445 input_module.write_input(fh, data, template, atom_line, **kwargs)
446 except Exception as exc:
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.
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')
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()