net/nanocoap: validate option length #10823
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Contribution description
The Buffer Append API added in #9085 uses the coap_pkt_t struct to track to amount of buffer space remaining as the CoAP PDU is built. _add_opt_pkt() is the low level function in that API to add an option to the buffer. This function uses coap_put_option() to actually write to the buffer. However, that function is part of the minimal Buffer Put API, and does not check the length of the buffer before writing. This PR updates _add_opt_pkt() to test the available buffer space before writing the option.
The PR also adds function documentation for _put_delta_optlen(), which writes the option header, and a unit test for building a message that completely fills the buffer.
The use of an assert in _add_opt_pkt() when the buffer is too small is not ideal. We plan to create a follow-on PR that returns a negative value from the function so the caller can recover.
Testing procedure
The 'tests-nanocoap' unit tests include a new test, test_nanocoap__option_add_buffer_max(), which completely fills the buffer used to write a request. Run 'tests-nanocoap' both without and with assertions enabled (compile with FORCE_ASSERTS=1). Both runs should pass.
Next, manually reduce the size of the buffer in the new test from 70 to 69 and rerun the tests. Without asserts, on native the test fails abruptly when the buffer overflows ("stack smashing detected"). With asserts enabled, the relevant assert in _add_opt_pkt() is tripped.
Issues/PRs references
-none-