Improper neutralization of external input used within a CSV or Excel formula ('Formula Injection')

ID

php.csv_injection

Severity

critical

Resource

Injection

Language

Php

Tags

CWE:116, NIST.SP.800-53, OWASP:2021:A3, PCI-DSS:6.5.1

Description

Improper neutralization of external input used within a CSV or Excel formula ('Formula Injection').

CSV Injection, also known as formula injection, occurs when an application exports unsanitized user input into a CSV file. This can lead to the execution of unintended scripts when the CSV is opened in a spreadsheet application.

Rationale

CSV Injection, or formula injection, takes advantage of the ability of some spreadsheet programs (like Microsoft Excel) to treat input beginning with certain characters (e.g., '=', '+', '-', '@') as formulas. When unsanitized user input containing these characters is exported to a CSV file, it can result in the execution of malicious scripts with potentially harmful consequences.

Consider the following PHP example where user data is exported to a CSV file:

<?php

function exportToCsv($data)
{
    $file = fopen('output.csv', 'w');

    foreach ($data as $value) {
        fputcsv($file, explode(',', $value));
    }

    fclose($file);
}

$data = $_POST['data'];
// Let's say that $data contains the following: ["NormalValue", "=SUM(1,2)", "+CMD|' /C calc'!A0"];

exportToCsv($data);
?>
php

In this example, if the CSV is opened in a spreadsheet application, cells containing "=SUM(1,2)" and "+CMD|' /C calc'!A0" could potentially trigger unwanted behavior, such as arbitrary command execution if the spreadsheet application interprets them as formulas or commands.

Remediation

To remediate CSV Injection vulnerabilities, you can use the following strategies:

  1. Escape User Input: Always escape user input to be exported to CSV.

  2. Use Strict Validation: Implement strict validation on input prior to its inclusion in a CSV. Ensuring that input only contains expected characters significantly lowers the risk of injection.

  3. Input Filtering: Apply input filtering to remove known harmful characters or sequences from user input before including them into a CSV.

4 Security Tools and Static Analysis: Utilize SAST tools to identify CSV injection vulnerabilities during the development process. These tools can provide early warnings about unsafe patterns or input concatenations.

By following these measures, you not only prevent CSV Injection but also ensure that your application remains robust and secure against a variety of input-based exploits.

Configuration

The detector has the following configurable parameters:

  • sources, that indicates the source kinds to check.

  • neutralizations, that indicates the neutralization kinds to check.

Unless you need to change the default behavior, you typically do not need to configure this detector.

References