2021-10-26 19:41:14 +00:00
|
|
|
import os
|
|
|
|
|
2022-02-20 08:09:02 +00:00
|
|
|
|
2021-10-26 19:41:14 +00:00
|
|
|
class SuspiciousFileOperation(Exception):
|
|
|
|
pass
|
|
|
|
|
2022-02-20 08:09:02 +00:00
|
|
|
|
2021-10-26 19:41:14 +00:00
|
|
|
def path_traversal_check(unsafe_path, known_safe_path):
|
|
|
|
known_safe_path = os.path.abspath(known_safe_path)
|
|
|
|
unsafe_path = os.path.abspath(unsafe_path)
|
|
|
|
|
|
|
|
if (os.path.commonprefix([known_safe_path, unsafe_path]) != known_safe_path):
|
|
|
|
raise SuspiciousFileOperation("{} is not safe".format(unsafe_path))
|
|
|
|
|
|
|
|
# Passes the check
|
|
|
|
return unsafe_path
|