cybersecurity · intermediate · ~20 min

Detect a malformed username (defensive check)

Multi-rule validation; stateful character scan.

Challenge

Validate a username strictly at the input boundary so every downstream layer (filenames, logs, queries) can trust it.

Task

Implement int valid_username(const char *u) that returns 1 if u satisfies all the rules below, else 0.

Input

  • u: a NUL-terminated candidate username the grader passes.

Output

Returns int: 1 if valid, 0 otherwise. A username is valid when:

  • length is 3..32 characters;
  • the first character is a lowercase letter a-z;
  • every other character is a lowercase letter, digit, _, -, or .;
  • it contains no two consecutive dots (..);
  • it does not end with a dot or hyphen.

Example

valid_username("alice")    ->   1
valid_username("a.b-c.d")  ->   1
valid_username("Ab")       ->   0   (uppercase + too short)
valid_username("a..b")     ->   0   (consecutive dots)
valid_username(".alice")   ->   0   (leading dot)
valid_username("1abc")     ->   0   (leading digit)

Edge cases

  • Empty string and lengths outside 3..32 are invalid.
  • A trailing dot or hyphen is invalid even if every character is otherwise allowed.

Why this matters

Usernames flow through filenames, log lines, SQL queries, and shell commands. Validating them strictly at input-time prevents an enormous class of injection attacks — every subsequent layer can trust the value.

Input format

A NUL-terminated candidate username u.

Output format

An int: 1 if u passes all the rules, else 0.

Constraints

No regex — scan the string directly.

Starter code

int valid_username(const char *u) { /* TODO */ return 0; }

Common mistakes

Allowing capital letters (some systems case-fold and create homograph collisions); allowing dots at end (filename-mode username/.config ambiguity); skipping the consecutive-dot check (path traversal vibes).

Edge cases to handle

Empty string. Single dot. 33-char string just over the limit.

Complexity

O(strlen).

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