From 0e890f100c09681491e3b20ba0a521838564e58f Mon Sep 17 00:00:00 2001 From: Ben Allan Date: Mon, 12 Feb 2024 12:17:11 -0700 Subject: [PATCH] fix memory misuse potential in json_stream_sampler JSON_LIST_VALUE_setter now: checks for malloc failure in asprintf stops potential use after free on rec_type_name puts out error messages if malloc fails checks for rec_idx being set properly before use. --- ldms/src/sampler/json/json_stream_sampler.c | 20 +++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/ldms/src/sampler/json/json_stream_sampler.c b/ldms/src/sampler/json/json_stream_sampler.c index 6bb701616..4a02f98cc 100644 --- a/ldms/src/sampler/json/json_stream_sampler.c +++ b/ldms/src/sampler/json/json_stream_sampler.c @@ -379,14 +379,28 @@ int JSON_LIST_VALUE_setter(ldms_set_t set, ldms_mval_t list_mval, LDMS_V_CHAR_ARRAY, 255); break; case JSON_DICT_VALUE: + rec_idx = -1; if (!rec_type_name) { rc = asprintf(&rec_type_name, "%s_record", (char *)ctxt); - rec_idx = ldms_metric_by_name(set, rec_type_name); - free(rec_type_name); + if (rc >= 0) { + rec_idx = ldms_metric_by_name(set, rec_type_name); + free(rec_type_name); + rec_type_name = NULL; + } else { + LERROR("out of memory"); + rc = ENOMEM; + goto err; + } + } + if (rec_idx < 0) { + LERROR("item_not_found"); + rc = EINVAL; + goto err; } item_mval = ldms_record_alloc(set, rec_idx); if (!item_mval) { rc = ENOMEM; + LERROR("out of memory"); goto err; } rc = ldms_list_append_record(set, list_mval, item_mval); @@ -993,7 +1007,7 @@ static int json_recv_cb(ldms_stream_event_t ev, void *arg) const char *msg; json_entity_t entity; int rc = EINVAL; - ldms_schema_t schema; + ldms_schema_t schema = NULL; struct json_cfg_inst *inst = arg; json_entity_t schema_name;