以下代码片段来自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}
下,并使用以下 URL 发送请求:http://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