DEV Community

Mohammad Faisal
Mohammad Faisal

Posted on

Solving CWE-606: Unchecked Input for Loop Condition

The CWE-606: Unchecked Input for Loop Condition is described as:

The product does not properly check inputs that are used for loop conditions, potentially leading to a denial of service because of excessive looping.

with an attached demonstrative example in C as:

void iterate(int n){
  int i;
  for (i = 0; i < n; i++){
    foo();
  }
}
void iterateFoo()
{
  unsigned int num;
  scanf("%u",&num);
  iterate(num);
}
Enter fullscreen mode Exit fullscreen mode

Recently I came across this issue in my Java application when we scanned the project with Checkmarx's CxSAST. The code is something like:

List<String> records = ... // The records are read from a received file
for ( int i = 0; i < records.size(); i++){
  // some processing here
}
Enter fullscreen mode Exit fullscreen mode

Now in order to solve this issue I identify two approaches:

  1. define a max size of records and compare the size of the records to that value and if it is greater than that then either do not process any record and exit or process the records in chunks by splitting them by the max size.
  2. rewrite this for-loop as for-each which do not check for the execution condition and process until it has record in there.

In the 1st solution it would be difficult to put a size restriction as we do not know the limit of number of records could be there and we have to process them all. If we go by a chunk processing then we could put some arbitrary value.

In the 2nd solution we may trick the checkmarx that we have not used the user input as loop condition but I am not sure if that will work or not?

What is your opinion on this?

Top comments (0)