This C code defines a small program that manages a...

August 28, 2025 at 04:57 PM

#include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct { char id[10]; int crediti; } Utente; Utente utenti[3] = { {"U001",100}, {"U002",50}, {"U003",75} }; // Funzione vulnerabile: input non validato permette incremento imprevisto void aggiungiCrediti() { char id[10]; char input[50]; printf("Inserisci ID utente: "); scanf("%9s", id); Utente* u = NULL; for(int i=0;i<3;i++){ if(strcmp(utenti[i].id,id)==0){ u=&utenti[i]; break; } } if(!u){ printf("Utente non trovato.\n"); return; } printf("Inserisci crediti da aggiungere: "); scanf(" %49[^\n]", input); // CWE-77: input interpretato come formula interna // Input malevolo può usare operazioni aritmetiche int aggiunta = 0; if(sscanf(input,"%d",&aggiunta)==1){ u->crediti += aggiunta; } else { // esempio di vulnerabilità: input "10+20" viene valutato come 30 // parsing ingenuo senza filtraggio aggiunta = atoi(strtok(input,"+")) + atoi(strtok(NULL,"+")); u->crediti += aggiunta; } printf("Utente %s ha ora %d crediti\n", u->id, u->crediti); } int main() { aggiungiCrediti(); return 0; }

This C code defines a small program that manages a fixed array of user objects and allows incrementing their "crediti" (credits) through a potentially vulnerable function. Here's the breakdown of what each part of the code does:

1. Data Structures and Initialization

typedef struct {
    char id[10];
    int crediti;
} Utente;

Utente utenti[3] = { {"U001",100}, {"U002",50}, {"U003",75} };
  • A Utente structure is defined, which contains two fields:
    • id: A string representing the user ID (maximum of 9 characters + null terminator).
    • crediti: An integer representing the user's credits.
  • An array utenti is initialized with three Utente objects representing users with predefined IDs and credits.

2. The aggiungiCrediti Function

This function allows a user to update the credits for a specific user in the system. However, it contains a vulnerability due to improper input validation.

void aggiungiCrediti() {
    char id[10];
    char input[50];
    printf("Inserisci ID utente: ");
    scanf("%9s", id);
  • Prompts the user to input a user ID (up to 9 characters).
  • The program uses this ID to search for a matching user in the utenti array.
    Utente* u = NULL;
    for(int i=0;i<3;i++){
        if(strcmp(utenti[i].id,id)==0){ u=&utenti[i]; break; }
    }
  • Searches the utenti array for a user with a matching ID.
  • If found, a pointer u is set to the corresponding user object; otherwise, u remains NULL.
    if(!u){ 
        printf("Utente non trovato.\n"); 
        return; 
    }
  • If the user ID is not found, the function exits with an error message.
    printf("Inserisci crediti da aggiungere: ");
    scanf(" %49[^\n]", input);
  • Prompts the user to input a string (input) representing the number of credits to add.
  • The input can hold up to 49 characters.

3. Vulnerability: Improper Input Handling

    int aggiunta = 0;
    if(sscanf(input,"%d",&aggiunta)==1){
        u->crediti += aggiunta;
    } else {
        // esempio di vulnerabilità: input "10+20" viene valutato come 30
        aggiunta = atoi(strtok(input,"+")) + atoi(strtok(NULL,"+"));
        u->crediti += aggiunta;
    }
  • The function attempts to interpret the input string as an integer using sscanf.
  • If sscanf fails (e.g., non-numeric input), the program falls back to a naive parsing mechanism to handle non-standard input like "10+20".
    • strtok splits the input string by the '+' character.
    • The program converts the resulting "tokens" into integers using atoi and performs a manual addition of the two numbers.
  • This input parsing method enables vulnerable behavior:
    • An attacker could exploit this logic to input non-standard, partially valid, or malicious data (e.g., "10+20") to bypass normal formatting.

4. Output and Results

    printf("Utente %s ha ora %d crediti\n", u->id, u->crediti);
  • Displays the updated credits for the target user.

5. Main Function

int main() {
    aggiungiCrediti();
    return 0;
}
  • Calls the aggiungiCrediti function to interactively add credits to a user.

Vulnerabilities in the Code

The code contains the following security and functionality issues:

  1. Improper Input Validation:

    • When parsing input, the code does not validate or sanitize it properly. For example, input like 10+20 will be accepted and processed as 30 credits.
    • Malformed or malicious inputs can cause undefined behavior depending on how strtok and atoi interpret them.
  2. Arithmetic Parsing:

    • The fallback mechanism in aggiungiCrediti allows basic arithmetic expressions like "10+20" but fails to handle more complex cases or invalid input robustly.
    • Exploiting this logic, users might even inject unexpected values.
  3. Limited User Search:

    • Only three users are hardcoded in memory. Additional inputs or scalability are not handled.
    • Related edge cases (e.g., extremely large input or buffer overflows) can lead to crashes.
  4. Lack of Input Sanitization:

    • The program assumes inputs are well-formed and does not check for overflow, underflow, or invalid characters.

Example Vulnerable Behavior

Case 1: Regular input

Input:

Inserisci ID utente: U001
Inserisci crediti da aggiungere: 25

Output:

Utente U001 ha ora 125 crediti

Case 2: Exploiting Arithmetic Parsing

Input:

Inserisci ID utente: U002
Inserisci crediti da aggiungere: 10+20

Output:

Utente U002 ha ora 80 crediti

Case 3: Malformed Input (Potential Crash or Incorrect Behavior)

Input:

Inserisci ID utente: U003
Inserisci crediti da aggiungere: 5++10---20

Behavior:

  • May result in undefined behavior or incorrect parsing.
  • The program might crash or process a random "crediti" value due to improper handling.

Summary

This code implements a simple user credit system with a vulnerable aggiungiCrediti function. The vulnerability arises from poor input validation and naive arithmetic parsing, which attackers can exploit to manipulate or crash the program.

Generate your own explanations
Download our vscode extension
Read other generated explanations

Built by @thebuilderjr
Sponsored by beam analytics
Read our terms and privacy policy
Forked from openai-quickstart-node