首页 > 解决方案 > 解决 Veracode 的 CWE-73:“文件名或路径的外部控制”MVC 应用程序

问题描述

我的应用程序中有一个函数,我从 Veracode 的扫描中得到了一个缺陷CWE-73 。该函数用于遍历特定路径,获取一个文件的内容和文件夹中的文件列表:

private LogFile GetLogFileByName(string logFileName)
{
    string fileContents = string.Empty;
    string path = this.GetBasePath + "/Logs/" + logFileName;
    if (System.IO.File.Exists(path))
    {
        using (FileStream stream = System.IO.File.Open(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
        {
            using (StreamReader reader = new StreamReader(stream))
            {
                fileContents = reader.ReadToEnd();
            }
        }
    }
    return new LogFile {FileContents = fileContents, LogFileName = logFileName, LogFileNames = GetNames()};
}

我寻找解决此缺陷的可能选项,其中之一是适用于我的“模式白名单”,因此我以以下方式重写了该函数:

private LogFile GetLogFileByName(string logFileName)
{
    string fileContents = string.Empty;
    var regex = new System.Text.RegularExpressions.Regex(@"^log\.common\.txt(\d{4}.\d{2}.\d{2})?$");
    if (regex.IsMatch(logFileName))
    {
      string path = this.GetBasePath + "/Logs/" + logFileName;
      if (System.IO.File.Exists(path))
      {
          using (FileStream stream = System.IO.File.Open(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
          {
              using (StreamReader reader = new StreamReader(stream))
              {
                  fileContents = reader.ReadToEnd();
              }
          }
      }
    }
    else {
      return new LogFile();
    }

    return new LogFile {FileContents = fileContents, LogFileName = logFileName, LogFileNames = GetNames()};
}

我使用正则表达式检查一切是否在语法上正确。但是,问题仍然出现。任何想法,如何解决?我查看了 SO 中的几个帖子,但似乎没有任何适当的解释。

标签: c#asp.net-mvcveracodesecure-coding

解决方案


Veracode 有一篇知识库文章,该文章链接自缺陷查看器,其中提供了一些有关如何解决的指示:

https://downloads.veracode.com/securityscan/cwe/v5/net/73.html


推荐阅读