https://security.openstack.org/guidelines/dg_using-file-paths.html
If I try to run the given code from the above link:
import os
def is_safe_path(basedir, path, follow_symlinks=True):
# resolves symbolic links
if follow_symlinks:
matchpath = os.path.realpath(path).startswith(basedir)
else:
matchpath = os.path.abspath(path).startswith(basedir)
return basedir == os.path.commonpath((basedir, matchpath))
is_safe_path('/test', '/test/../abc')
It clearly does not work:
$ python
Python 3.8.8 (default, Mar 4 2021, 21:24:42)
[GCC 10.2.0] on cygwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>>
>>> def is_safe_path(basedir, path, follow_symlinks=True):
... # resolves symbolic links
... if follow_symlinks:
... matchpath = os.path.realpath(path).startswith(basedir)
... else:
... matchpath = os.path.abspath(path).startswith(basedir)
... return basedir == os.path.commonpath((basedir, matchpath))
...
>>> is_safe_path('/test', '/test/../abc')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 7, in is_safe_path
File "/usr/lib/python3.8/posixpath.py", line 496, in commonpath
paths = tuple(map(os.fspath, paths))
TypeError: expected str, bytes or os.PathLike object, not bool
What's the spurious bit of code here?
Should the .startswith()
be removed?
Am I totally misunderstanding what the purpose of having a boolean in the tuple is?
I found the edit where this was changed:
https://bugs.launchpad.net/ossa/+bug/1815422 https://review.opendev.org/c/openstack/ossa/+/771854/
This is a typo in the code, .startswith(basedir)
isn't meant to follow realpath
or abspath
. Most likely a copy and paste issue to be honest. I would highly recommend that you submit a fix for the issue!