Improper input validation can enable attacks and lead to unwanted behavior. Parts of the system may receive unintended input, which could result in altered control flow, arbitrary control of a resource, or arbitrary code execution.
1#include <stdio.h>
2#include <string.h>
3
4void improperInputValidationNonCompliant(const char* username) {
5 printf("Enter username: ");
6 fgets(username, sizeof(username), stdin);
7 // Noncompliant: Input validation is needed to prevent user input from exceeding the allocated memory for `username`.
8 printf("Hello, %s!\n", username);
9}
1#include <stdio.h>
2#include <string.h>
3
4void improperInputValidationCompliant(const char* input) {
5 char buffer[100]; // Assuming a maximum length of 100 characters
6
7 printf("Enter input: ");
8 scanf("%99s", buffer); // Limit input to 99 characters to leave space for null terminator
9
10 if(strlen(buffer) > 99) {
11 printf("Input exceeds maximum length\n");
12 return;
13 }
14 // Compliant: Validated input is copied to the provided const char* input
15 strcpy(input, buffer);
16
17 printf("You entered: %s\n", input);
18}