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

[cbor] Invalid value returned for negative int32 where the absolute value is > 2^31 - 1 #124

Closed JacekLach closed 6 years ago

JacekLach commented 6 years ago

In https://github.com/FasterXML/jackson-dataformats-binary/issues/30, parsing of positive integers was fixed for the case where the uint32 value overflows a java int: https://github.com/FasterXML/jackson-dataformats-binary/blob/d8f82c788c4d8c41c59ca143caf2f989d0e9a9ae/cbor/src/main/java/com/fasterxml/jackson/dataformat/cbor/CBORParser.java#L679-L689

However, the parsing of negative numbers (major type 1) was not adjusted correctly:

https://github.com/FasterXML/jackson-dataformats-binary/blob/d8f82c788c4d8c41c59ca143caf2f989d0e9a9ae/cbor/src/main/java/com/fasterxml/jackson/dataformat/cbor/CBORParser.java#L722-L731

The cast of _numberLong = ((long) v) + -1L; does not adequately prevent overflow; if v is negative, it has to be adjusted to represent the uint32 value, and then negated:

case 2:
    {
        int v = _decode32Bits();
        if (v < 0) {
            long unsignedV = (long) v & 0xFFFFFFFFL;
            _numberLong = -1L - unsignedV;
            _numTypesValid = NR_LONG;
        } else {
            _numberInt = -v - 1;
        }
    }
    break;

Similar adjustment is required for other sizes.

As a test case, deserializing 3A 9FF0947F should produce -2683344000; currently it results in -1611623298.

cowtowncoder commented 6 years ago

Thank you for reporting this, providing fix! Will be in 2.9.3.