From c978b9dfe57e68d92c6dd3afac565fe05d325be0 Mon Sep 17 00:00:00 2001 From: Thomas Haller Date: Fri, 13 Oct 2017 11:56:06 +0200 Subject: [PATCH] core: randomize hash seed with a global seed This makes hashing non-deterministic with the aim to make it harder to exploit hash collisions. Non-deterministic also means that for unit testing we will get different values on each run. But since we shall never assign any meaning to these hash values nor rely on them being stable between restarts (or upgrades), that doesn't hurt. --- shared/nm-utils/nm-shared-utils.c | 23 +++++++++++++++++++++++ shared/nm-utils/nm-shared-utils.h | 6 +----- 2 files changed, 24 insertions(+), 5 deletions(-) diff --git a/shared/nm-utils/nm-shared-utils.c b/shared/nm-utils/nm-shared-utils.c index d2c057c48c..ba99ce2f87 100644 --- a/shared/nm-utils/nm-shared-utils.c +++ b/shared/nm-utils/nm-shared-utils.c @@ -863,6 +863,29 @@ nm_g_object_class_find_property_from_gtype (GType gtype, /*****************************************************************************/ +guint +NM_HASH_INIT (guint seed) +{ + static volatile guint global_seed = 0; + guint g, s; + + /* we xor @seed with a random @global_seed. This is to make the hashing behavior + * less predictable and harder to exploit collisions. */ + g = global_seed; + if (G_UNLIKELY (g == 0)) { + nm_utils_random_bytes (&s, sizeof (s)); + if (s == 0) + s = 42; + g_atomic_int_compare_and_exchange ((int *) &global_seed, 0, s); + g = global_seed; + nm_assert (g); + } + + return g ^ seed; +} + +/*****************************************************************************/ + static void _str_append_escape (GString *s, char ch) { diff --git a/shared/nm-utils/nm-shared-utils.h b/shared/nm-utils/nm-shared-utils.h index 57f1619245..0f9df73fb3 100644 --- a/shared/nm-utils/nm-shared-utils.h +++ b/shared/nm-utils/nm-shared-utils.h @@ -378,11 +378,7 @@ GParamSpec *nm_g_object_class_find_property_from_gtype (GType gtype, /*****************************************************************************/ -static inline guint -NM_HASH_INIT (guint seed) -{ - return seed; -} +guint NM_HASH_INIT (guint seed); static inline guint NM_HASH_COMBINE (guint h, guint val)