From 3342aa06f6b7cccde059bc28aa4646dae74e6e41 Mon Sep 17 00:00:00 2001 From: "Victor M. Alvarez" Date: Thu, 8 Feb 2024 11:27:44 +0100 Subject: [PATCH] Fix bug in `magic` module when `libmagic` returns null pointer. The pointer returned from `libmagic` was passed directly to `yr_strdup` (a wrapper of `strdup`), but this function has undefined behavior when the argument is null. --- libyara/modules/magic/magic.c | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/libyara/modules/magic/magic.c b/libyara/modules/magic/magic.c index 6e59dddec5..124ed2afda 100644 --- a/libyara/modules/magic/magic.c +++ b/libyara/modules/magic/magic.c @@ -111,8 +111,10 @@ define_function(magic_mime_type) { magic_setflags(cache->magic_cookie, MAGIC_MIME_TYPE); - cache->cached_mime_type = yr_strdup( - magic_buffer(cache->magic_cookie, block_data, block->size)); + const char* type = magic_buffer( + cache->magic_cookie, block_data, block->size); + + cache->cached_mime_type = (type == NULL) ? NULL : yr_strdup(type); } } @@ -148,8 +150,10 @@ define_function(magic_type) { magic_setflags(cache->magic_cookie, 0); - cache->cached_type = yr_strdup( - magic_buffer(cache->magic_cookie, block_data, block->size)); + const char* type = magic_buffer( + cache->magic_cookie, block_data, block->size); + + cache->cached_type = (type == NULL) ? NULL : yr_strdup(type); } }