Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Invalid UTF-8 byte sequence is accepted as valid UTF-8 by text-2.0.1 #575

Closed
fatho opened this issue Jan 18, 2023 · 8 comments · Fixed by #582
Closed

Invalid UTF-8 byte sequence is accepted as valid UTF-8 by text-2.0.1 #575

fatho opened this issue Jan 18, 2023 · 8 comments · Fixed by #582
Milestone

Comments

@fatho
Copy link

fatho commented Jan 18, 2023

I found a weird quirk/bug in the UTF-8 decoding function of text-2.0.1. In some cases (given enough padding around it), the decodeUtf8 function will accept an invalid byte sequence as valid UTF-8, as demonstrated by the following reproducer I ran with GHC 9.4.4 (which comes with text 2.0.1).

As you can see, the input contains a byte with the highest bit set, meaning it should be part of a multi-byte UTF-8 sequence. This byte alone is invalid. And indeed, if we try to decode a singleton bytestring consisting of just that byte, we'll get the expected exception.
However, adding sufficient padding around the invalid byte appears to make the validation pass, as witnessed by the second decoding call.

import Control.Exception
import qualified Data.Text.Encoding as Enc
import qualified Data.ByteString as BS

main :: IO ()
main = do
  -- This byte has the high bit set and thus is not valid UTF 8 by itself
  let simpleInvalidUtf8 = BS.pack [216]

  -- Correctly prints error
  testDecoding simpleInvalidUtf8

  -- Pad the invalid character with spaces
  let paddedInvalidUtf8 = BS.pack $ replicate 127 32 <> [216] <> replicate 128 32

  testDecoding paddedInvalidUtf8


testDecoding :: BS.ByteString -> IO ()
testDecoding input = do
  let
    decode = do
      result <- evaluate $ Enc.decodeUtf8 input
      putStrLn $ "Decoded " <> show input <> " to " <> show result

  catch decode $ \exc -> do
    putStrLn $ "Decoding " <> show input <> " failed with: " <> show (exc :: SomeException)

Reproducer output:

Decoding "\216" failed with: Cannot decode byte '\xd8': Data.Text.Internal.Encoding: Invalid UTF-8 stream
Decoded "                                                                                                                               \216                                                                                                                                " to "                                                                                                                               \1440                                                                                                                               "
Since I saw that text employs some fancy SIMD algorithms, my CPUID flags might also be relevant, so here they are.
flags		: fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc art arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc cpuid aperfmperf pni pclmulqdq dtes64 monitor ds_cpl vmx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault epb invpcid_single ssbd ibrs ibpb stibp ibrs_enhanced tpr_shadow vnmi flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid mpx rdseed adx smap clflushopt intel_pt xsaveopt xsavec xgetbv1 xsaves dtherm ida arat pln pts hwp hwp_notify hwp_act_window hwp_epp pku ospke md_clear flush_l1d arch_capabilities

For comparison, running the same reproducer with GHC 9.2.5 (which ships text text-1.2.5.0), it prints two errors (as I would expect):

Decoding "\216" failed with: Cannot decode byte '\xd8': Data.Text.Internal.Encoding.decodeUtf8: Invalid UTF-8 stream
Decoding "                                                                                                                               \216                                                                                                                                " failed with: Cannot decode byte '\xd8': Data.Text.Internal.Encoding.decodeUtf8: Invalid UTF-8 stream
@Bodigrim Bodigrim transferred this issue from haskell/text Jan 18, 2023
@Bodigrim
Copy link
Contributor

Bodigrim commented Jan 18, 2023

This is actually a problem with UTF-8 decoding in bytestring, the issue with text is just a consequence:

import qualified Data.ByteString as BS

main :: IO ()
main = do
  -- This byte has the high bit set and thus is not valid UTF 8 by itself
  let simpleInvalidUtf8 = BS.pack [216]

  -- Correctly says False
  print $ BS.isValidUtf8 simpleInvalidUtf8

  -- Pad the invalid character with spaces
  let paddedInvalidUtf8 = BS.pack $ replicate 127 32 <> [216] <> replicate 128 32

  -- Incorrectly says True
  print $ BS.isValidUtf8 paddedInvalidUtf8

CC @kozross

@Bodigrim
Copy link
Contributor

I'm currently on ARM so referring to cbits/aarch64/is-valid-utf8.c, but AVX2 implementation (which @fatho is running) has the same structure.

The input string is structured that way that a) the first chunk is a valid partial input, ending with a start of multibyte sequence b) the second chunk is completely ASCII.

// Check if we have ASCII
if (is_ascii(inputs)) {
// Prev_first_len cheaply.
prev_first_len = vqtbl1q_u8(first_len_tbl, vshrq_n_u8(inputs[3], 4));
} else {

I don't quite comprehend this, but my suspicion is that we are so happy to consume a full chunk of ASCII bytes that we eagerly forget the decoding state at which the previous chunk has ended.

@kozross
Copy link
Contributor

kozross commented Jan 18, 2023

@Bodigrim - that's my suspicion as well. I'll take a look when I can.

@fatho
Copy link
Author

fatho commented Jan 20, 2023

Thanks for looking into it! I did some further experimentation, and it seems that there is something else going on, besides the chunk-boundary case you suspect in bytestring.

In both reproducers, I increased the number of leading padding spaces to 128.

Now, the following bytestring reproducer expectedly prints False two times (consistent with your observation).

import qualified Data.ByteString as BS

main :: IO ()
main = do
  -- This byte has the high bit set and thus is not valid UTF 8 by itself
  let simpleInvalidUtf8 = BS.pack [216]

  -- Correctly says False
  print $ BS.isValidUtf8 simpleInvalidUtf8

  -- Pad the invalid character with spaces
  let paddedInvalidUtf8 = BS.pack $ replicate 128 32 <> [216] <> replicate 128 32

  -- Incorrectly says True
  print $ BS.isValidUtf8 paddedInvalidUtf8

However, this reproducer using the text library still claims to have decoded the second invalid string:

import Control.Exception
import qualified Data.Text.Encoding as Enc
import qualified Data.ByteString as BS

main :: IO ()
main = do
  -- This byte has the high bit set and thus is not valid UTF 8 by itself
  let simpleInvalidUtf8 = BS.pack [216]

  -- Correctly prints error
  testDecoding simpleInvalidUtf8

  -- Pad the invalid character with spaces
  let paddedInvalidUtf8 = BS.pack $ replicate 128 32 <> [216] <> replicate 128 32

  testDecoding paddedInvalidUtf8


testDecoding :: BS.ByteString -> IO ()
testDecoding input = do
  let
    decode = do
      result <- evaluate $ Enc.decodeUtf8 input
      putStrLn $ "Decoded " <> show input <> " to " <> show result

  catch decode $ \exc -> do
    putStrLn $ "Decoding " <> show input <> " failed with: " <> show (exc :: SomeException)

That behavior persists even with more padding, but the amount of padding in my initial example was the least amount of padding necessary to trigger this bug.

Is that something you can reproduce as well?

@Bodigrim
Copy link
Contributor

@fatho I can reproduce your example, but the root cause is the same. When text parses a bytestring, which is reported as invalid, it parses the first byte first (which succeeds) and then retries with the rest (which leaves us with 127+1+128, which again succeeds due to the bug).

@fatho
Copy link
Author

fatho commented Jan 25, 2023

@Bodigrim Thanks for your explanation. The "parse one byte, then retry the rest"-part sounded like an accidentally-quadratic algorithm to me, so I wrote a reproducer for that and opened another issue to not derail this comment thread: haskell/text#495

@Bodigrim
Copy link
Contributor

@kozross could you possibly take a look at this? I prepared regression tests in #578.

@kozross
Copy link
Contributor

kozross commented Feb 22, 2023

@Bodigrim - sorry for my lack of response: work's been busy. I've got approval for two full workdays to chase this, but I'm just stitching up something more urgent. I'll let you know once I'm available to deal with this.

Thanks for the regression tests - they'll help get this sorted.

@Bodigrim Bodigrim added this to the 0.11.5.0 milestone Apr 25, 2023
clyring pushed a commit that referenced this issue Jun 13, 2023
* Refactor isValidUtf8 tests to enable shrinking

* Test isValidUtf8 on strings which are almost valid, with long ranges of ASCII

* Repair invalid UTF-8 issue, more tests

* Fix NEON ASCII check

* Refactor isValidUtf8 tests to enable shrinking

* Test isValidUtf8 on strings which are almost valid, with long ranges of ASCII

* Use ctzll to ensure 8 bytes get processed

* Set -fno-strict-aliasing

---------

Co-authored-by: Bodigrim <[email protected]>
clyring pushed a commit that referenced this issue Jun 13, 2023
* Refactor isValidUtf8 tests to enable shrinking

* Test isValidUtf8 on strings which are almost valid, with long ranges of ASCII

* Repair invalid UTF-8 issue, more tests

* Fix NEON ASCII check

* Refactor isValidUtf8 tests to enable shrinking

* Test isValidUtf8 on strings which are almost valid, with long ranges of ASCII

* Use ctzll to ensure 8 bytes get processed

* Set -fno-strict-aliasing

---------

Co-authored-by: Bodigrim <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants