CS.NPS

Accessing file data without encryption or setting access control privileges to file

If a file is created or used insecurely, application and system data can be left open to attack. Dangerous data can be injected into the application, or data stored in a file can be accessed, modified, or corrupted. The CS.NPS checker flags situations in which file data is written or read without encryption or without setting access control for the file.

Vulnerability and risk

If a file is not encrypted or access has not been restricted by appropriate permissions being set, then an attacker can exploit it to manipulate critical information.

Mitigation and prevention

To avoid vulnerability:
  • Use function SetAccessControl of System.IO.File , System.IO.FileInfo , or System.IO.FileStream.Net Framework classes.
  • Use function Encrypt of System.IO.File and System.IO.FileInfo.Net Framework classes.

Vulnerable code example

Copy
  using System.IO;
  
  class FileCreator 
  {
    public void WriteFile(string filePath, byte[] data, int length) 
    {
      FileStream fs = File.Create(filePath);    
      fs.Write(data, 0, length);    
      fs.Close();  
   }
 }

Klocwork reports a defect in this example because the file stream fs was created without specifying access control settings; methods SetAccessControl and Encrypt are not invoked to protect data written by the file stream.

Fixed code example

Copy
  using System.IO;

  class FileCreator 
  {
    public void WriteFile(string filePath, byte[] data, int length)
    {
       FileStream fs = File.Create(filePath, 1024, FileOptions.Encrypted); //no CS.NPS
       fs.Write(data, 0, length);
       fs.Close();  
   }
 }

Klocwork does not report a defect in this example because the code encrypts the file.

Security training

Application security training materials provided by Secure Code Warrior.