From f607c031dc9b57dccc781751d154301c85b0d895 Mon Sep 17 00:00:00 2001 From: Mathias Detmers Date: Wed, 24 Jan 2018 17:03:07 +0100 Subject: [PATCH] add overflow checks for MT_UNSIGNED, MT_NEGATIVE and MT_TAG --- include/cn-cbor/cn-cbor.h | 5 ++++- src/cn-cbor.c | 13 ++++++++++--- 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/include/cn-cbor/cn-cbor.h b/include/cn-cbor/cn-cbor.h index bf71af8..1deccd6 100644 --- a/include/cn-cbor/cn-cbor.h +++ b/include/cn-cbor/cn-cbor.h @@ -136,7 +136,10 @@ typedef enum cn_cbor_error { CN_CBOR_ERR_OUT_OF_MEMORY, /** A float was encountered during parse but the library was built without support for float types. */ - CN_CBOR_ERR_FLOAT_NOT_SUPPORTED + CN_CBOR_ERR_FLOAT_NOT_SUPPORTED, + /** An overflow occured while assigning an unsigned or signed integer + */ + CN_CBOR_ERR_OVERFLOW } cn_cbor_error; /** diff --git a/src/cn-cbor.c b/src/cn-cbor.c index a7677ae..3b673ac 100644 --- a/src/cn-cbor.c +++ b/src/cn-cbor.c @@ -151,10 +151,15 @@ static cn_cbor *decode_item (struct parse_buf *pb CBOR_CONTEXT, cn_cbor* top_par // process content switch (mt) { case MT_UNSIGNED: - cb->v.uint = val; /* to do: Overflow check */ + /* with Overflow check */ + if (__builtin_add_overflow(val, 0, &cb->v.uint)) + CN_CBOR_FAIL(CN_CBOR_ERR_OVERFLOW); break; case MT_NEGATIVE: - cb->v.sint = ~val; /* to do: Overflow check */ + /* with Overflow check */ + if (__builtin_add_overflow(val, 0, &cb->v.sint)) + CN_CBOR_FAIL(CN_CBOR_ERR_OVERFLOW); + cb->v.sint = ~cb->v.sint; break; case MT_BYTES: case MT_TEXT: cb->v.str = (char *) pos; @@ -171,7 +176,9 @@ static cn_cbor *decode_item (struct parse_buf *pb CBOR_CONTEXT, cn_cbor* top_par } break; case MT_TAG: - cb->v.uint = val; + /* with Overflow check?*/ + if (__builtin_add_overflow(val, 0, &cb->v.uint)) + CN_CBOR_FAIL(CN_CBOR_ERR_OVERFLOW); goto push; case MT_PRIM: switch (ai) {