Skip to content

Instantly share code, notes, and snippets.

@seanieb
Last active September 16, 2023 07:56
Show Gist options
  • Save seanieb/1939fd1bc24db7980c5c0c8e09524b04 to your computer and use it in GitHub Desktop.
Save seanieb/1939fd1bc24db7980c5c0c8e09524b04 to your computer and use it in GitHub Desktop.
Prevent CSV Injection when suing user generated data
def escape_csv(user_generated_string):
"""
CSV injection esacaping for Python. Excel treats a string as active content when it encounters a
"trigger" character at the start of the string. This method returns the string with
the triger character escaped.
"""
if user_generated_string[0] in ('@','+','-', '='):
user_generated_string = "'" + user_generated_string
return user_generated_string
# Example
user_generated_string = '@bob'
print escape_csv(user_generated_string)
@ZephrFish
Copy link

I've added an updated escape, in a fork :)
The issue here isn't the @ character, or=, +, -. The problem is with the pipe (|) character, which Excel and other applications use to execute arbitrary commands. From research the best workaround is to escape the pipe character using a \.This is due to excel looking for an executable named cmd.exe however when adding a \ into the path the exe will not launch hence escaping and fixing the issue.

@fkromer
Copy link

fkromer commented Apr 1, 2020

There is no need for duplication :) defusedcsv

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment