diff --git a/dbus/gattlib.c b/dbus/gattlib.c index 0411284..46eb8f6 100644 --- a/dbus/gattlib.c +++ b/dbus/gattlib.c @@ -849,7 +849,7 @@ int gattlib_discover_char_range(gattlib_connection_t* connection, uint16_t start static void add_characteristics_from_service(struct _gattlib_connection_backend* backend, GDBusObjectManager *device_manager, const char* service_object_path, unsigned int start, unsigned int end, - gattlib_characteristic_t* characteristic_list, int* count) + gattlib_characteristic_t* characteristic_list, int count_max, int* count) { GError *error = NULL; @@ -891,6 +891,7 @@ static void add_characteristics_from_service(struct _gattlib_connection_backend* continue; } if (strcmp(property_value, service_object_path)) { + // This GATT characteristic is not for the current GATT service. Ignore it g_object_unref(characteristic); continue; } else { @@ -907,6 +908,12 @@ static void add_characteristics_from_service(struct _gattlib_connection_backend* GATTLIB_LOG(GATTLIB_DEBUG, "- count %d with characteristic %s", *count, object_path); + // Sanity check to avoid buffer overflow + if (*count >= count_max) { + GATTLIB_LOG(GATTLIB_WARNING, "Skip GATT characteristic %s. Not enough space in the GATT characteristic array.", object_path); + continue; + } + characteristic_list[*count].handle = handle; characteristic_list[*count].value_handle = handle; characteristic_list[*count].properties = 0; @@ -1006,6 +1013,12 @@ int gattlib_discover_char_range(gattlib_connection_t* connection, uint16_t start if (interface) { g_object_unref(interface); + // Sanity check to avoid buffer overflow + if (count >= count_max) { + GATTLIB_LOG(GATTLIB_WARNING, "Skip battery characteristic. Not enough space in the GATT characteristic array."); + continue; + } + characteristic_list[count].handle = 0; characteristic_list[count].value_handle = 0; characteristic_list[count].properties = GATTLIB_CHARACTERISTIC_READ | GATTLIB_CHARACTERISTIC_NOTIFY; @@ -1049,7 +1062,8 @@ int gattlib_discover_char_range(gattlib_connection_t* connection, uint16_t start } // Add all characteristics attached to this service - add_characteristics_from_service(&connection->backend, device_manager, object_path, start, end, characteristic_list, &count); + add_characteristics_from_service(&connection->backend, device_manager, object_path, start, end, characteristic_list, + count_max, &count); g_object_unref(service_proxy); }