0

请在下面找到我编写的代码:

private void WriteLogs(Guid _guid)
{

string varpath = ConfigurationManager.AppSettings["LogFilePath"].ToString() + @"\ErrorLogs\Logs\";

string FileName = _guid.ToString() + ".txt";

string finalPath = System.IO.Path.GetFullPath(varpath + FileName);

if (Path.GetDirectoryName(finalPath) == Path.GetDirectoryName(varpath))
{
    if (!Directory.Exists(varpath))
    {
        Directory.CreateDirectory(varpath);
    }

    // Other code
}
}

请让我知道此代码是否可以防止目录遍历缺陷?

4

2 回答 2

0

由于 theGuid是唯一传入的东西,并且 aGuid不能是 form ..\..\,我认为你可以免受Directory Traversal Attack的伤害。

唯一的其他输入是ConfigurationManager.AppSettings["LogFilePath"]. 这可能是形式X:\Example\..,但也可能是X:\,所以我不认为这是一个问题。无论哪种方式,您都将添加@"\ErrorLogs\Logs\"到您正在编写的路径中。

我还建议使用Path.Combine,这样您就不必迷失在\'s

string varpath = Path.Combine(ConfigurationManager.AppSettings["LogFilePath"]
                     .ToString(), @"ErrorLogs\Logs");
于 2013-06-11T13:35:42.997 回答
-1

这对我有用:

 private bool IsValidPath(string fileNamePath)
    {
        if (string.IsNullOrWhiteSpace(fileNamePath))
            return false;
        var decodedPath = HttpUtility.UrlDecode(fileNamePath);

        return decodedPath.IndexOfAny(Path.GetInvalidPathChars()) < 0 &&
            decodedPath.IndexOfAny(Path.GetInvalidFileNameChars()) < 0 &&
            fileNamePath.IndexOfAny(Path.GetInvalidPathChars()) < 0 &&
            fileNamePath.IndexOfAny(Path.GetInvalidFileNameChars()) < 0;
    }
于 2020-09-01T09:56:50.637 回答