Sanitize data for CSV generation

CSV generation is not fully sanitized to prevent CSV injection.
According to https://owasp.org/www-community/attacks/CSV_Injection,
we have to use the following sanitization:
 - Wrap each cell field in double quotes
 - Prepend each cell field with a single quote
 - Escape every double quote using an additional double quote

The patch https://review.opendev.org/c/openstack/horizon/+/679161
takes care of the double quotes. This patch adds a single quote to
the cell fields beginning with specific characters, so their content
will be read by a spreadsheet editor as text, not a formula.

Closes-Bug: #2048106

Change-Id: I882fe376613ff1dc13a61f38b59d2a2567dbba7d
This commit is contained in:
Tatiana Ovchinnikova 2024-03-21 15:43:39 -05:00
parent da8e959298
commit c6bba842af
2 changed files with 6 additions and 3 deletions

View File

@ -57,7 +57,10 @@ class CsvDataMixin(object):
self.writer.writerow([self.encode(col) for col in args])
def encode(self, value):
return str(value)
data = str(value)
if data and data[0] in ('=', '+', '-', '@', chr(9), chr(13)):
return "'" + data
return data
class BaseCsvResponse(CsvDataMixin, HttpResponse):

View File

@ -1226,10 +1226,10 @@ class UsageViewTests(test.BaseAdminViewTests):
hdr = ('"Instance Name","VCPUs","RAM (MB)","Disk (GB)",'
'"Usage (Hours)","Age (Seconds)","State"')
self.assertContains(res, '%s\r\n' % hdr)
usage_1_quoted = ('"=cmd|\' /C calc\'!A0","1","512","0","122.87",'
usage_1_quoted = ('"\'=cmd|\' /C calc\'!A0","1","512","0","122.87",'
'"442321","Active"')
self.assertContains(res, '%s\r\n' % usage_1_quoted)
usage_2_quoted = ('"=cmd|\' /C calc\'!A0","1","512","0","2.61",'
usage_2_quoted = ('"\'=cmd|\' /C calc\'!A0","1","512","0","2.61",'
'"9367","Active"')
self.assertContains(res, '%s\r\n' % usage_2_quoted)