因此,我接到了修复基本 Java Web 应用程序中的路径遍历问题的任务,但我陷入了困境。我们的目的是从本质上确保代码是安全的,同时维护功能(这是我正在努力解决的部分)
到目前为止,我已经在网上查看了如何解决我收到的问题,并且我设法解决了这些问题,但是测试代码的机器人返回一条消息,指出该应用程序不再具有功能,但很安全。
我收到的 2 个错误如下:
1) FileDownload 中的 PATH_TRAVERSAL_IN。 java 源文件文件下载。 java 类名 chatapp.文件下载 方法名称 doGet 源代码行 31
2) FileDownload 中的 PT_RELATIVE_PATH_TRAVERSAL。 java 源文件文件下载。 java 类名 chatapp.文件下载 方法名称 doGet 源代码行 28
仅供引用,此代码是其功能的原始代码,但并不安全。
private String DOWNLOAD_PATH = new File(".").getCanonicalPath() +
"/webapps/webapp/app/download";
public FileDownload() throws IOException {
}
public void init() throws ServletException {
//To Do
}
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
!!!String file = request.getParameter("file");
String downloadPath = DOWNLOAD_PATH + "/" + file;
!!!File downloadFile = new File(FilenameUtils.getName(downloadPath));
if (downloadFile.exists()) {
response.setContentType("application/octet-stream");
response.setHeader("Content-disposition", "attachment; filename="+ downloadFile.getName());
FileInputStream fis = new FileInputStream(downloadFile);
byte[] data = new byte[(int) downloadFile.length()];
fis.read(data);
fis.close();
OutputStream out = response.getOutputStream();
out.write(data);
out.flush();
}
else
response.sendError(404);
}
有人有解决此类问题的经验吗?我有点困惑
最佳答案
维基百科关于路径遍历的文章 has a proposed method to prevent it :
- Process URI requests that do not result in a file request, e.g., executing a hook into user code, before continuing below.
- When a URI request for a file/directory is to be made, build a full path to the file/directory if it exists, and normalize all characters (e.g.,
%20
converted to spaces).- It is assumed that a 'Document Root' fully qualified, normalized, path is known, and this string has a length ''N''. Assume that no files outside this directory can be served.
- Ensure that the first ''N'' characters of the fully qualified path to the requested file is exactly the same as the 'Document Root'.
- If so, allow the file to be returned.
- If not, return an error, since the request is clearly out of bounds from what the web-server should be allowed to serve.
因此,您需要从 DOWNLOAD_PATH
创建第二个文件对象,然后使用 getCanonicalPath
查看要下载的文件的路径是否以下载目录的路径开头。
完成此操作后,您可以向该方法添加一个 @SuppressWarnings
注释,以隐藏现在已正确处理的警告。
关于在机器人中测试时,Java webapp 代码返回路径遍历问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58813932/