FasterXML / jackson-dataformats-binary

Uber-project for standard Jackson binary format backends: avro, cbor, ion, protobuf, smile
Apache License 2.0
310 stars 133 forks source link

Unexpected `ArrayIndexOutOfBoundsException` in `CBORParser` for corrupt String value #464

Closed arthurscchan closed 8 months ago

arthurscchan commented 8 months ago

The CBORParser::_finishShortText(int) method relies on the integer index _inputPtr to read the next character from the provided input byte array. It takes in an integer len to determine how many characters are needed to read from the byte array input. In the method, there is a while loop to read all the needed characters. One of the exit points of the while loop is when the integer end is reached where end is calculated by _inputPtr + len. Because len is read from the input and could be malformed, a very large len could make the end variable much larger than the size of the input byte array buffer. This could cause ArrayIndexOutOfBoundsException when the while loop does not exit correctly with a large end value. It could also throw ArrayIndexOutOfBoundsException if inPtr already pointing at the end of inputBuf when entering the while loop. Last but not least, if the provided len is negative, the end value is almost certain to be negative and it results in the same situation as the first case.

        while ((i = inputBuf[inPtr]) >= 0) {
            outBuf[outPtr++] = (char) i;
            if (++inPtr == end) {
                String str = _textBuffer.setCurrentAndReturn(outPtr);
                if (stringRefs != null) {
                    stringRefs.stringRefs.add(str);
                    _sharedString = str;
                }
                return str;
            }
        }

The suggested fix is to add a check before entering the while loop to ensure the end is not larger than the size of the inputBuf byte array.

We found this issue by OSS-Fuzz and it is reported in https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=65722.