Question

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?

Was it helpful?

Solution

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");

OTHER TIPS

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;
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top