cybersecurity · intermediate · ~20 min

Detect a malformed username (defensive check)

Multi-rule validation; stateful character scan.

Challenge

Implement int valid_username(const char *u). Rules:

  • Length 3..32.
  • First char must be a lowercase letter.
  • Subsequent chars: lowercase, digit, _, -, ..
  • No two consecutive dots (..).
  • No leading/trailing dot or hyphen.
  • Returns 1 if valid, 0 if not.

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

Null-terminated string.

Output format

0 or 1.

Constraints

No regex.

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.