C#中使用动态数据构建路径时的路径遍历问题如何解决?
解决路径遍历(Path Traversal)问题的方案
当前代码直接将用户可控的project值拼接进路径,攻击者可以输入../这类构造跳出指定的ProjectPath目录,访问或操作其他敏感目录的资源,这就是路径遍历漏洞的核心风险。以下是具体解决方法:
核心解决步骤
严格验证输入合法性
限制project只能是合法的文件夹名称,禁止包含路径分隔符(\、/)、特殊字符(..、:、*等)。可以用正则表达式做白名单校验:if (!System.Text.RegularExpressions.Regex.IsMatch(project, @"^[a-zA-Z0-9_-]+$")) { throw new ArgumentException("项目文件夹名称格式非法"); }用
Path.Combine安全拼接路径
不要直接用字符串拼接路径,Path.Combine会自动处理路径分隔符,避免手动拼接的错误:string basePath = ConfigurationManager.AppSettings["ProjectPath"].ToString(); string combinedPath = System.IO.Path.Combine(basePath, project);规范化路径并校验范围
把拼接后的路径转为绝对路径,然后检查它是否完全包含在预先定义的基础目录内,彻底防止越界:string basePath = System.IO.Path.GetFullPath(ConfigurationManager.AppSettings["ProjectPath"].ToString()); string combinedPath = System.IO.Path.GetFullPath(System.IO.Path.Combine(basePath, project)); if (!combinedPath.StartsWith(basePath, StringComparison.OrdinalIgnoreCase)) { throw new System.Security.SecurityException("无权访问指定路径"); }用映射关系替代直接输入(可选)
尽量不要直接用用户输入的字符串当文件夹名,改用项目ID这类唯一标识,后台通过ID映射到合法的文件夹名,从根源避免输入风险:// 假设从表格取项目ID,而非名称 string projectId = gv_projects.Rows[index].Cells[0].Text; // 从数据库或配置获取对应合法文件夹名 string safeFolderName = GetSafeFolderNameById(projectId); string combinedPath = System.IO.Path.Combine(basePath, safeFolderName);
修改后的完整示例代码
// 从配置获取基础路径并规范化 string basePath = System.IO.Path.GetFullPath(ConfigurationManager.AppSettings["ProjectPath"].ToString()); // 获取用户输入的项目名称 string project = gv_projects.Rows[index].Cells[1].Text; // 验证输入合法性 if (!System.Text.RegularExpressions.Regex.IsMatch(project, @"^[a-zA-Z0-9_-]+$")) { throw new ArgumentException("项目文件夹名称格式非法"); } // 安全拼接并校验路径范围 string combinedPath = System.IO.Path.GetFullPath(System.IO.Path.Combine(basePath, project)); if (!combinedPath.StartsWith(basePath, StringComparison.OrdinalIgnoreCase)) { throw new System.Security.SecurityException("无权访问指定路径"); } // 存储到ViewState ViewState["ProjectFolder"] = combinedPath; // 执行移动操作 string oldfolder = ViewState["ProjectFolder"].ToString(); System.IO.Directory.Move(oldfolder, newfolder);
内容的提问来源于stack exchange,提问作者Aswini
相关产品推荐
相关产品推荐

