我有一个 Java 网络应用程序,它具有使用 URL 获取远程文件的功能。 .
当我测试代码时,我发现匿名用户可以通过将文件路径 /etc/passwd
修改为 file URL schema 来读取本地文件。 , file:///etc/passwd
, 文件会通过URL读取, 下面是一个例子:
String remoteUrl = "file:///etc/passwd"; // some url we got from anonymous user
URL url = new URL(remoteUrl);
byte data[] = new byte[1024];
int length;
BufferedInputStream inputStream = new BufferedInputStream(url.openStream());
ServletOutputStream outputStream = response.getOutputStream();
// OR PrintStream outputStream = System.out;
while( (length = inputStream.read(data, 0, 1024)) >= 0 ) {
outputStream.write(data, 0, length);
}
对解决这个问题有什么建议吗?
最佳答案
如果您使用 URL,您可以从中获取协议(protocol)。在这种情况下,如果协议(protocol)是"file"(或者不是“http”,具体取决于您希望对其进行的限制程度),您可以抛出异常
关于java - 禁止 Java URL 获取本地文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14347343/