All integer values originating from untrusted sources should be evaluated to determine whether there are identifiable upper and lower bounds. If so, these limits should be enforced by the interface. Anything that can be done to limit Restricting the input of excessively large or small integers should help helps prevent overflow, truncation, and other type range errors. Furthermore, it is easier to find and correct input problems than it is to trace internal errors back to faulty inputs.
...
In the following non-compliant code example, size
is a user supplied parameter argument that is used to determine the size of table
.
Code Block | ||
---|---|---|
| ||
int create_table(size_t size) { char **table; if (sizeof(char *) > SIZE_MAX/size) { /* handle overflow */ } size_t table_size = size * sizeof(char *); table = malloc(table_size) if (table == NULL) { /* Handle error condition */ } /* ... */ return 0; } |
However, since size
can be Because size
is controlled by the user, it could be specified to be either large enough to consume large amounts of system resources and still succeed or large enough to cause the call to malloc()
to fail, which, depending on how error handling is implemented, may result in a denial of service condition.
...
This compliant solution defines an the acceptable range for table size
as {{1 to , MAX_TABLE_SIZE}}. The size
parameter is typed declared as size_t
and , which is unsigned by definition. Consequently, it is not necessary to check size
for negative values (see INT01-A. Use size_t for all integer values representing the size of an object).
...