26
This example demonstrates a shopping interaction in which the user is free to specify the quantity
of items to be purchased and a total is calculated.
Example Language: Java (Bad)
...
public static final double price = 20.00;
int quantity = currentUser.getAttribute("quantity");
double total = price * quantity;
chargeUser(total);
...
The user has no control over the price variable, however the code does not prevent a negative
value from being specified for quantity. If an attacker were to provide a negative value, then the
user would have their account credited instead of debited.
Example 2:
This example asks the user for a height and width of an m X n game board with a maximum
dimension of 100 squares.
Example Language: C (Bad)
...
#define MAX_DIM 100
...
/* board dimensions */
int m,n, error;
board_square_t *board;
printf("Please specify the board height: \n");
error = scanf("%d", &m);
if ( EOF == error ){
die("No integer passed: Die evil hacker!\n");
}
printf("Please specify the board width: \n");
error = scanf("%d", &n);
if ( EOF == error ){
die("No integer passed: Die evil hacker!\n");
}
if ( m > MAX_DIM || n > MAX_DIM ) {
die("Value too large: Die evil hacker!\n");
}
board = (board_square_t*) malloc( m * n * sizeof(board_square_t));
...
While this code checks to make sure the user cannot specify large, positive integers and consume
too much memory, it does not check for negative values supplied by the user. As a result, an
attacker can perform a resource consumption (CWE-400) attack against this program by specifying
two, large negative values that will not overflow, resulting in a very large memory allocation
(CWE-789) and possibly a system crash. Alternatively, an attacker can provide very large negative
values which will cause an integer overflow (CWE-190) and unexpected behavior will follow
depending on how the values are treated in the remainder of the program.
Example 3:
The following example shows a PHP application in which the programmer attempts to display a
user's birthday and homepage.
Example Language: PHP (Bad)
$birthday = $_GET['birthday'];
$homepage = $_GET['homepage'];
echo "Birthday: $birthday<br>Homepage: <a href=$homepage>click here</a>"
CWE Version 4.14
CWE-20: Improper Input Validation
CWE-20: Improper Input Validation