From 18bfa23b9b52fecf6f551f4c225abe8034f9dac2 Mon Sep 17 00:00:00 2001
From: Yu Watanabe <watanabe.yu+github@gmail.com>
Date: Wed, 7 Dec 2022 09:06:48 +0900
Subject: [PATCH] hexdecoct: fix NULL pointer dereferences in hexmem()

Fixes oss-fuzz#54090 (https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=54090).

Fixes #25655.

(cherry picked from commit 7d34567444304ea0acec7ed3c44c09bb65cea32c)
(cherry picked from commit 772e89452e8e72347360bfe6556ecc3d95b2caf4)

Conflict:adapt test cases based on the existing test case framework
Reference:https://github.com/systemd/systemd-stable/commit/18bfa23b9b52fecf6f551f4c225abe8034f9dac2
---
 src/basic/hexdecoct.c     |  4 +++-
 src/test/test-hexdecoct.c | 21 +++++++++++++++++++++
 2 files changed, 24 insertions(+), 1 deletion(-)

diff --git a/src/basic/hexdecoct.c b/src/basic/hexdecoct.c
index 99b82d4..c9cda67 100644
--- a/src/basic/hexdecoct.c
+++ b/src/basic/hexdecoct.c
@@ -59,11 +59,13 @@ char *hexmem(const void *p, size_t l) {
         const uint8_t *x;
         char *r, *z;
 
+        assert(p || l == 0);
+
         z = r = new(char, l * 2 + 1);
         if (!r)
                 return NULL;
 
-        for (x = p; x < (const uint8_t*) p + l; x++) {
+        for (x = p; x && x < (const uint8_t*) p + l; x++) {
                 *(z++) = hexchar(*x >> 4);
                 *(z++) = hexchar(*x & 15);
         }
diff --git a/src/test/test-hexdecoct.c b/src/test/test-hexdecoct.c
index c9d318b..413ad0e 100644
--- a/src/test/test-hexdecoct.c
+++ b/src/test/test-hexdecoct.c
@@ -6,6 +6,7 @@
 #include "hexdecoct.h"
 #include "macro.h"
 #include "string-util.h"
+#include "memory-util.h"
 
 static void test_hexchar(void) {
         assert_se(hexchar(0xa) == 'a');
@@ -71,6 +72,25 @@ static void test_undecchar(void) {
         assert_se(undecchar('9') == 9);
 }
 
+static void test_hexmem_one(const char *in, const char *expected) {
+        _cleanup_free_ char *result = NULL;
+        _cleanup_free_ void *mem = NULL;
+        size_t len;
+
+        assert_se(result = hexmem(in, strlen_ptr(in)));
+        log_debug("hexmem(\"%s\") → \"%s\" (expected: \"%s\")", strnull(in), result, expected);
+        assert_se(streq(result, expected));
+
+        assert_se(unhexmem(result, SIZE_MAX, &mem, &len) >= 0);
+        assert_se(memcmp_safe(mem, in, len) == 0);
+}
+
+static void test_hexmem(void) {
+        test_hexmem_one(NULL, "");
+        test_hexmem_one("", "");
+        test_hexmem_one("foo", "666f6f");
+}
+
 static void test_unhexmem_one(const char *s, size_t l, int retval) {
         _cleanup_free_ char *hex = NULL;
         _cleanup_free_ void *mem = NULL;
@@ -350,6 +370,7 @@ int main(int argc, char *argv[]) {
         test_base64mem();
         test_unbase64mem();
         test_hexdump();
+        test_hexmem();
 
         return 0;
 }
-- 
2.33.0

