Unchecked Input In Loop Condition
ID |
java.unchecked_input_in_loop_condition |
Severity |
high |
Resource |
Injection |
Language |
Java |
Tags |
CWE:606, NIST.SP.800-53, PCI-DSS:6.5.6 |
Description
Improper neutralization of external input in loop condition.
Unchecked input in a loop condition involves the use of user-supplied input to control loop iteration counts without adequate validation or sanitization. This can lead to denial of service through excessive loop iterations or even providing a vector for logic or timing attacks.
Rationale
When an application uses unchecked input to determine the number of iterations in a loop, it opens up multiple avenues for potential security issues. An adversary can exploit this to degrade performance, as the loop might iterate excessively, consuming CPU and memory resources. This unchecked input issue can lead to denial of service if an attacker feeds large input values causing unexpected load.
Consider a scenario in Java where user input dictates loop iterations:
import java.util.Scanner;
public class LoopConditionExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter number of times to print 'Hello':");
int iterations = scanner.nextInt(); // Unchecked user input
for (int i = 0; i < iterations; i++) {
System.out.println("Hello");
}
}
}
In this code, the number of iterations for the loop is directly tied to an integer input from the user. Without proper validation or constraints, a malicious user could input an excessively large number, potentially affecting system availability by overwhelming system resources.
Remediation
To protect against unchecked input in loop conditions, incorporate input validation and set appropriate boundaries on user input. Consider the following strategy:
-
Validate Input: Always validate and sanitize all user inputs. Reject or handle any invalid or harmful data.
-
Set Limits: Define sensible upper and lower limits for loop control variables to ensure the application operates within safe boundaries.