cybersecurity · intermediate · ~15 min · safe pentest lab

Validate input length

Adopt allowlist validation as a habit.

Challenge

Accept a string only if every character is on an approved allowlist and its length is in range — the safe alternative to blocking known-bad characters.

Task

Implement int validate_user_input(const char *s) that returns 0 if s is valid and -1 otherwise.

s is valid when all of these hold:

  • its length is between 1 and 64 characters (inclusive), and
  • every character is an ASCII letter, an ASCII digit, or one of - _ . @ +.

Input

A NUL-terminated string s the grader passes. s may be NULL.

Output

Returns 0 if s is valid, -1 otherwise.

Example

validate_user_input("alice99@example.com")   ->   0
validate_user_input("alice.smith")           ->   0
validate_user_input("ali ce")                ->   -1   (space not allowed)
validate_user_input("alice;")                ->   -1   (';' not allowed)
validate_user_input("")                      ->   -1   (too short)
validate_user_input(NULL)                    ->   -1

Edge cases

  • Empty string: invalid (length 0).
  • Length exactly 64: valid; 65 or more: invalid.
  • NULL pointer: return -1.

Rules

  • Use an allowlist (approve known-good characters) rather than a blocklist.

Why this matters

The most common input bug isn't malicious content — it's malformed length. A function that asserts input length is in a known range catches 90% of bugs before they reach business logic.

Input format

A NUL-terminated string s (may be NULL).

Output format

0 if s is 1..64 chars and only letters/digits/-_.@+; otherwise -1.

Constraints

Allowlist the permitted characters; reject everything else.

Starter code

#include <stdio.h>
#include <ctype.h>

int validate_user_input(const char *s) {
    /* TODO */
    return -1;
}

Common mistakes

Off-by-one on the upper bound. Not checking for NULL. Using strlen on non-NUL-terminated input.

Edge cases to handle

Empty input. Input exactly at the limit. Input one byte over the limit. NULL pointer.

Complexity

O(length).

Background lessons

Up next

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.