laurencelundblade / QCBOR

Comprehensive, powerful, commercial-quality CBOR encoder/ decoder that is still suited for small devices.
Other
183 stars 47 forks source link

Writing an empty null buffer triggers undefined behaviour. #164

Closed plietar closed 1 year ago

plietar commented 1 year ago

Writing an empty but null buffer to a QCBOR encoder context causes a call to memmove with a NULL pointer as its second argument, which is not allowed, even when the size is 0 (see eg. https://www.imperialviolet.org/2016/06/26/nonnull.html). This causes sanitizers to raise errors.

Simple reproduction:

#include <qcbor/qcbor.h>
int main() {
  UsefulBuf_MAKE_STACK_UB(buffer, 16);

  QCBOREncodeContext context;
  QCBOREncode_Init(&context, buffer);
  QCBOREncode_AddBytes(&context, NULLUsefulBufC);
  return 0;
}
$ clang main.c -o main -fsanitize=undefined,address -lqcbor
$ ./main
QCBOR/src/UsefulBuf.c:271:32: runtime error: null pointer passed as argument 2, which is declared to never be null
/usr/include/string.h:48:14: note: nonnull attribute specified here
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior QCBOR/src/UsefulBuf.c:271:32 in

Full stack trace:

    #0 0x4f3270 in UsefulOutBuf_InsertUsefulBuf QCBOR/src/UsefulBuf.c:271
    #1 0x4f1289 in UsefulOutBuf_AppendUsefulBuf QCBOR/inc/qcbor/UsefulBuf.h:2100
    #2 0x4f1289 in QCBOREncode_AddBuffer QCBOR/src/qcbor_encode.c:708
    #3 0x4f06c1 in QCBOREncode_AddBytes QCBOR/inc/qcbor/qcbor_encode.h:2412
    #4 0x4f06c1 in main main.c:8
    #5 0x7fe66a171236 in __libc_start_call_main ??:?
    #6 0x7fe66a1712f4 in __libc_start_main_alias_2 ??:?
    #7 0x41b3a0 in _start /build/glibc-2.34/csu/../sysdeps/x86_64/start.S:116
laurencelundblade commented 1 year ago

Hi Paul, see if #170 addresses this.

Coincidentally #168 fixes a similar issue. I will be merging it too.

laurencelundblade commented 1 year ago

Fixed in #170