Skip to contentSkip to conversation

src: make hash seed attribute optional

PATCH Superseded Laura Garcia Liebana 1 participant 1 message Nov 1, 2016 netfilter

v2 of 3 Superseded Latest is v3 →

lore
Share & tools
lore
#0 lore raw

PATCH v2 1/4 src: make hash seed attribute optional

The hash expression requires a seed attribute to call the jhash operation, eg.

 # nft add rule x y meta mark set jhash ip saddr . ip daddr mod 2 \
	seed 0xdeadbeef

With this patch the seed attribute is optional and it's generated by a random function from userspace, eg.

 # nft add rule x y meta mark set jhash ip saddr . ip daddr mod 2

In order to generate a resilient random number, the syscall getrandom(2)[0] is used if detected. In other case, the trivial rand() will be used.

[0] https://lwn.net/Articles/605828/

---
Changes in v2:
- Use getrandom(2) syscall instead of arc4random, suggested by Pablo.
- This case hasn't a test case due to the random seed generation in
the payload won't match.

 configure.ac       | 22 +++++++++++++++++++++-
 include/hash.h     | 12 ++++++++++++
 src/parser_bison.y |  5 +++++
 3 files changed, 38 insertions(+), 1 deletion(-)
configure.ac +20 -1
index 7e0b75c..d21fe97 100644
@@ -108,6 +108,24 @@ AC_DEFINE([HAVE_LIBXTABLES], [1], [0])
 AC_SUBST(with_libxtables)
 AM_CONDITIONAL([BUILD_XTABLES], [test "x$with_libxtables" == xyes])
 
+AC_COMPILE_IFELSE(
+[
+	AC_LANG_SOURCE([[
+		#include <sys/syscall.h>
+		#include <linux/random.h>
+		int main(){
+			int s;
+			syscall(SYS_getrandom, &s, sizeof(s), 0);
+		}
+	]])
+], [have_random=yes
+   AC_DEFINE([HAVE_GETRANDOM], [1], [] )],
+   [have_random=no])
+
+AS_IF([test "x$have_random" != xno],
+[have_random=getrandom],
+[have_random=rand])
+
 # Checks for header files.
 AC_HEADER_STDC
 AC_HEADER_ASSERT
@@ -158,4 +176,5 @@ nft configuration:
   enable debugging:		${with_debug}
   use mini-gmp:			${with_mini_gmp}
   enable pdf documentation:	${enable_pdf_doc}
-  libxtables support:		${with_libxtables}"
+  libxtables support:		${with_libxtables}
+  random used:			${have_random}"
include/hash.h +12 -0
index bc8c86a..6d6badd 100644
@@ -1,6 +1,18 @@
 #ifndef NFTABLES_HASH_H
 #define NFTABLES_HASH_H
 
+#ifdef HAVE_GETRANDOM
+#include <sys/syscall.h>
+#include <linux/random.h>
+#define selrandom()	({ uint32_t s; \
+			syscall(SYS_getrandom, &s, sizeof(s), 0); s; })
+
+#else
+#include <time.h>
+#include <stdlib.h>
+#define selrandom()	({ srand(time(NULL)); (uint32_t)rand(); })
+#endif
+
 extern struct expr *hash_expr_alloc(const struct location *loc,
 				    uint32_t modulus, uint32_t seed);
 
src/parser_bison.y +5 -0
index 106df27..6a24bec 100644
@@ -2585,6 +2585,11 @@ hash_expr		:	JHASH	expr	MOD	NUM	SEED	NUM
 				$$ = hash_expr_alloc(&@$, $4, $6);
 				$$->hash.expr = $2;
 			}
+			|	JHASH	expr	MOD	NUM
+			{
+				$$ = hash_expr_alloc(&@$, $4, selrandom());
+				$$->hash.expr = $2;
+			}
 			;
 
 rt_expr			:	RT	rt_key
Signature · 1 line
2.9.3