CS.SV.TAINTED.CALL.GLOBAL

Use of Unvalidated Integer in an Assignment Operation

This checker reports a defect whenever tainted data is used to assign a globally visible data field via a function call.

Vulnerability and risk

Global variables, such as C# public static class fields, are visible in the entire program scope. It can be difficult for a programmer or an analysis tool to fully control their assignments or reads in the program. The possibility of a reduced understanding of the global variable effect on the program control flow can introduce a security risk when integer data input to the code is not validated properly and is used to assign a global variable.

Vulnerable code example

Copy
   using System;
   using System.IO;
   namespace TaintedGlobal
   {
     class TestTaintedGlobal
     {
       const string fileName = "File.dat";
       public static int gVar = 0;
   
      public static void TaintedGlobalExample()
      {
              int t = getTaintedData();
        bar(t); // CS.SV.TAINTED.CALL.GLOBAL
      }
  
      public static int getTaintedData()
      {
        try
        {
          using (BinaryReader br = new BinaryReader(File.Open(fileName, FileMode.Open)))
          {
            return(br.ReadInt32());
          }
        }
        catch (Exception e)
        {
          Console.WriteLine(e);
        }
      }

      public static void bar(int value)
      {
        gVar = value;
      }
    }
  }

In the above example, an attacker can provide an arbitrary value for global variable ‘gVar’ that can later be potentially used elsewhere in a code that the programmer has no control or even not aware of. This potentially introduces a risk of security vulnerability involving that variable.

Klocwork reports a SV.TAINTED.CALL.GLOBAL defect at line 12, indicating that “Unvalidated integer value ’t’ that is received from ’getTaintedData’ at line 12 is used to assign a global variable via a call 'bar()' at line 13.”

Fixed code example

Copy
   using System;
   using System.IO;
   
   namespace TaintedGlobal
   {
     class TestTaintedGlobal
     {
       const string fileName = "File.dat";
       const int maxBuf = 10;
      public static int gVar = 0;
  
      public static void TaintedGlobalExample()
      {
              int t = getTaintedData();
        if(t < maxBuf)
        {
          bar(t); 
        }
      }
  
      public static int getTaintedData()
      {
        try
        {
          using (BinaryReader br = new BinaryReader(File.Open(fileName, FileMode.Open)))
          {
            return(br.ReadInt32());
          }
        }
        catch (Exception e)
        {
          Console.WriteLine(e);
        }
      }
  
      public static void bar(int value)
      {
        gVar = value;
      }
    }
  }

Klocwork no longer reports a defect since the integer value 't' is validated.