CS.SV.TAINTED.PATH_TRAVERSAL
Unvalidated input in path construction
If a program uses external input to construct a pathname without special character neutralization, it can be left open to a path traversal attack. This checker reports defects when external strings that are used as parts of file paths are not checked properly.
Vulnerability and risk
A path traversal attack aims to get access to arbitrary files and directories including critical system or application data. A path traversal attack can also be used to provide malicious configuration for a program. It has been ranked as #12 in the Top 25 Most Dangerous Programming Errors.
Mitigation and prevention
To avoid this issue, it's best to add validation code before raw input is used as a pathname. The validation code must contain checks for the following cases:
- dot-dot-slash ( ../ ): Using this sequence and its variations, an attacker could navigate your file system and obtain access to any file. Note that ( ../ ) can be presented in various encodings, for example, " ../../../etc/shadow " .
- absolute paths: Using absolute paths in a situation when relative paths are expected could also provide access to arbitrary files in your system, for example, " /etc/shadow ".
- null symbol : Using the null symbol may allow an attacker to truncate a generated filename to widen the scope of attack in a situation when an application restricts possible file extensions by checking or appending specific extension, for example, " application.cfg%00.pdf ".
Vulnerable code example
namespace Program
{
class Program
{
static void Main(string[] args)
{
string fileName = args[1];
using (BinaryWriter writer = new BinaryWriter(File.Open(fileName, FileMode.Create)))
{
writer.Write(1.250F);
writer.Write(@"c:\Temp");
writer.Write(10);
writer.Write(true);
}
}
}
}
In this example, Klocwork reports a defect because the "fileName" string is received through the "args" argument and is used as a pathname without being validated.
Fixed code example
namespace Test
{
class Program
{
static void Main(string[] args)
{
string fileName = args[1];
neutralize(fileName);
using (BinaryWriter writer = new BinaryWriter(File.Open(fileName, FileMode.Create)))
{
writer.Write(1.250F);
writer.Write(@"c:\Temp");
writer.Write(10);
writer.Write(true);
}
}
private static void neutralize(string fname)
{
}
}
}
Klocwork no longer reports a defect because the external input is passed to the "neutralize" function and is validated, making the path safe.
Related checkers
External guidance
- CWE-20: Improper Input Validation
- CWE-22: Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')
- CWE-426: Untrusted Search Path
- CWE-896: SFP Primary Cluster: Tainted Input
- OWASP A1:2021 Broken Access Control
- OWASP A3:2021 Injection
- OWASP A8:2021 Software and Data Integrity Failures
Security training
Application security training materials provided by Secure Code Warrior.