645 points · by rpenm · 9y ago · 188 comments
>Unfortunately that’s not the end of the story. The character might not show up, but it is still there. A quick string length check with =LEN(D4) will confirm that.
The documented way is prefixing with a ' character. It doesn't have the length issue either.
As to the root issue, I can't think of any perfect way to transfer a series of values between applications that apply different types to those values and applications that don't. At some point, something is going to have to guess.
It is suggested in comments, but the author answered
> Yes, this prevents formula expansion... once. Unfortunately Excel's own CSV exporter doesn't write the ', so if the user saves the ‘safe’ file and then loads it again all the problems are back.
:-/
As someone mentioned elsewhere this is an issue with long numbers. Excel converts them to scientific notation. Reformat and export, all good. Reopen said file, back to scientific notation.
Really anything that relies on an escape character (') or a specific format gets lost on export to CSV. It exports correctly but there is simply no way to document these formats in a CSV file and have it be compatible with anything but Excel.
Not the best experience :(
Amazing.
Technically it's exported and imported I suppose, but it makes no difference to the user.
Interestingly, in Excel removing the quotes entirely also causes a formula to be interpreted as a formula and text (even with spaces) as text and numbers as numbers.
In my testing, quotes are only needed when a field contains a comma to prevent it being interpreted as a delimiter.
If we thought about it as an API mechanism, we would parse the strings and apply rules to sanitise or reject it.
Here is a principle for thinking about data. Distinguish internal data structures (persistence, search) from interchange structures (APIs). Codebase A should not be able to directly access the structures of Codebase B. To communicate, they must use explicit APIs.
At the moment, this principle is not mainstream. The CSV loader is not sure if it is loading an interchange format or persistence format. Another, that happens regularly: (1) developer builds a database as a storage mechanism. (2) developer decides to have other separate codebases query into that database. Is the database an application-data-structure (interal) or an API (external)? It is acting as both.
Analogy: people think PDF files are safe, but aren't aware of the constant stream of RCE vulnerabilities that is Acrobat Reader & how widely it's used, which invalidates their model of behaviour associated with PDF files.
1,foo,'=SUM(A1:A10),bar
and open it, then the single apostrophe is visible in the cell.
1,foo,='SUM(A1:A10),bar
So when an Excel cell contains the UPC 123456123456, we get a CSV file that contains "1.23456E+11", which is worse than useless.
The hardest ones to work with were the mom and pop shops who suddenly had some success on Amazon and came to us after fulfilling out of their garage for a year and a half. Try telling a semi-retired 60 year old electrician in the middle of Iowa that the file he sent is worthless because none of the product codes match what you have, especially when once he closes the file he doesn't have any idea where it is.
It was hard to decide what I hated most about the project. The mind numbing stupidity of it. That fact that managers had allowed this single point of failure, and then let the guy leave. Or... that it was all a fictitious dance, pursued because spinning off their trading operations, would get them millions in tax subsidies.
The worst part is that it's not something that can be solved with an external dependency on some new startup - that would just add another layer we'd have to go through in the error cases, which would be numerous.
God, I wish I could share some of the files we've received. I cannot conceive what sort of monster would write a data exporter that would produce these unreadable things.
I ask for XLSX files since at least it's structured, unambiguous and documented, but even better: a minimal XLSX parser is trivial (about a page) to write.
Also: Educating users on how to specify the character set in every application that the user seems to want to use is a special kind of hell.
People use Excel when they should really use a database, they use it because they want to format something on a 2-d grid, edit tabular data, make plots, do calculations, make projections, etc.
The problems go down to the data structures in use.
For instance there is nothing 2-dimensional about financial reports (and projections), really financial reports are hyperdimensional. Proper handling of dates and times is absolutely critical. Also the use of floating point with a binary exponent is a huge distraction in any kind of math tools aimed at ordinary people. (Mainframes got that right in the 1960s!)
Google Sheets is just a stripped down version of Excel and other than the ability for multiple people to work on it simultaneously, is really no better.
Excel for all its faults is easy for beginners to pick up. Semi-technical people can quickly hack together a bug-ridden prototype of their ideas. In most companies the alternative is not well-written software, but spending countless meetings to get IT to spend millions to provide a bug-ridden prototype in a few years time.
One of the main problems with Excel as I can see it is that it is effectively a write-only language. Auditing an Excel sheet is famously almost impossible. And that's before you add VBA in the mix.
Since I mentioned PHP: one of the best things I can say about the language and its ecosystem is that they made it really easy to add a 'web-counter' to your otherwise late 90s static html-only page on shared hosting. You begin with a web-counter, and then just keep on copy-and-pasting.. Haskell is not nearly that easy to pick up, even if you are prepared to do it badly.
It's really a missed opportunity. Had they had the balls to actually specify CSV properly this wouldn't be nearly as much of a problem. This would have probably left a lot of the existing CSV writers non-conformant, but it would have likely improved the future situation considerably.
It doesn't even need to be complex. Just a few rules:
(basic CSV spec here)
1. Reserved characters are , " \
2. If a reserved character appears in a field, escape it with \
3. Alternatively you can double quote a field, in which case you only need to escape " characters in the field
4. Line endings are either CR, CR/LF, or LF. Parsers must suppport all line endings.
5. Character set is UTF-8, however the " , and \ characters must be 0x22, 0x2C, and 0x5C. Alternative language lookalike characters will not be treated as control characters.
6. Whitespace adjacent to a comma is ignored by the parser§ 2.1 says that lines end in CRLF. This is in opposition to every UNIX-based system out there (which outnumber systems that use CRLF as a line delimiter by between 2:1 and 8:1 depending on how you choose to estimate this) and means that CSV files either don't exist on Mac OS X or Linux, or aren't "text files" by the standard definition of that term -- both absolutely silly conclusions! Nevertheless, following RFC4180-logic, § 2.6 thus suggests that a bare line-feed can appear unquoted.
§ 2.3 says the header is optional and that a client knows if it is present because the MIME type says "text/csv; header" then § 3 admits that this isn't very helpful and clients will have to "make their own decision" anyway.
§ 2.7 requires fortran-style doubling of double-quote marks, like COBOL and SQL, and ignores that many "CSV" systems use backslash to escape quotes.
§ 3 says that the character set is in the mime type. Operating systems which don't use MIME types for their file system (i.e. almost all of them) thus cannot support any character set other than "US-ASCII".
None of these "suggestions" are true of any operating system I'm aware of, nor are they true of any popular CSV consumer; If a conforming implementation of RFC4180 exists, it's definitely not useful. In fact, one of the citations (ESR) says:
The bad results of proliferating special cases are twofold. First, the complexity of the parser (and its vulnerability to bugs) is increased. Second, because the format rules are complex and underspecified, different implementations diverge in their handling of edge cases. Sometimes continuation lines are supported, by starting the last field of the line with an unterminated double quote — but only in some products! Microsoft has incompatible versions of CSV files between its own applications, and in some cases between different versions of the same application (Excel being the obvious example here).
A better spec would be honest about these special cases. A "good" implementation of CSV:
• needs a flag or switch indicating whether there is a header or not
• needs to be explicitly told the character set
• needs a flag to specify the escaping method \ or ""
• needs the line-ending specified (CR, LF, CRLF, [\r\n]{1,}, or \r{0,}\n{1,})
... and it needs all of these flags and switches "user-accessible". RFC4180 doesn't mention any of this, and so anyone who picks it up looking for guidance is going to be deluded into thinking that there are rules for "escaping double quotes" or "commas" or "newlines" that will help them consume and produce CSV files. Anyone writing specifications for developers who tries to use RFC4180 for guidance to implement the "import CSV files" feature is going to be left to dry.
The devil has demanded I support CSV, so the advice I can give to anyone who has received a similar requirement:
• parse using a state machine (and not by recursive splitting or a regex-with-backtracking).
• use heuristics to "guess" the delimiter by observing that a file is likely rectangular -- tricky, since some implementations don't include trailing delimiters if the trailing values in a row are missing. I use a bag of delimiters (, ; and tab) and choose the one that produces the most columns, but has no rows with more columns than the first.
• use heuristics to "guess" the character set especially if the import might have come from Windows. For web applications I use header-hints to guess the operating system and language settings to adjust my weights.
• use heuristics to "guess" the line-ending method. I normally use whatever the first-line ends in unless [\r\n]{1,} produces a better rectangle and no subsequent lines extend beyond the first one.
A successful and fast implementation of all of these tricks is a challenge for any programmer. If you guess first, then let the user guide changes with switches, your users will be happiest, but this is very relative: Users think parsing CSV is "easy" so they're sure to complain about any issues. I have saved per-user coefficients for my heuristic guesses to try and make users happier. I have wasted more time on CSV than I have any other file format.
My advice is that we should ignore RFC4180 completely and, given the choice, avoid CSV files for any real work. XLSX is unambiguous and easy enough that a useful implementation takes less space than my criticism of CSV takes- and weirdly enough- many uses of "CSV" are just "I want to get my data out of Excel" anyway.
The comma-separated-value file almost certainly comes from list-directed I/O in Fortran, which used doubling of quote characters to "escape" them. This was probably an IBM-thing since other IBM-popularised languages also do this (including SQL and COBOL). As someone else pointed out, RFC4180's own interpretation of "csv" also does this.
My guess is that they did this because parsing and encoding was simple (only a few instructions) on these systems and required no extra memory.
What are the downsides of using it for ~everything?
But at least the work has been done for me.
A rather more manageable read can be found at https://github.com/woahdae/simple_xlsx_reader/blob/master/li... which seems to illuminate the basics of the xlsx format in exactly the way I was hoping.
My php-based xlsx parser is about 100 lines. If you don't need time series you can save almost twenty lines. Strings cost about ten lines. Even still, whilst it may not support every string-type or every time format, it is more reliable than any CSV parser...
01101 -> 1101
ASCII had addressed the problem of separating entries ever since its creation: Separator control codes. There are:
x01 SOH "Start of Heading"
x02 STX "Start of Text"
x03 ETX "End of Text"
x04 EOT "End of Transmission"
x1C FS "File Separator"
x1D GS "Group Separator"
x1E RS "Record Separator"
x1F US "Unit Separator"
You can use those just fine for exchanging data as you would using CSV, but without the ambiguities of separation characters and the need to quote strings. Heck if payload data is limited to the subset ASCII/UTF-8 without control codes you can just dump anything without the need for escaping or quoting.
So my suggestion is simple. Don't use CSV or "P"SV (printable separated values). Use ASV (ASCII separated values).
I predict this will never happen under the principle of "good enough to use, bad enough to complain on HN." My point is that people keep suggesting ASCII delimiters as if it's some obvious solution that solves the entire problem, but it doesn't. People should instead be suggesting that text editors better support ASCII delimiters so that we can use them roughly as easily as we use commas today.
Sure, if you're building some kind of system where you need to ingest data from one application from another application you control, then using a different interchange format like ASV is an option. But then people tend to use more powerful formats like JSON or XML.
That, and data in CSV format is human readable in any old text editor or even work processor which many use as a quick sanity check to make sure their data looks sane. A lot of editors will not display the ASCII control characters at all so the fields on the line get mashed together, or may even reject the file as containing what it considers to be unexpected characters.
While it's great to hope to use a well defined transport for machine-to-machine communication, it's exhausting to explain anything beyond CSV to Bob from sales.
Worse; most 'non computer people' cannot get them imported into a spreadsheet properly (for whatever reason; usually it just puts everything in one field or column, people curse and give up), so they have to edit them in Notepad or worse, in MS Word and then send them back.
Not really seeing the beauty I guess.
:help digraph
:help digraph-table
Feel free to implement mappings for quickly accessing these digraphs. Those pesky F<n> keys are perfect for this. Easy to reach, gets the job done.
ASCII Name - Vim Insert - Visual Repr
--------------------------------------------------
Start of Heading - Ctrl-v Ctrl-a - ^A
Start of Text - Ctrl-v Ctrl-b - ^B
End of Text - Ctrl-v Ctrl-c - ^C
End of Transmission - Ctrl-v Ctrl-d - ^D
File Separator - Ctrl-v Ctrl-\ - ^\
Group Separator - Ctrl-v Ctrl-] - ^]
For insertion you can also always just Ctrl-v DDD or Ctrl-v xHH where DDD is the three digit decimal value or HH is two hex values of the ascii code.Accordingly, the reference to "54 year old" appears to be to the first standard as well as first commercial use of ASCII, in 1963.
That first ASCII standard from 1963 specified eight "separators" simply named S0 through S7 at codes 0x18--0x1F. The 1965 update reused the first four for other purposes (eg cancel and escape) and labeled 0x1C--0x1F with the more descriptive names we now know.
I know the response will be "they'll just open it in Excel anyway" which is true in most cases, but I frequently have clients that want to download an export, modify it real quick with a text editor (many use Notepad++ for this), and then reupload it. They're usually doing massive find/replaces on the data and then reuploading into the system and a simple text editor is a lot better for this than Excel.
If Excel decides that text between Start of Text and End of Text that begins with a "=" is a formula, then you're in the same spot.
I use CSV all the time when I am working with R. My data can come in the form of CSV, XLS, or PDF. Which would you want to work with?
I can easily look at the data. I never touch my incoming data and my output is in reports, but CSV can be the easiest way to get data into a computer.
"ASV" is only a viable option if you then also use your time machine to go back 40 years and make everyone start using it then.
CSV -> import on web app -> SQLi
Malicious input -> CSV download from web app -> Excel -> formula -> sneaky data exfil
CSV -> JS -> import into web app XSS (in places no other XSS existed because of the data)
CSV import -> weird CSV header -> arbitrary data loading (headers were column names.... Schema injection .. like SQLi only more hilarious
Point is apps and devs can have blind spots (knowledge gaps) or just not think of a CSV import or export like other functionality.
>calling a pentested a script kiddie
welp, my work is done here
Filtering user inputs is security 101, yet we missed this while focusing on fancy defense mechanics. This large gap between what the engineering team prepared for, and how they were exposed, is what made the outcome "embarrassing" - hence I agreed with GP that CSV/Excel stuff could be a blind spot even for well-trained people.
That isn't really true. Why does the intended format of the input matter regarding veracity?
To get comma separated CSVs to show properly in Excel we have to mess around with OS language settings. CSV as a format should have died years ago, it's a shame so many apps/services only export CSV files. Many developers (mainly US/UK based) are probably not aware of how much of a headache they inflict on people in other countries by using CSV files.
Why? Aren't the import settings enough?
https://support.office.com/en-us/article/Text-Import-Wizard-...
I'm not just being pedantic, it makes a big difference. If I want to change some values in a spreadsheet I should be able to just open it, change the values, save, and be certain that the document will be identical apart from the deliberate changes. This is especially important for CSV files, which are commonly used for import/export operations.
Semicolons are really better though, because they aren't used as a decimal separator unlike commas in most countries.
I don't know about Excel, but LibreOffice allows very easily to select which parameters to use when opening a CSV file, it works just fine.
If you're going to separate values with semicolons--which is perfectly reasonable--I feel like you probably shouldn't do that with a format called Comma Separated Values.
0x1C FS File Separator
0x1D GS Group Separator
0x1E RS Record Separator
0x1F US Unit Separator
You just need a font with glyphs for them.https://en.wikipedia.org/wiki/Delimiter#ASCII_delimited_text
P.S. Aren't .xlsx files subject to the same problem as the .csv?
[1] https://genomebiology.biomedcentral.com/articles/10.1186/s13...
EDIT: LibreOffice also allows you to tell it what encoding a file uses and what character(s) are used as separators.
In any case, I imagine the Ensembl ID is still safer than other encodings in the case of invertebrates. For example, genes IDs in the Fruit fly genome look like FBgn0034730.
Some things I dislike about CSV:
* No distinction between categorical data and strings. R thinks your strings are categories, and Pandas thinks your categories are strings.
* I'm not a fan of the empty field. Pandas thinks it's a floating point NaN, while R doesn't. So is it a NaN? Is it an empty string? Does it mean Not Applicable? Does it mean Don't Know? Maybe it should be removed altogether.
* No agreement about escape characters.
* No agreement about separator characters.
* No agreement about line endings.
* No agreement about encoding. Is it ASCII, or UTF-8, or UTF-16, or Latin-whatever?
* None of the choices above are made explicit in the file itself. They all have the same extension "CSV".
These use up a bit of time whenever I get a CSV from a colleague, or even when I change operating system. Sometimes I end up clobbering the file itself.
Good things: * Human readable. * Simple.
I think the addition of some rules, and a standard interpretation of them, could go some way to improving the format.
The thing you use CSV for is not it's technical merit. You use CSV for its ubiquity. If you nailed down all those things you talk about, you would have a much, much smaller user base and there would be no reason to use CSV in the first place.
(Hey, this reminds me of a similar situation governing s/CSV/C/g...)
I think this is more of an R-ism than a standardization issue. Strings are a pretty universal data type, where as categorical data (factors) are mostly specific to the domain of statistical modeling. IMO Python is doing the correct thing here. Personally I find factors to be more trouble than they are worth, and fortunately `data.table::fread` mimics Python in this regard.
Why would these apps go off executing code from a text file? How odd.
Is there a way to tell Excel or Sheets to open a CSV file without executing code?
or at least this the most logical explanation I could find.
I have never seen a way to disable a full recalculation when Excel opens a CSV file, which beyond the security implications is painful for people like me who keep their calculations on manual because I often have very heavy workbooks opened all the time.
This one is your data turned out to be code. There are many, many books on all the various forms this takes. Memory corruption cat and mouse..... It is a long complex story that we can sweep up to that generalization. But it is important to know that high, medium, and low level of these issues. They form a gigantic tree. The medium level somewhere between is where devs need to threat model most of the time. But some of the time things are very specific and you just need to know about the specific thing and not it's various generalized forms, because the specific thing can really matter. E.g. simple programming mistakes lead to side channels, etc. We can generically understand a side channels easily. But it takes a ton of specific hard earned knowledge to avoid it.
I agree, it catches people off guard to think CSV files once interpreted can do more than give columns of information, but it's not an injection which is my beef.
(But please, just do me a small favor and don't submit any reports for SQL injection or information disclosure if you're using the SQL-like API that we expressly provide for the purpose of accessing public data. We get a couple clueless people sending such reports every week.)
Makes me wanna troll ops people at my own startup just for funsies.
A more common format is TSV (TAB delimited) which makes a lot more sense, however the best choice when importing data in Excel is still to change the file extension to a non-recognized extension (like - say - .txt) and in the "import wizard" set the appropriate separator and set all columns as "text".
>CSV files are just text files (the format is defined in RFC 4180) and evaluating formulas is a behavior of only a subset of the applications opening them - it's rather a side effect of the CSV format and not a vulnerability in our products which can export user-created CSVs. This issue should mitigated by the application which would be importing/interpreting data from an external source, as Microsoft Excel does (for example) by showing a warning. In other words, the proper fix should be applied when opening the CSV files, rather then when creating them.
[0]: https://sites.google.com/site/bughunteruniversity/nonvuln/cs...
Their policy makes it sound like that the second vulnerability should indeed be fixed in Google Sheets itself (it is the one opening the file, after all)
CSVs are still the most portable format for moving data around despite all of their evils of escaping characters, comma delimitation, etc...
A lot of old legacy systems know CSV and its easy to inspect visually as compares to more efficient binary formats like ORC or Paquet.
Use anything else, even XLSX which is at least a typed and openly standardized format.
These vulnerabilities can't be blamed on CSV so much as on the desire of application vendors to treat data as code.
Excel conflates the idea of display format and data type which is the source of countless headaches. It is legacy pain in the purest form.
Dates are a /type/ of text; parsing dates in to machine readable formats is an /entire/ other can of spam.
http://blog.hackensplat.com/2013/09/never-sanitize-your-inpu...