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

1  using System.IO;
2  
3  class FileCreator 
4  {
5    public void WriteFile(string filePath, byte[] data, int length) 
6    {
7      FileStream fs = File.Create(filePath);    
8      fs.Write(data, 0, length);    
9      fs.Close();  
10   }
11 }

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

1  using System.IO;
2
3  class FileCreator 
4  {
5    public void WriteFile(string filePath, byte[] data, int length)
6    {
7       FileStream fs = File.Create(filePath, 1024, FileOptions.Encrypted); //no CS.NPS
8       fs.Write(data, 0, length);
9       fs.Close();  
10   }
11 }  

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.