Skip to content

[Security] Multiple NULL pointer dereferences in cbor_copy() on allocation failure #417

@Benjamin608608

Description

@Benjamin608608

Summary

Multiple NULL pointer dereferences in cbor_copy() and cbor_copy_definite() when memory allocation fails, causing crashes instead of graceful error handling.

Vulnerability Details

  • Type: NULL Pointer Dereference (CWE-476)
  • Severity: Medium
  • Locations:
    • src/cbor.c, line 141 (_cbor_copy_int)
    • src/cbor.c, line 337 (cbor_copy_definite, bytestring case)
    • src/cbor.c, line 367-368 (cbor_copy_definite, string case)
  • Affected versions: All versions up to and including current master

Description

Issue A: _cbor_copy_int (line 141)

static cbor_item_t* _cbor_copy_int(cbor_item_t* item, bool negative) {
  cbor_item_t* res = NULL;    // line 125
  switch (cbor_int_get_width(item)) {
    case CBOR_INT_8:
      res = cbor_build_uint8(cbor_get_uint8(item));  // can return NULL
      break;
    // ... other cases similarly
  }
  if (negative) cbor_mark_negint(res);  // line 141: dereferences res without NULL check
  return res;
}

If cbor_build_uint*() returns NULL (allocation failure), the function continues to cbor_mark_negint(res) which dereferences the NULL pointer.

Issue B: cbor_copy_definite bytestring (line 337)

cbor_item_t* res = cbor_new_definite_bytestring();  // can return NULL
cbor_bytestring_set_handle(res, combined_data, total_length);  // dereferences res

Issue C: cbor_copy_definite string (line 367-368)

cbor_item_t* res = cbor_new_definite_string();  // can return NULL
cbor_string_set_handle(res, combined_data, total_length);  // dereferences res

Root Cause

Missing NULL checks after allocation functions that can fail.

Impact

  • Crash when copying CBOR items under memory pressure
  • Applications using custom memory allocators (e.g., embedded systems with limited memory) are particularly affected
  • Any application that calls cbor_copy() or cbor_copy_definite() on untrusted data when memory is constrained

Suggested Fix

Fix A (line 141):

if (res != NULL && negative) cbor_mark_negint(res);

Fix B (line 337):

cbor_item_t* res = cbor_new_definite_bytestring();
if (res == NULL) {
    _cbor_free(combined_data);
    return NULL;
}
cbor_bytestring_set_handle(res, combined_data, total_length);

Fix C (line 367-368):

cbor_item_t* res = cbor_new_definite_string();
if (res == NULL) {
    _cbor_free(combined_data);
    return NULL;
}
cbor_string_set_handle(res, combined_data, total_length);

Affected Version

Tested on latest master commit. All prior versions likely affected.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions