Skip to content

The server returns invalid JSON #3301

Open

Description

@AtnNn

In python 2, with a driver modified to print raw query results:

>>> r.expr(u"—").run()
RAW RESPONSE: '\'{"t":1,"r":["\\xe2\\x80\\x94"]}\''
u'\u2014'

\x is accepted by python's JSON parser, but at far as I can tell it is invalid JSON. The standard way to escape arbitrary unicode characters is `\uXXXX.

The server itself does not handle \x escapes in JSON strings:

>>> r.json("[\"\\xe2\\x80\\x94\"]").run()
[u'xe2x80x94']

The server also gladly converts non-utf-8 strings into JSON:

>>> r.expr(u"—").split("").run()
RAW RESPONSE: '\'{"t":1,"r":[["\\xe2","\\x80","\\x94"]]}\''
UnicodeDecodeError: 'utf8' codec can't decode byte 0xe2 in position 14: invalid continuation byte

I believe the server should not blindly convert non-utf-8 strings into datums:

  • as the result of operations like split
  • when parsing protobuf queries
  • when reading older documents from disk

It should perhaps convert them to binary or error out instead.

Activity

  1. added this to the subsequent milestone on Nov 6, 2014
  2. danielmewes commented on Nov 6, 2014

    @danielmewes
    Member

    @AtnNn Do you think this could cause issues with other drivers? Does the server return invalid JSON in response to putting in valid JSON?

  3. AtnNn commented on Nov 6, 2014

    @AtnNn
    MemberAuthor

    The JavaScript and Ruby drivers accept non-utf-8 strings in the server response. The Python driver and Haskell driver do not.

    In the first and third examples, valid JSON sent to the server, and the server returns invalid JSON. It the second example, non-standard JSON sent to the server is interpreted in a different way that most JSON parsers.

  4. mlucy commented on Nov 6, 2014

    @mlucy
    Member

    sharpens cJSON murdering knife

  5. danielmewes commented on Nov 11, 2014

    @danielmewes
    Member

    (Just had PHP choke on a non-UTF8 string returned by the server.)

  6. gchpaco commented on Nov 15, 2014

    @gchpaco
    Contributor

    I had a discussion with @danielmewes the other night that amounted to the following.

    1. Now that we have an r.binary type we really shouldn't go around accepting bizarre strings; we should accept that we must do at least some processing of Unicode strings to make UTF-8 work. We should trigger an error if you pass non-UTF-8 data (and yes this will probably break somebody's stuff, so we'll need to think about what we want to do if there's terrible data already in the database that someone wants to read out). This will require at minimum rebuilding people's sindexes, and possibly altering the main btree index in the event that somebody managed to store a denormalized key. This is a headache, but we are demonstrably doing the wrong thing here.
    2. We should never emit denormalized strings and we should always normalize strings on input. Unicode normalization is an algorithm defined by the Unicode committee that is semantically lossless. We should absolutely not write our own normalization algorithm; we should use the one from ICU. ICU is capable of using UTF-8. There are four different normalization algorithms depending on what you want; we should use NFC, as NFKC is not appropriate for our application.
    3. We should absolutely not support any form of input other than UTF-8 (possibly we should accept CESU-8 for cross compatibility, but certainly we should never emit it). If we use ICU as I advocate, this is a non-issue.
    4. Folks who want to store text encoded in Shift JIS or for that matter in EBCDIC are welcome to use r.binary as normal, which will roundtrip the text unmolested.

    For those unfamiliar with what normalization does, consider é. There are two ways of encoding that character in Unicode; either as the single code point U+00E9 or as the character sequence U+0065, U+0301. These exist because not every combination of letters and diacritical marks used in human languages exists as a discrete code point in Unicode. Multiple diacritical marks are also possible, which raises an ordering problem; consider for example the Vietnamese name "Bằng", with two diacritics on the "a".

    One potential headache with adopting UTF-8; UTF-8 can contain NULL characters (that is, U+0000); this is a particular nuisance with cJSON and perhaps a good reason to abandon it. Our other strings use Pascal style by and large but somebody should probably go through and verify that we are null byte safe. There are "alternate UTF-8 encodings" that do not have this issue (for example Java's "modified UTF-8" through the serialization process, which encodes U+0000 as 0xC0,0x80, or CESU-8 which is a bizarre thing that Oracle and MySQL think are UTF-8) but our wire protocol absolutely should be UTF-8 with null bytes intact.

  7. gchpaco commented on Nov 15, 2014

    @gchpaco
    Contributor

    @VeXocide points out that the ECMA standard for JSON is online as ECMA-404 and a competing standard is RFC-7159. ECMA-404 defines the language on Unicode code points, specifically on ISO 10646:2012, RFC-7159 defines the language on hexadecimal bit patterns, which happen to correspond to UTF-8 (and, as it happens, only UTF-8). Both standards otherwise agree, save the following bit of madness from ECMA-404:

    To escape a code point that is not in the Basic Multilingual Plane, the character is represented as a twelve- character sequence, encoding the UTF-16 surrogate pair. So for example, a string containing only the G clef character (U+1D11E) may be represented as "\uD834\uDD1E".

    Which is to be frank, horrible, but that's life.

    RFC-7159 specifies the following as far as character encoding, after having defined everything with hex digits.

    JSON text SHALL be encoded in UTF-8, UTF-16, or UTF-32. The default encoding is UTF-8, and JSON texts that are encoded in UTF-8 are interoperable in the sense that they will be read successfully by the maximum number of implementations; there are many implementations that cannot successfully read texts in other encodings (such as UTF-16 and UTF-32).
    Implementations MUST NOT add a byte order mark to the beginning of a JSON text. In the interests of interoperability, implementations that parse JSON texts MAY ignore the presence of a byte order mark rather than treating it as an error.

    I interpret this as an implicit acceptance of UTF-8 as the required standard; we may be able to support UTF-16 or UTF-32 if we go crazy, but UTF-8 is the only required one, and thus the only one I suggest we bother with.

  8. AtnNn commented on Nov 18, 2014

    @AtnNn
    MemberAuthor

    We should never emit denormalized strings and we should always normalize strings on input

    I'm not convinced we should do this.

    1. It would mean users would get out data that was different than the one they put in. This behaviour might be appropriate in other libraries or applications, but I think it is questionable whether a database should be modifying the data stored into it. As far as I can tell, most other databases do not normalize Unicode strings.
    2. OS X's file system normalizes file names to NFD. This has caused bugs in bzr, bash, python and other projects.
    3. In all languages we have drivers for, canonical-equivalent character sequences are not considered equal. Here are some examples. It would be very difficult for users writing applications in these languages to correctly handle non-normalised strings.

    However

    1. This is already the case for numbers, which get rounded to the nearest double
    2. If we had comprehensive Unicode support we could help users avoid a different category of bugs.
    3. The Unicode standard allows rewriting Unicode strings to other canonical-equivalent representations and says applications should not rely on canonical-equivalent strings being treated as distinct by other libraries.
  9. larkost commented on Nov 18, 2014

    @larkost
    Collaborator

    My vote is for UTF-normalization. While it does break the absolute round-tripping, it does so in a way that is more likely to be user-friendly. For example when someone is searching for "über" they don't really care about whether the first letter is a single code-point or two (u + ¨).

    @AtnNn does a nice job of showing the cases where (for example) Python screws up on this. But to me that is exactly why we should be doing this. For most people those combinations are the same thing, and they will only be confused when they are not. The bad examples are different at the binary level, not the meaning level.

    Normalization would mean that for all operations inside RethinkDB we would be consistent, at the cost of sometimes being inconsistent with comparisons outside of RethinkDB on round-trips. We already have the generic problem with data coming from multiple sources.

    To illustrate here are the benefits/drawbacks of a hypothetical normalizing system in Python2.7:

    twoByte = 'ü' # b'\xc3\xbc'
    oneByte = u'ü' # b'\xfc'
    
    oneByte == unicodedata.normalize('NFC', u'ü') # True
    
    # the good
    r.table('bob').insert({'id': twoByte}).run()
    list(r.table('bob').get(oneByte).run()) == [{'id': oneByte}] # True
    list(r.table('bob').get(twoByte).run()) == [{'id': oneByte}] # True
    
    # the bad
    list(r.table('bob').get(twoByte).run()) == [{'id': twoByte}] # False, it will never return the twoByte value

    Note that this is significantly harder to manually enter in bad cases in Python3.x since you have to work at it to get the twoByte version.

  10. srh commented on Nov 18, 2014

    @srh
    Contributor

    You shouldn't fuck with users' data. If a user wants their strings to be Unicode-normalized, let them normalize it themselves. The only reason given for normalizing so far is the really nerdy one, that the strings are the same on the meaning level, just not the binary level. This is completely irrelevant to how the world works. Lots of strings have the same meaning. "I am Sam." has the same meaning as " I am Sam." Yet they don't compare equal.

    Doing suprising stuff with unicode is a big source of bugs and security flaws. An example: Application logic has been added that says that a certain set of usernames should have their contact information invisible. The code checks that the requested username doesn't match any in that set, then performs the request. RethinkDB unicode-normalizes the query and returns the user's private data.

    Unless the query explicitly asks for a custom Unicode experience, rethinkdb should be treating strings like a dumb sequence of Unicode codepoints, in a way that doesn't surprise people.

  11. danielmewes commented on Nov 18, 2014

    @danielmewes
    Member

    I think we all agree that we should verify input strings to be valid UTF-8 encoded Unicode, and that we should reject the query otherwise (with the remaining question of whether and how to provide backwards compatibility for existing data).

    When it comes to normalization, there seem to be different scenarios where either behavior can be confusing for users.
    Here's my high-level recap of the issue, according to how I understand it:

    If we do normalization automatically, we get the sort of security problem that @srh mentions. In my opinion this is probably the strongest argument against general normalization of strings in RethinkDB.

    If we don't do normalization, the results of the database can be quite unexpected to a human observer (see the example by @larkost). Under certain circumstances, data inserted in one way, cannot be retrieved anymore through a different channel. For example a user might be unable to even enter a certain encoding of a character without going through great lengths (not to mention them having to figure out that there's a problem with different encodings in the first place).

    Both of these cases are going to primarily surprise users who are not aware of how unicode works.

    We can add a text type (unicode is another possible name) similar to our binary type. We would perform automatic normalization only on text-type strings.
    This would solve the problem for users who are aware of the issue, but would help little for those who are not since they wouldn't use it in the first place.

    This is my current opinion on the question:
    I used to lean towards general normalization. I think the fact that we wouldn't preserve strings in their binary form is fine. That's what we have r.binary for.
    I hadn't previously thought of the security problems that @srh mentioned though. I can totally see something like that happen, and I can think of many related scenarios that would cause similar security issues in users' applications. While storing non-normalized strings has much more potential for confusion to a human user, I'm having a much harder time thinking of security vulnerabilities which don't involve a human operator that could stem from this behavior.
    For that reason I now think generally normalizing inputs would be a bad idea given our current type system, unless we can find a way to avoid these issues.

  12. mlucy commented on Nov 18, 2014

    @mlucy
    Member

    I think we should do the following:

    • If the user inserts and retrieves a string, return the string they inserted without normalization. Doing otherwise would be confusing and a source of bugs.
    • If the user compares two strings, compare them as if they had been normalized. @AtnNn tells me that there's a fast algorithm in ICU to compare two non-normalized strings that always produces the same ordering as normalizing and then comparing those strings.
    • If the user uses a string as an on-disk key, normalize the string before calling our key serialization function on it. This might cause confusion if the user has two canonical-equivalent strings that their app thinks are different and they try to use them both as keys, but it seems better than the alternative.
    • If the user performs a Unicode-aware operation (split, upcase, match), normalize the string before performing the operation.
      • I'm a little worried about normalizing before calling match, since people might expect that the string they get out of a match group is a substring of the string they inserted, so maybe this is actually a bad idea.
  13. deontologician commented on Nov 18, 2014

    @deontologician
    Contributor

    if we normalize before comparing, then people may be surprised if they compare in application code and get a different answer.

  14. deontologician commented on Nov 18, 2014

    @deontologician
    Contributor

    I think normalization makes more sense if we add a bunch of full-text search features, where the expectation is that things are fuzzy.

  15. danielmewes commented on Nov 18, 2014

    @danielmewes
    Member

    @mlucy

    • If the user compares two strings, compare them as if they had been normalized. @AtnNn tells me that there's a fast algorithm in ICU to compare two non-normalized strings that always produces the same ordering as normalizing and then comparing those strings.
    • If the user uses a string as an on-disk key, normalize the string before calling our key serialization function on it. This might cause confusion if the user has two canonical-equivalent strings that their app thinks are different and they try to use them both as keys, but it seems better than the alternative.

    Note that this would still have the same security issues as if we normalized everything.

  16. mlucy commented on Nov 18, 2014

    @mlucy
    Member

    Note that this would still have the same security issues as if we normalized everything.

    I don't think that's true. In the specific example @srh gave, the problem was inserting Unicode data, retrieving normalized Unicode data, and then testing for set membership incorrectly. How we compare Unicode inside RethinkDB doesn't affect that.

    In general I think most bugs and confusion would come from getting out different data than you put in, not from how we compare things internally in RethinkDB. Internally we basically have to compare things correctly; doing a byte-order compare on Unicode strings doesn't make much sense.

  17. mlucy commented on Nov 18, 2014

    @mlucy
    Member

    if we normalize before comparing, then people may be surprised if they compare in application code and get a different answer.

    They would also be confused if their application code was doing "correct" Unicode comparison and we were just comparing bytes. We have to pick some definition of how strings compare, and whichever one we pick the user might pick a different one, so we might as well pick the correct one.

  18. srh commented on Nov 18, 2014

    @srh
    Contributor

    The correct one is to compare unicode code points... so pick that.

  19. danielmewes commented on Nov 18, 2014

    @danielmewes
    Member

    Maybe my understanding of @srh's example is wrong.
    So here's a slightly different one:
    Suppose you have a table where entries have different visibilities. You have "public" and "private" entries. Except that you are a French software developer and hence use the terms "public" and "privé" to represent these visibilities in your table.

    Assume that some users of your application are allowed to list either all public or private entries, but other users are only allowed to see the public ones. So you might have a URL like this (assume it's a web application):
    listEntries?userSecret=....&showVisibility=privé

    In your application, you are now going to verify the userSecret. If the user is not permitted to view private entries, you might have code that looks somewhat like this:

    if (userNotAuthorized && showVisibility == "privé") {
        echo "You are not authorized to see this.";
        return;
    }
    display(r.table("t").filter(r.row("visiblity").eq(showVisbility)).run());
    

    This is perfectly fine and safe code, as long as at the place where you insert into the table you use the same encoding of the "privé" string as in this piece of code. That is very likely, since you are probably using the same editor and language for both places (and if there's a mismatch, you will notice it since the code won't work).

    Now consider what would happen if RethinkDB normalized the strings for the purpose of comparison. An attacker could pass in a differently encoded showVisibility argument that normalizes to the same string as "privé" does. RethinkDB would happily reveal all the private entries in this case.

    I'm sure you can construct some case where a vulnerability would be avoided by normalization, but my impression is that those cases are less common. I can think of a lot of cases where code stops working properly due to a lack of normalization, but I'm having a hard time thinking of a case where it would lead to security issues.
    Generally my impression is that it's typically safer to consider two keys as non-equal when it doubt, than it is to consider them as equal. Something might stop working, but it's much less likely that you reveal secret data. I could be wrong about this though.

    There's also the interesting question of how many commonly used other systems do unicode-aware comparison and how many don't. If there's a clear majority that does it one way, we could avoid many issues by doing it the same way.

  20. srh commented on Nov 18, 2014

    @srh
    Contributor

    This is perfectly fine and safe code,

    That's actually terrible, awful code. You don't pass in data from the outside world to use directly as enumeration values in your database. (Your post shows one of the reasons why.)

  21. danielmewes commented on Nov 18, 2014

    @danielmewes
    Member

    @srh that assumes that you are aware of the fact that "equality" can have different meanings. If you are not, the code seems semantically safe (since you exclude the critical value before fetching the data).

  22. srh commented on Nov 18, 2014

    @srh
    Contributor

    No, it has nothing to do with that fact, I am talking about the practice of using unsanitized user input in general.

  23. danielmewes commented on Dec 11, 2014

    @danielmewes
    Member

    @gchpaco has implemented a UTF-8 validation step which we are going to perform on user-provided strings (but not on results of ReQL computations, such as when applying split to a Unicode string, see #2518).

    So there will still be ways to store illegal UTF-8 data in a table by applying split (and possibly some other string manipulation operations), but it will catch the most common case where users insert data that's in a different encoding.

  24. mdmdmdmd commented on Dec 11, 2014

    @mdmdmdmd

    The requirement is to use an index and the between( ) function call to reliably find a name in a variety of languages in UTF8. Maybe some interim workaround is available where the binary UTF8 and the collation is submitted to the engine for ordering purposes.

    That way, it would be application dependend on the interpretation of the raw bytes.

    In reality, there are just very focused areas that need proper utf-8 storage and utf8 query support. Generally the only reason is Name search and City Search.

    So during the discussions, maybe talk about a low-impact approach instead of a complete fork lift upgrade to get some sort of UTF8 support.

  25. tracker1 commented on Dec 16, 2014

    @tracker1

    If all input data is actually 7-bit when going to-from JSON, encoding appropriately to UCS16 "\u####" escape sequences (which require surrogate pairs for astral codes.

    As to indexes, if the data is stored binary as utf-8, that would probably be enough for most, if you need more explicit matching, you will need to do something more like "...".normalize('NFKC') for indexing or other utility methods.

  26. gchpaco commented on Jan 8, 2015

    @gchpaco
    Contributor

    @mdmdmdmd collation is on the menu, in a more localized form (the current state of the discussion is a secondary index with an attached collation locale that you query against). @tracker1 that would involve some sort of normalization, although I shie away from NFK* for most applications. This particular ticket, as I understand it, was merely to stop us accepting/emitting junk. If you want to store random bytes in your database, we have r.binary for that.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions