intel / tinycbor

Concise Binary Object Representation (CBOR) Library
MIT License
501 stars 187 forks source link

Compile library without assert #237

Closed glynj-bsquare closed 1 year ago

glynj-bsquare commented 1 year ago

I am writing code that can be given any arbitrary binary data. Normally this should be correctly formatted cbor, but may be corrupted or potentially sent maliciously to the system. I want to be able to report the erroneous data and continue the program in a graceful manner.

The simple code that should do this

      CborParser p;
        CborValue v;
        CborError e;
       if ( cbor_parser_init( data, length, 0, &p, &v ) != CborNoError ) {
            std::cout << "Failed to init parser" << std::endl;
            return;
        }
        e = cbor_value_validate_basic( &v );
        if ( e != CborNoError ) {
            std::cout << "Cbor is invalid: " << cbor_error_string(e) << std::endl;
            return;
        }

However, this asserts and the program crashes. I have also tried encapsulating all of the above within a try/catch block, but this also crashes.

The specific assertion is lora_gateway: src/cborparser.c:584: cbor_value_enter_container: Assertion "cbor_value_is_container(it)" failed. This is correct for the deliberately invalid data I have provided for a unit test.

Is there a way to compile the library so it throws errors instead of crashing or forces me to check return values?

glynj-bsquare commented 1 year ago

Solved. It turns out that the basic validation passed, and the error occurred later in the code. Replacing

e = cbor_value_validate_basic( &v );

with

e = cbor_value_validate( &v, CborValidateCompleteData );

resolved the issue.