如何在Java中防止路径遍历攻击

4

最近,我使用AppScan Source扫描编码时发现了一个问题,但我不知道如何修复并通过扫描仪。

以下是我的代码。

public void init()
{
String prefix = getServletContext().getRealPath("/");
String file = getInitParameter("log4j-init-file");

String pth = "C:\\wls1034\\user_projects\\domains\\base_domain\\servers\\AdminServer\\tmp\\_WL_user\\SimulationService\\39m5yi\\war\\WEB-INF";
String n= prefix+file;

File fileExists = new File(n);
if (fileExists.exists()) {
            PropertyConfigurator.configure("C:\\wls1034\\user_projects\\domains\\base_domain\\servers\\AdminServer\\tmp\\_WL_user\\SimulationService\\39m5yi\\war\\WEB-INF" + file);
          } else {
            BasicConfigurator.configure();
          }   
 }

我尝试添加if语句来检查路径中是否有任何特殊字符。然而,扫描器仍然报告在"File fileExists = new File(n);"中发现了问题。

public void init()
{
String prefix = getServletContext().getRealPath("/");
String file = getInitParameter("log4j-init-file");

String pth = "C:\\wls1034\\user_projects\\domains\\base_domain\\servers\\AdminServer\\tmp\\_WL_user\\SimulationService\\39m5yi\\war\\WEB-INF";
String n= prefix+file;
 //For Security Checking
if (file != null && !n.contains("../") && !n.contains("$") && !n.contains("*"))//Check the path whether it's included risk character
{

File fileExists = new File(n);
if (fileExists.exists()) {
            PropertyConfigurator.configure("C:\\wls1034\\user_projects\\domains\\base_domain\\servers\\AdminServer\\tmp\\_WL_user\\SimulationService\\39m5yi\\war\\WEB-INF" + file);
          } else {
            BasicConfigurator.configure();
          }
}
 }

现在有什么问题?我有点理解,但还不够清楚。 - Kick Buttowski
扫描器检测到一个在文件fileExists = new File(n)中的发现。在进行扫描之前,我没有添加if语句来检查文件名。 - Chris Mok
2个回答

4

这只是扫描器的误报。由于在读取或写入路径时未涉及用户输入,因此上述代码不存在安全风险。


1
是的。AppScan将init参数/配置视为受污染的源,因为它是来自代码外部的输入,但实际上在绝大多数情况下,它并不受攻击者控制(或者如果是,你已经完全失去了控制)。 - bobince

0

扫描器会标记带有变量的文件路径。

var sr = new StreamReader("C:\\....\\WEB-INF" + file);

正如Ahmad所提到的,这通常是一个误报。但是验证恶意用户无法利用代码并访问未预期的文件是个好主意。

为了让扫描器满意,您可以提供硬编码路径,或为每个可能的文件路径创建一个switch语句。

switch (fileId)
  {
      case "1":
          sr = new StreamReader("C:\file-1");
          break;
      case "2":
          sr = new StreamReader("C:\file-2");
          break;
  }

但是谁想这样做呢!

你最好的选择是确保不存在威胁,并说服安全人员允许你的代码继续执行。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接