cybersecurity · beginner · ~15 min
Neutralize format string injection attacks by escaping format specifiers.
Passing user-controlled strings directly into printf or syslog causes format string vulnerabilities where %n allows arbitrary memory writes and %x leaks stack memory. A sanitizer strips or escapes % specifiers.
Implement:
int sanitize_format_string(const char *untrusted, char *dest, size_t dest_cap, size_t *escaped_count);
untrusted == NULL, dest == NULL, escaped_count == NULL, or dest_cap == 0, return -1.*escaped_count = 0.untrusted into dest.% character is encountered in untrusted:%% (two percent characters) to dest.*escaped_count by 1.dest_cap, return -1 without buffer overflow.dest and return 0.char out[32]; size_t count = 0;
sanitize_format_string("User %s score: 100%", out, sizeof(out), &count);
// out becomes: "User %%s score: 100%%", count == 2
untrusted: input string; dest: output buffer; dest_cap: capacity; escaped_count: count pointer.
Returns 0 on success, -1 on capacity overflow or NULL.
Must escape every % into %%. Safe NUL termination.
#include <stddef.h>
int sanitize_format_string(const char *untrusted, char *dest, size_t dest_cap, size_t *escaped_count) {
(void)untrusted; (void)dest; (void)dest_cap; (void)escaped_count;
return -1;
}
Forgetting the NUL terminator; buffer overflow when double-percent exceeds dest_cap.
Empty string produces empty output and 0 count; string with no % copied identically.
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.