2021-10-26 21:41:14 +02:00
|
|
|
import os
|
|
|
|
|
2022-02-20 09:09:02 +01:00
|
|
|
|
2023-07-09 12:38:03 +02:00
|
|
|
class SuspiciousFileOperationError(Exception):
|
2021-10-26 21:41:14 +02:00
|
|
|
pass
|
|
|
|
|
2022-02-20 09:09:02 +01:00
|
|
|
|
2021-10-26 21:41:14 +02: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):
|
2023-07-09 12:38:03 +02:00
|
|
|
raise SuspiciousFileOperationError(f"{unsafe_path} is not safe")
|
2021-10-26 21:41:14 +02:00
|
|
|
|
|
|
|
# Passes the check
|
2023-07-09 12:38:03 +02:00
|
|
|
return unsafe_path
|