CsvHelper
CsvHelper copied to clipboard
CSV Injection sanitizer is being applied to numeric fields as a well as strings
Description
When using InjectionOptions
to prevent CSV injection we're finding that string fields are being escaped as expected, however this is also being applied to numeric based fields where no injection would be possible.
In some cases this results in negative numbers having the -
character stripped from the start of the value as this is one of the defaults in CsvConfiguration.InjectionCharacters
, e.g:
=, @, +, -, \t, \r
To Reproduce
This issue is present when writing directly via CsvWriter
and WriteField
e.g:
CsvConfiguration config = new CsvConfiguration(CultureInfo.CurrentUICulture)
{
InjectionOptions = InjectionOptions.Strip,
};
using (var writer = new StringWriter())
using (var csv = new CsvWriter(writer, config))
{
csv.WriteField(-10);
csv.WriteField(-1234.56);
csv.WriteField("=test,data");
csv.NextRecord();
csv.Flush();
output = writer.ToString();
}
Expected result: -10,-1234.56,"test,data"
Actual result: 10,1234.56,"test,data"
It's also reproduceable when writing strongly typed models, e.g:
public class TestClass{
public int IntValue { get; set; }
public string StringData { get; set; }
public double MoneyValue { get; set; }
}
...
CsvConfiguration config = new CsvConfiguration(CultureInfo.CurrentUICulture)
{
InjectionOptions = InjectionOptions.Strip,
};
List<TestClass> tmp = new List<TestClass>()
{
new TestClass() {IntValue = 10, StringData = "=Test,data", MoneyValue = 1234.56 },
new TestClass() {IntValue = -20, StringData = "=Test,data", MoneyValue = -1234.56 }
};
using (var writer = new StringWriter())
using (var csv = new CsvWriter(writer, config))
{
csv.WriteRecords(tmp);
csv.Flush();
output = writer.ToString();
}
Expected result IntValue,StringData,MoneyValue 10,"Test,data",1234.56 -20,"Test,data",-1234.56
Actual result IntValue,StringData,MoneyValue 10,"Test,data",1234.56 20,"Test,data",1234.56
As you can see, the leading -
character is being stripped from numeric fields where no injection is actually possible.
Expected behavior The injection sanitizer to only be applied to string fields since formula injection via numeric data should not be possible.
Additional context
We recognise that we can configure CsvConfiguration.InjectionCharacters
ourselves, removing -
from the config but this weakens our protection so we would like to avoid doing this if possible.
Thank you