Python WSGI 应用程序中的以下代码片段是否可以避免目录遍历?它读取作为参数传递的文件名并返回命名文件。
file_name = request.path_params["file"]
file = open(file_name, "rb")
mime_type = mimetypes.guess_type(file_name)[0]
start_response(status.OK, [('Content-Type', mime_type)])
return file
我将应用程序安装在下面http://localhost:8000/file/{file}
,并使用 URLhttp://localhost:8000/file/../alarm.gif
和http://localhost:8000/file/%2e%2e%2falarm.gif
. 但是我的任何尝试都没有交付(现有)文件。那么我的代码是否已经不受目录遍历的影响?
新的方法
以下代码似乎阻止了目录遍历:
file_name = request.path_params["file"]
absolute_path = os.path.join(self.base_directory, file_name)
normalized_path = os.path.normpath(absolute_path)
# security check to prevent directory traversal
if not normalized_path.startswith(self.base_directory):
raise IOError()
file = open(normalized_path, "rb")
mime_type = mimetypes.guess_type(normalized_path)[0]
start_response(status.OK, [('Content-Type', mime_type)])
return file