cybersecurity · intermediate · ~25 min

Prevent CSV injection by prefixing risky cells

Threat-aware defensive copying.

Challenge

Implement int sanitize_cell(const char *cell, char *out, size_t cap). If cell starts with =, +, -, or @, prepend a single tab character \t so spreadsheet apps treat it as text. Otherwise copy as-is. NUL-terminate out. Return the number of bytes written, or -1 if it would not fit.

Why this matters

CSV injection (formula injection) is when a malicious value like =cmd|'/c calc'!A0 runs in Excel when a user opens an exported CSV. Excel and LibreOffice still treat leading =, +, -, @ as formulas. Prevent it at export time.

Input format

Cell text, null-terminated.

Output format

See API.

Constraints

No allocations.

Starter code

#include <stddef.h>
int sanitize_cell(const char *cell, char *out, size_t cap) { /* TODO */ return -1; }

Common mistakes

Only checking = (Excel formulas also start with +, -, @); prepending a space (Excel sometimes strips it); prepending the tab outside the quoted CSV field (breaks formatting).

Edge cases to handle

Empty input — no prefix. A leading tab already present — still safe to add another (idempotency isn't required).

Complexity

O(strlen).

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