0

Please find below code that i have written:

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
}
}

Please let me know does this code prevent Directory Traversal flaw?

Nilesh Sarvaiya
  • 49
  • 3
  • 11
  • 1
    Looks fine to me. You can use `Path.Combine(varpath, FileName)` instead of `Path.GetFullPath` so that it joins them even if you forget the '\' character in the .config file. – Dominic Zukiewicz Jun 11 '13 at 13:20

2 Answers2

0

Since the Guid is the only thing passed in, and a Guid cannot be of the form ..\..\, I think you would be safe from a Directory Traversal Attack.

The only other input is ConfigurationManager.AppSettings["LogFilePath"]. This could be of the form X:\Example\.., but it could also be X:\, so I do not see this as a problem. Either way, you will be adding @"\ErrorLogs\Logs\" to the path you are writing.

I would also recommend using Path.Combine, so you dont have to get lost in \'s

string varpath = Path.Combine(ConfigurationManager.AppSettings["LogFilePath"]
                     .ToString(), @"ErrorLogs\Logs");
Nick Freeman
  • 1,411
  • 1
  • 12
  • 25
-1

this is working for me:

 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;
    }
DanielV
  • 2,076
  • 2
  • 40
  • 61