How do I fix SCS0018?

1k Views Asked by At

Security Scan SCS0018 Warnings in Visual Studio are shown during the build. Currently, I am working on these warnings to get removed. I tried several MSDN sites but no luck. I have also read OWSAP but they are not clearly related to C#. Please find the image of Path Traversal warning.

Path Traversal Warning Message

Code:

   public void Move(string sourceFileName, string destinationFileName)
    {
        
        try
        {
            System.IO.File.Move(sourceFileName,destinationFileName);
        }
        catch (System.Exception e)
        {
        }
   }
2

There are 2 best solutions below

0
Anthony Mastrean On

You should read the docs on this warning to understand the problem and find relevant references.

A path traversal attack (also known as directory traversal) aims to access files and directories that are stored outside the expected directory.By manipulating variables that reference files with “dot-dot-slash (../)” sequences and its variations or by using absolute file paths, it may be possible to access arbitrary files and directories stored on file system including application source code or configuration and critical system files.

https://security-code-scan.github.io/#SCS0018

The problem with your code is that you accept and use the destinationFileName parameter without any kind of checking.

System.IO.File.Move(sourceFileName,destinationFileName);

The documentation provides a recommendation (checking for invalid filename chars and throwing an exception before using the parameter) and .NET Core provides a new type, PhysicalFileProvider, that may protect from path traversal.

The PhysicalFileProvider provides access to the physical file system. PhysicalFileProvider uses the System.IO.File type (for the physical provider) and scopes all paths to a directory and its children. This scoping prevents access to the file system outside of the specified directory and its children.

But, I don't know if SCS detects usage of this type correctly.

0
Jaroslav Lobačevski On

First of all, give a try to the version 5.0.0 that has better untrusted input tracking and may not give you a warning in this case.

If it still gives you the warning, you need to properly validate or sanitize the untrusted parameter. However SCS is not smart enough to recognize custom validation function so you need to add it into a configuration file like:

Sanitizers:
  - Type: NamespaceAndClassName
    TaintTypes:
      - SCS0018
    Methods:
      - Name: SanitizePath

See the built-in configuration for more sanitizer examples.

If instead you prefer to not have a dedicated function, but validate it inline, the other option is to suppress the warning.