More accurately match paths in safe path example

As was pointed out in a bug report, the example for safe path
matching should not be comparing substrings, but actual path
components. As OpenStack projects currently no longer support Python
interpreter versions prior to 3.5, we can take advantage of
os.path.commonpath() for confirming this correctly.

Change-Id: I3f8d3760daceb9e62396ae21b0d915ae07eff303
Closes-Bug: #1815422
This commit is contained in:
Jeremy Stanley 2021-01-21 16:53:50 +00:00
parent fc1a66d398
commit 0e4118d19e
1 changed files with 6 additions and 5 deletions

View File

@ -79,11 +79,12 @@ defeat path traversal.
import sys
def is_safe_path(basedir, path, follow_symlinks=True):
# resolves symbolic links
if follow_symlinks:
return os.path.realpath(path).startswith(basedir)
return os.path.abspath(path).startswith(basedir)
# 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))
def main(args):