cybersecurity · intermediate · ~15 min · safe pentest lab

Detect format string misuse in toy code

Static-analysis-style detection of a specific bug shape.

Challenge

Detect the format-string smell where user data is passed as the format argument: printf(name) is a vulnerability if name is attacker-controlled.

Task

Implement int looks_like_format_misuse(const char *line) that returns 1 if line contains a call shaped like printf(<arg>) or fprintf(<stream>, <arg>) where the format <arg> is an identifier (not a string literal). Otherwise return 0.

The format argument is risky when it does NOT start with a " — i.e. it is a variable rather than a literal format string.

Input

  • line: a single NUL-terminated line of C source text. The grader passes a fixed line baked into the harness.

Output

Returns int: 1 if the line looks like a misuse, else 0.

Example

"    printf(name);"          ->   1   (variable as format)
"    printf(\"hi %s\", x);"     ->   0   (literal format — fine)
"    fprintf(stderr, msg);"  ->   1   (variable is the format arg)
"    snprintf(b, n, fmt, x);"->   0   (not printf/fprintf)
"    printf();"              ->   0   (no argument)

Edge cases

  • A literal-string first argument (starts with ") is fine.
  • snprintf, vprintf, etc. are not printf/fprintf and do not match.
  • printf() with no argument does not match.

Rules

  • Detection only — scan the line, no execution.

Input format

A NUL-terminated line of C source text line.

Output format

An int: 1 if the line looks like printf/fprintf misuse, else 0.

Constraints

Detection only; recognise only bare printf/fprintf, not snprintf etc.

Starter code

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

int looks_like_format_misuse(const char *line) {
    /* TODO */
    return 0;
}

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