format-string

Untrusted input used as a format string.

Group
Code
Runs
Runs under ur scan: ur scan --rule format-string
Level
warning
Reads
Every file
Fix
None: the safe form depends on what the value is meant to be

Why

A value from outside the program, such as an environment variable, is given to printf or a function like it as its format, so whoever chose it can make the call read the stack with %x or write memory with %n. Pass a fixed format and the value as its argument, as printf("%s", value).

The fix, as Ur suggests it: pass a fixed format, as "%s", and the value after it.

For agents

Never pass input as a format string; pass a fixed format and the input as an argument.

Example

src/main.cpp
#include <cstdio>
#include <cstdlib>

int main() {
  const char* greeting = std::getenv("GREETING");
  std::printf(greeting);
  return 0;
}
What Ur prints
$ ur scan --rule format-string
warning[format-string]: `std::getenv`, an environment variable, reaches `std::printf`
  --> ./src/main.cpp:6:3 function `main`
  = step 1: ./src/main.cpp:5:26 `std::getenv`, an environment variable,
  = hint: pass a fixed format, as "%s", and the value after it
  = see: FIO30-C. Exclude user input from format strings, SEI CERT C Coding Standard (2023-10-25), https://wiki.sei.cmu.edu/confluence/display/c/FIO30-C.+Exclude+user+input+from+format+strings
scanned 1 file (no framework recognized)
  format-string: 1 high, 0 medium
1 finding and 0 of medium confidence

Try it in the playground →

Source

FIO30-C. Exclude user input from format strings, SEI CERT C Coding Standard (2023-10-25).