intel / tinycbor

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

cbor_value_copy_byte_string causes stack corruption #194

Closed StefanHri closed 3 years ago

StefanHri commented 3 years ago

The documentation of the function cbor_value_copy_byte_string says:

If the buffer is large enough, this function will insert a null byte after the last copied byte, to facilitate manipulation of null-terminated strings. 

However, the null byte is appended without checking if the size of buffer:

CborError _cbor_value_copy_string(const CborValue *value, void *buffer,
                                 size_t *buflen, CborValue *next)
{
    bool copied_all;
    CborError err = iterate_string_chunks(value, (char*)buffer, buflen, &copied_all, next,
                                          buffer ? (IterateFunction) value->parser->d->cpy : iterate_noop);
    if (err) {
        return err;
    }

    if (!copied_all) {
        return CborErrorOutOfMemory;
    }

    if (buffer) {
        *((uint8_t *)buffer + *buflen) = '\0';
    }

    return CborNoError;
}

This causes that one byte belonging to some other variable is overwritten.

thiagomacieira commented 3 years ago

I can't find this version of the code. What version of TinyCBOR are you using?

The function _cbor_value_copy_string was introduced in commit ff130bc339dbc0ae1fceca2949858b8ebad909ca and did not look like that. The braces in the function also do not match the coding style I use.

StefanHri commented 3 years ago

I am using TinyCBOR from ZephyrOS https://github.com/zephyrproject-rtos/tinycbor/blob/31ae89e4b768612722620cb6cb173a0de4a19cc9/src/cborparser.c#L1292

thiagomacieira commented 3 years ago

Please report to them. Their copy is modified.