Skip to contentSkip to conversation

Introduce The SipHash PRF

PATCH Superseded Jason A. Donenfeld 4 participants 12 messages Jan 7, 2017 – Jan 9, 2017

Subsystems (6)

v2 of 3 Superseded Latest is v3 →

lore
Share & tools
lore
author maintainer
#2 lore raw

PATCH v2 2/4 siphash: implement HalfSipHash1-3 for hash tables

In reply to Jason A. Donenfeld

HalfSipHash, or hsiphash, is a shortened version of SipHash, which generates 32-bit outputs using a weaker 64-bit key. It has *much* lower security margins, and shouldn't be used for anything too sensitive, but it could be used as a hashtable key function replacement, if the output is never exposed, and if the security requirement is not too high.

The goal is to make this something that performance-critical jhash users would be willing to use.

On 64-bit machines, HalfSipHash1-3 is slower than SipHash1-3, so we alias SipHash1-3 to HalfSipHash1-3 on those systems.

64-bit x86_64:

[    0.509409] test_siphash:     SipHash2-4 cycles: 4049181
[    0.510650] test_siphash:     SipHash1-3 cycles: 2512884
[    0.512205] test_siphash: HalfSipHash1-3 cycles: 3429920
[    0.512904] test_siphash:    JenkinsHash cycles:  978267

So, we map hsiphash() -> SipHash1-3

32-bit x86:

[    0.509868] test_siphash:     SipHash2-4 cycles: 14812892
[    0.513601] test_siphash:     SipHash1-3 cycles:  9510710
[    0.515263] test_siphash: HalfSipHash1-3 cycles:  3856157
[    0.515952] test_siphash:    JenkinsHash cycles:  1148567

So, we map hsiphash() -> HalfSipHash1-3

hsiphash() is roughly 3 times slower than jhash(), but comes with a considerable security improvement.

---
 Documentation/siphash.txt |  75 +++++++++++
 include/linux/siphash.h   |  62 ++++++++-
 lib/siphash.c             | 321 +++++++++++++++++++++++++++++++++++++++++++++-
 lib/test_siphash.c        |  98 +++++++++++++-
 4 files changed, 551 insertions(+), 5 deletions(-)
Documentation/siphash.txt +75 -0
index e540ab14eb8f..4a229a1f53e5 100644
@@ -77,3 +77,78 @@ Linux implements the "2-4" variant of SipHash.
 
 Read the SipHash paper if you're interested in learning more:
 https://131002.net/siphash/siphash.pdf
+
+
+~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~
+
+HalfSipHash - SipHash's insecure younger cousin
+-----------------------------------------------
+Written by Jason A. Donenfeld <[email protected]>
+
+On the off-chance that SipHash is not fast enough for your needs, you might be
+able to justify using HalfSipHash, a terrifying but potentially useful
+possibility. HalfSipHash cuts SipHash's rounds down from "2-4" to "1-3" and,
+even scarier, uses an easily brute-forcable 64-bit key (with a 32-bit output)
+instead of SipHash's 128-bit key. However, this may appeal to some
+high-performance `jhash` users.
+
+Danger!
+
+Do not ever use HalfSipHash except for as a hashtable key function, and only
+then when you can be absolutely certain that the outputs will never be
+transmitted out of the kernel. This is only remotely useful over `jhash` as a
+means of mitigating hashtable flooding denial of service attacks.
+
+1. Generating a key
+
+Keys should always be generated from a cryptographically secure source of
+random numbers, either using get_random_bytes or get_random_once:
+
+hsiphash_key_t key;
+get_random_bytes(&key, sizeof(key));
+
+If you're not deriving your key from here, you're doing it wrong.
+
+2. Using the functions
+
+There are two variants of the function, one that takes a list of integers, and
+one that takes a buffer:
+
+u32 hsiphash(const void *data, size_t len, const siphash_key_t *key);
+
+And:
+
+u32 hsiphash_1u32(u32, const hsiphash_key_t *key);
+u32 hsiphash_2u32(u32, u32, const hsiphash_key_t *key);
+u32 hsiphash_3u32(u32, u32, u32, const hsiphash_key_t *key);
+u32 hsiphash_4u32(u32, u32, u32, u32, const hsiphash_key_t *key);
+
+If you pass the generic hsiphash function something of a constant length, it
+will constant fold at compile-time and automatically choose one of the
+optimized functions.
+
+3. Hashtable key function usage:
+
+struct some_hashtable {
+	DECLARE_HASHTABLE(hashtable, 8);
+	hsiphash_key_t key;
+};
+
+void init_hashtable(struct some_hashtable *table)
+{
+	get_random_bytes(&table->key, sizeof(table->key));
+}
+
+static inline hlist_head *some_hashtable_bucket(struct some_hashtable *table, struct interesting_input *input)
+{
+	return &table->hashtable[hsiphash(input, sizeof(*input), &table->key) & (HASH_SIZE(table->hashtable) - 1)];
+}
+
+You may then iterate like usual over the returned hash bucket.
+
+4. Performance
+
+HalfSipHash is roughly 3 times slower than JenkinsHash. For many replacements,
+this will not be a problem, as the hashtable lookup isn't the bottleneck. And
+in general, this is probably a good sacrifice to make for the security and DoS
+resistance of HalfSipHash.
include/linux/siphash.h +61 -1

72 lines not on this page · raw message

lib/siphash.c +320 -1

330 lines not on this page · raw message

lib/test_siphash.c +95 -3

128 lines not on this page · raw message

Signature · 1 line
2.11.0
author maintainer
#3 lore raw

PATCH v2 3/4 secure_seq: use SipHash in place of MD5

In reply to Jason A. Donenfeld

This gives a clear speed and security improvement. Siphash is both faster and is more solid crypto than the aging MD5.

Rather than manually filling MD5 buffers, for IPv6, we simply create a layout by a simple anonymous struct, for which gcc generates rather efficient code. For IPv4, we pass the values directly to the short input convenience functions.

64-bit x86_64:

[    1.683628] secure_tcpv6_sequence_number_md5# cycles: 99563527
[    1.717350] secure_tcp_sequence_number_md5# cycles: 92890502
[    1.741968] secure_tcpv6_sequence_number_siphash# cycles: 67825362
[    1.762048] secure_tcp_sequence_number_siphash# cycles: 67485526

32-bit x86:

[    1.600012] secure_tcpv6_sequence_number_md5# cycles: 103227892
[    1.634219] secure_tcp_sequence_number_md5# cycles: 94732544
[    1.669102] secure_tcpv6_sequence_number_siphash# cycles: 96299384
[    1.700165] secure_tcp_sequence_number_siphash# cycles: 86015473
Cc Andi Kleen <[email protected]>
Cc David Miller <[email protected]>
Cc David Laight <[email protected]>
Cc Tom Herbert <[email protected]>
Cc Hannes Frederic Sowa <[email protected]>
Cc Eric Dumazet <[email protected]>
---
 net/core/secure_seq.c | 145 ++++++++++++++++++++++----------------------------
 1 file changed, 63 insertions(+), 82 deletions(-)
net/core/secure_seq.c +63 -82
index 88a8e429fc3e..119e3ebe2f30 100644
@@ -1,3 +1,7 @@
+/*
+ * Copyright (C) 2016 Jason A. Donenfeld <[email protected]>. All Rights Reserved.
+ */
+
 #include <linux/kernel.h>
 #include <linux/init.h>
 #include <linux/cryptohash.h>
@@ -8,18 +12,18 @@
 #include <linux/ktime.h>
 #include <linux/string.h>
 #include <linux/net.h>
-
+#include <linux/siphash.h>
 #include <net/secure_seq.h>
 
 #if IS_ENABLED(CONFIG_IPV6) || IS_ENABLED(CONFIG_INET)
+#include <linux/in6.h>
 #include <net/tcp.h>
-#define NET_SECRET_SIZE (MD5_MESSAGE_BYTES / 4)
 
-static u32 net_secret[NET_SECRET_SIZE] ____cacheline_aligned;
+static siphash_key_t net_secret;
 
 static __always_inline void net_secret_init(void)
 {
-	net_get_random_once(net_secret, sizeof(net_secret));
+	net_get_random_once(&net_secret, sizeof(net_secret));
 }
 #endif
 
@@ -44,80 +48,70 @@ static u32 seq_scale(u32 seq)
 u32 secure_tcpv6_sequence_number(const __be32 *saddr, const __be32 *daddr,
 				 __be16 sport, __be16 dport, u32 *tsoff)
 {
-	u32 secret[MD5_MESSAGE_BYTES / 4];
-	u32 hash[MD5_DIGEST_WORDS];
-	u32 i;
-
+	const struct {
+		struct in6_addr saddr;
+		struct in6_addr daddr;
+		__be16 sport;
+		__be16 dport;
+	} __aligned(SIPHASH_ALIGNMENT) combined = {
+		.saddr = *(struct in6_addr *)saddr,
+		.daddr = *(struct in6_addr *)daddr,
+		.sport = sport,
+		.dport = dport
+	};
+	u64 hash;
 	net_secret_init();
-	memcpy(hash, saddr, 16);
-	for (i = 0; i < 4; i++)
-		secret[i] = net_secret[i] + (__force u32)daddr[i];
-	secret[4] = net_secret[4] +
-		(((__force u16)sport << 16) + (__force u16)dport);
-	for (i = 5; i < MD5_MESSAGE_BYTES / 4; i++)
-		secret[i] = net_secret[i];
-
-	md5_transform(hash, secret);
-
-	*tsoff = sysctl_tcp_timestamps == 1 ? hash[1] : 0;
-	return seq_scale(hash[0]);
+	hash = siphash(&combined, offsetofend(typeof(combined), dport),
+		       &net_secret);
+	*tsoff = sysctl_tcp_timestamps == 1 ? (hash >> 32) : 0;
+	return seq_scale(hash);
 }
 EXPORT_SYMBOL(secure_tcpv6_sequence_number);
 
 u32 secure_ipv6_port_ephemeral(const __be32 *saddr, const __be32 *daddr,
 			       __be16 dport)
 {
-	u32 secret[MD5_MESSAGE_BYTES / 4];
-	u32 hash[MD5_DIGEST_WORDS];
-	u32 i;
-
+	const struct {
+		struct in6_addr saddr;
+		struct in6_addr daddr;
+		__be16 dport;
+	} __aligned(SIPHASH_ALIGNMENT) combined = {
+		.saddr = *(struct in6_addr *)saddr,
+		.daddr = *(struct in6_addr *)daddr,
+		.dport = dport
+	};
 	net_secret_init();
-	memcpy(hash, saddr, 16);
-	for (i = 0; i < 4; i++)
-		secret[i] = net_secret[i] + (__force u32) daddr[i];
-	secret[4] = net_secret[4] + (__force u32)dport;
-	for (i = 5; i < MD5_MESSAGE_BYTES / 4; i++)
-		secret[i] = net_secret[i];
-
-	md5_transform(hash, secret);
-
-	return hash[0];
+	return siphash(&combined, offsetofend(typeof(combined), dport),
+		       &net_secret);
 }
 EXPORT_SYMBOL(secure_ipv6_port_ephemeral);
 #endif
 
 #ifdef CONFIG_INET
 
+/* secure_tcp_sequence_number(a, b, 0, d) == secure_ipv4_port_ephemeral(a, b, d),
+ * but fortunately, `sport' cannot be 0 in any circumstances. If this changes,
+ * it would be easy enough to have the former function use siphash_4u32, passing
+ * the arguments as separate u32.
+ */
+
 u32 secure_tcp_sequence_number(__be32 saddr, __be32 daddr,
 			       __be16 sport, __be16 dport, u32 *tsoff)
 {
-	u32 hash[MD5_DIGEST_WORDS];
-
+	u64 hash;
 	net_secret_init();
-	hash[0] = (__force u32)saddr;
-	hash[1] = (__force u32)daddr;
-	hash[2] = ((__force u16)sport << 16) + (__force u16)dport;
-	hash[3] = net_secret[15];
-
-	md5_transform(hash, net_secret);
-
-	*tsoff = sysctl_tcp_timestamps == 1 ? hash[1] : 0;
-	return seq_scale(hash[0]);
+	hash = siphash_3u32((__force u32)saddr, (__force u32)daddr,
+			    (__force u32)sport << 16 | (__force u32)dport,
+			    &net_secret);
+	*tsoff = sysctl_tcp_timestamps == 1 ? (hash >> 32) : 0;
+	return seq_scale(hash);
 }
 
 u32 secure_ipv4_port_ephemeral(__be32 saddr, __be32 daddr, __be16 dport)
 {
-	u32 hash[MD5_DIGEST_WORDS];
-
 	net_secret_init();
-	hash[0] = (__force u32)saddr;
-	hash[1] = (__force u32)daddr;
-	hash[2] = (__force u32)dport ^ net_secret[14];
-	hash[3] = net_secret[15];
-
-	md5_transform(hash, net_secret);
-
-	return hash[0];
+	return siphash_3u32((__force u32)saddr, (__force u32)daddr,
+			    (__force u16)dport, &net_secret);
 }
 EXPORT_SYMBOL_GPL(secure_ipv4_port_ephemeral);
 #endif
@@ -126,21 +120,11 @@ EXPORT_SYMBOL_GPL(secure_ipv4_port_ephemeral);
 u64 secure_dccp_sequence_number(__be32 saddr, __be32 daddr,
 				__be16 sport, __be16 dport)
 {
-	u32 hash[MD5_DIGEST_WORDS];
 	u64 seq;
-
 	net_secret_init();
-	hash[0] = (__force u32)saddr;
-	hash[1] = (__force u32)daddr;
-	hash[2] = ((__force u16)sport << 16) + (__force u16)dport;
-	hash[3] = net_secret[15];
-
-	md5_transform(hash, net_secret);
-
-	seq = hash[0] | (((u64)hash[1]) << 32);
+	seq = siphash_3u32(saddr, daddr, (u32)sport << 16 | dport, &net_secret);
 	seq += ktime_get_real_ns();
 	seq &= (1ull << 48) - 1;
-
 	return seq;
 }
 EXPORT_SYMBOL(secure_dccp_sequence_number);
@@ -149,26 +133,23 @@ EXPORT_SYMBOL(secure_dccp_sequence_number);
 u64 secure_dccpv6_sequence_number(__be32 *saddr, __be32 *daddr,
 				  __be16 sport, __be16 dport)
 {
-	u32 secret[MD5_MESSAGE_BYTES / 4];
-	u32 hash[MD5_DIGEST_WORDS];
+	const struct {
+		struct in6_addr saddr;
+		struct in6_addr daddr;
+		__be16 sport;
+		__be16 dport;
+	} __aligned(SIPHASH_ALIGNMENT) combined = {
+		.saddr = *(struct in6_addr *)saddr,
+		.daddr = *(struct in6_addr *)daddr,
+		.sport = sport,
+		.dport = dport
+	};
 	u64 seq;
-	u32 i;
-
 	net_secret_init();
-	memcpy(hash, saddr, 16);
-	for (i = 0; i < 4; i++)
-		secret[i] = net_secret[i] + (__force u32)daddr[i];
-	secret[4] = net_secret[4] +
-		(((__force u16)sport << 16) + (__force u16)dport);
-	for (i = 5; i < MD5_MESSAGE_BYTES / 4; i++)
-		secret[i] = net_secret[i];
-
-	md5_transform(hash, secret);
-
-	seq = hash[0] | (((u64)hash[1]) << 32);
+	seq = siphash(&combined, offsetofend(typeof(combined), dport),
+		      &net_secret);
 	seq += ktime_get_real_ns();
 	seq &= (1ull << 48) - 1;
-
 	return seq;
 }
 EXPORT_SYMBOL(secure_dccpv6_sequence_number);
Signature · 1 line
2.11.0

Jason A. Donenfeld

author maintainer
#0 lore raw

v2 cover Introduce The SipHash PRF

This patch series introduces SipHash into the kernel. SipHash is a cryptographically secure PRF, which serves a variety of functions, and is introduced in patch #1. The following patch #2 introduces HalfSipHash, an optimization suitable for hash tables only. Finally, the last two patches in this series show two usages of the introduced siphash function family. It is expected that after this initial introductin, other usages will follow.

Please read the extensive descriptions in patch #1 and patch #2 of what these functions do and the various levels of assurances. They're products of intense cryptographic research, and I believe they're suitable for the uses outlined herein.

The use of SipHash is not limited to the networking subsystem -- indeed I would like to use it in other places too in the kernel. But after discussing with a few on this list and at Linus' suggestion, the initial import of these functions is coming through the networking tree. After these are merged, it will then be easier to expand use elsewhere.

Changes v1->v2:
- len in the macro is now (len).
- siphash_key_t is now a struct, so that passing by reference is more obvious and clear. This required changing all the call sites.
- Rather than calling le32_to_cpu(data[0]), where data is a u64, we now do the safer thing and call le32_to_cpup((const __le32 *)data).
- The alignment in the tests is now more explicit.
- Sparse no longer complains, after fixing up a few endian casts.
- White space fixups.
- Word wrapping fixes.
- The valid suggestions from checkpatch.

Jason A. Donenfeld (4):
siphash: add cryptographically secure PRF
siphash: implement HalfSipHash1-3 for hash tables
secure_seq: use SipHash in place of MD5
syncookies: use SipHash in place of SHA1

 Documentation/siphash.txt | 154 +++++++++++++
 MAINTAINERS               |   7 +
 include/linux/siphash.h   | 145 ++++++++++++
 lib/Kconfig.debug         |   6 +-
 lib/Makefile              |   5 +-
 lib/siphash.c             | 551 ++++++++++++++++++++++++++++++++++++++++++++++
 lib/test_siphash.c        | 223 +++++++++++++++++++
 net/core/secure_seq.c     | 145 ++++++------
 net/ipv4/syncookies.c     |  21 +-
 net/ipv6/syncookies.c     |  41 ++--
 10 files changed, 1173 insertions(+), 125 deletions(-)
 create mode 100644 Documentation/siphash.txt
 create mode 100644 include/linux/siphash.h
 create mode 100644 lib/siphash.c
 create mode 100644 lib/test_siphash.c
Signature · 1 line
2.11.0
author maintainer
#1 lore raw

PATCH v2 1/4 siphash: add cryptographically secure PRF

SipHash is a 64-bit keyed hash function that is actually a cryptographically secure PRF, like HMAC. Except SipHash is super fast, and is meant to be used as a hashtable keyed lookup function, or as a general PRF for short input use cases, such as sequence numbers or RNG chaining.

For the first usage:

There are a variety of attacks known as "hashtable poisoning" in which an attacker forms some data such that the hash of that data will be the same, and then preceeds to fill up all entries of a hashbucket. This is a realistic and well-known denial-of-service vector. Currently hashtables use jhash, which is fast but not secure, and some kind of rotating key scheme (or none at all, which isn't good). SipHash is meant as a replacement for jhash in these cases.

There are a modicum of places in the kernel that are vulnerable to hashtable poisoning attacks, either via userspace vectors or network vectors, and there's not a reliable mechanism inside the kernel at the moment to fix it. The first step toward fixing these issues is actually getting a secure primitive into the kernel for developers to use. Then we can, bit by bit, port things over to it as deemed appropriate.

While SipHash is extremely fast for a cryptographically secure function, it is likely a bit slower than the insecure jhash, and so replacements will be evaluated on a case-by-case basis based on whether or not the difference in speed is negligible and whether or not the current jhash usage poses a real security risk.

For the second usage:

A few places in the kernel are using MD5 or SHA1 for creating secure sequence numbers, syn cookies, port numbers, or fast random numbers. SipHash is a faster and more fitting, and more secure replacement for MD5 in those situations. Replacing MD5 and SHA1 with SipHash for these uses is obvious and straight-forward, and so is submitted along with this patch series. There shouldn't be much of a debate over its efficacy.

Dozens of languages are already using this internally for their hash tables and PRFs. Some of the BSDs already use this in their kernels. SipHash is a widely known high-speed solution to a widely known set of problems, and it's time we catch-up.

---
 Documentation/siphash.txt |  79 ++++++++++++++++
 MAINTAINERS               |   7 ++
 include/linux/siphash.h   |  85 +++++++++++++++++
 lib/Kconfig.debug         |   6 +-
 lib/Makefile              |   5 +-
 lib/siphash.c             | 232 ++++++++++++++++++++++++++++++++++++++++++++++
 lib/test_siphash.c        | 131 ++++++++++++++++++++++++++
 7 files changed, 540 insertions(+), 5 deletions(-)
 create mode 100644 Documentation/siphash.txt
 create mode 100644 include/linux/siphash.h
 create mode 100644 lib/siphash.c
 create mode 100644 lib/test_siphash.c
Documentation/siphash.txt new file +79 -0
new file mode 100644
index 000000000000..e540ab14eb8f
@@ -0,0 +1,79 @@
+         SipHash - a short input PRF
+-----------------------------------------------
+Written by Jason A. Donenfeld <[email protected]>
+
+SipHash is a cryptographically secure PRF -- a keyed hash function -- that
+performs very well for short inputs, hence the name. It was designed by
+cryptographers Daniel J. Bernstein and Jean-Philippe Aumasson. It is intended
+as a replacement for some uses of: `jhash`, `md5_transform`, `sha_transform`,
+and so forth.
+
+SipHash takes a secret key filled with randomly generated numbers and either
+an input buffer or several input integers. It spits out an integer that is
+indistinguishable from random. You may then use that integer as part of secure
+sequence numbers, secure cookies, or mask it off for use in a hash table.
+
+1. Generating a key
+
+Keys should always be generated from a cryptographically secure source of
+random numbers, either using get_random_bytes or get_random_once:
+
+siphash_key_t key;
+get_random_bytes(&key, sizeof(key));
+
+If you're not deriving your key from here, you're doing it wrong.
+
+2. Using the functions
+
+There are two variants of the function, one that takes a list of integers, and
+one that takes a buffer:
+
+u64 siphash(const void *data, size_t len, const siphash_key_t *key);
+
+And:
+
+u64 siphash_1u64(u64, const siphash_key_t *key);
+u64 siphash_2u64(u64, u64, const siphash_key_t *key);
+u64 siphash_3u64(u64, u64, u64, const siphash_key_t *key);
+u64 siphash_4u64(u64, u64, u64, u64, const siphash_key_t *key);
+u64 siphash_1u32(u32, const siphash_key_t *key);
+u64 siphash_2u32(u32, u32, const siphash_key_t *key);
+u64 siphash_3u32(u32, u32, u32, const siphash_key_t *key);
+u64 siphash_4u32(u32, u32, u32, u32, const siphash_key_t *key);
+
+If you pass the generic siphash function something of a constant length, it
+will constant fold at compile-time and automatically choose one of the
+optimized functions.
+
+3. Hashtable key function usage:
+
+struct some_hashtable {
+	DECLARE_HASHTABLE(hashtable, 8);
+	siphash_key_t key;
+};
+
+void init_hashtable(struct some_hashtable *table)
+{
+	get_random_bytes(&table->key, sizeof(table->key));
+}
+
+static inline hlist_head *some_hashtable_bucket(struct some_hashtable *table, struct interesting_input *input)
+{
+	return &table->hashtable[siphash(input, sizeof(*input), &table->key) & (HASH_SIZE(table->hashtable) - 1)];
+}
+
+You may then iterate like usual over the returned hash bucket.
+
+4. Security
+
+SipHash has a very high security margin, with its 128-bit key. So long as the
+key is kept secret, it is impossible for an attacker to guess the outputs of
+the function, even if being able to observe many outputs, since 2^128 outputs
+is significant.
+
+Linux implements the "2-4" variant of SipHash.
+
+5. Resources
+
+Read the SipHash paper if you're interested in learning more:
+https://131002.net/siphash/siphash.pdf
MAINTAINERS +7 -0
index a136dfbb8eea..50afa1118112 100644
@@ -11299,6 +11299,13 @@ F:	arch/arm/mach-s3c24xx/mach-bast.c
 F:	arch/arm/mach-s3c24xx/bast-ide.c
 F:	arch/arm/mach-s3c24xx/bast-irq.c
 
+SIPHASH PRF ROUTINES
+M:	Jason A. Donenfeld <[email protected]>
+S:	Maintained
+F:	lib/siphash.c
+F:	lib/test_siphash.c
+F:	include/linux/siphash.h
+
 TI DAVINCI MACHINE SUPPORT
 M:	Sekhar Nori <[email protected]>
 M:	Kevin Hilman <[email protected]>
include/linux/siphash.h new file +85 -0

85 lines not on this page · raw message

lib/Kconfig.debug +3 -3
index b06848a104e6..3d2515a770c3 100644
@@ -1819,9 +1819,9 @@ config TEST_HASH
 	tristate "Perform selftest on hash functions"
 	default n
 	help
-	  Enable this option to test the kernel's integer (<linux/hash,h>)
-	  and string (<linux/stringhash.h>) hash functions on boot
-	  (or module load).
+	  Enable this option to test the kernel's integer (<linux/hash.h>),
+	  string (<linux/stringhash.h>), and siphash (<linux/siphash.h>)
+	  hash functions on boot (or module load).
 
 	  This is intended to help people writing architecture-specific
 	  optimized versions.  If unsure, say N.
lib/Makefile +3 -2
index bc4073a8cd08..7b3008d58600 100644
@@ -22,7 +22,8 @@ lib-y := ctype.o string.o vsprintf.o cmdline.o \
 	 sha1.o chacha20.o md5.o irq_regs.o argv_split.o \
 	 flex_proportions.o ratelimit.o show_mem.o \
 	 is_single_threaded.o plist.o decompress.o kobject_uevent.o \
-	 earlycpio.o seq_buf.o nmi_backtrace.o nodemask.o win_minmax.o
+	 earlycpio.o seq_buf.o siphash.o \
+	 nmi_backtrace.o nodemask.o win_minmax.o
 
 lib-$(CONFIG_MMU) += ioremap.o
 lib-$(CONFIG_SMP) += cpumask.o
@@ -44,7 +45,7 @@ obj-$(CONFIG_TEST_HEXDUMP) += test_hexdump.o
 obj-y += kstrtox.o
 obj-$(CONFIG_TEST_BPF) += test_bpf.o
 obj-$(CONFIG_TEST_FIRMWARE) += test_firmware.o
-obj-$(CONFIG_TEST_HASH) += test_hash.o
+obj-$(CONFIG_TEST_HASH) += test_hash.o test_siphash.o
 obj-$(CONFIG_TEST_KASAN) += test_kasan.o
 obj-$(CONFIG_TEST_KSTRTOX) += test-kstrtox.o
 obj-$(CONFIG_TEST_LKM) += test_module.o
lib/siphash.c new file +232 -0

232 lines not on this page · raw message

lib/test_siphash.c new file +131 -0

131 lines not on this page · raw message

Signature · 1 line
2.11.0
author maintainer
#9 lore raw

PATCH v2 4/4 syncookies: use SipHash in place of SHA1

In reply to Jason A. Donenfeld

SHA1 is slower and less secure than SipHash, and so replacing syncookie generation with SipHash makes natural sense. Some BSDs have been doing this for several years in fact.

The speedup should be similar -- and even more impressive -- to the speedup from the sequence number fix in this series.

Cc Eric Dumazet <[email protected]>
Cc David Miller <[email protected]>
---
 net/ipv4/syncookies.c | 21 +++++----------------
 net/ipv6/syncookies.c | 41 +++++++++++++++++++----------------------
 2 files changed, 24 insertions(+), 38 deletions(-)
net/ipv4/syncookies.c +5 -16
index 3e88467d70ee..496b97e17aaf 100644
@@ -13,13 +13,13 @@
 #include <linux/tcp.h>
 #include <linux/slab.h>
 #include <linux/random.h>
-#include <linux/cryptohash.h>
+#include <linux/siphash.h>
 #include <linux/kernel.h>
 #include <linux/export.h>
 #include <net/tcp.h>
 #include <net/route.h>
 
-static u32 syncookie_secret[2][16-4+SHA_DIGEST_WORDS] __read_mostly;
+static siphash_key_t syncookie_secret[2] __read_mostly;
 
 #define COOKIEBITS 24	/* Upper bits store count */
 #define COOKIEMASK (((__u32)1 << COOKIEBITS) - 1)
@@ -48,24 +48,13 @@ static u32 syncookie_secret[2][16-4+SHA_DIGEST_WORDS] __read_mostly;
 #define TSBITS	6
 #define TSMASK	(((__u32)1 << TSBITS) - 1)
 
-static DEFINE_PER_CPU(__u32 [16 + 5 + SHA_WORKSPACE_WORDS], ipv4_cookie_scratch);
-
 static u32 cookie_hash(__be32 saddr, __be32 daddr, __be16 sport, __be16 dport,
 		       u32 count, int c)
 {
-	__u32 *tmp;
-
 	net_get_random_once(syncookie_secret, sizeof(syncookie_secret));
-
-	tmp  = this_cpu_ptr(ipv4_cookie_scratch);
-	memcpy(tmp + 4, syncookie_secret[c], sizeof(syncookie_secret[c]));
-	tmp[0] = (__force u32)saddr;
-	tmp[1] = (__force u32)daddr;
-	tmp[2] = ((__force u32)sport << 16) + (__force u32)dport;
-	tmp[3] = count;
-	sha_transform(tmp + 16, (__u8 *)tmp, tmp + 16 + 5);
-
-	return tmp[17];
+	return siphash_4u32((__force u32)saddr, (__force u32)daddr,
+			    (__force u32)sport << 16 | (__force u32)dport,
+			    count, &syncookie_secret[c]);
 }
 
 
net/ipv6/syncookies.c +19 -22

63 lines not on this page · raw message

Signature · 1 line
2.11.0
#10 lore raw
In reply to Jason A. Donenfeld
Quoted 6 lines · Jason A. Donenfeld

This patch series introduces SipHash into the kernel. SipHash is a cryptographically secure PRF, which serves a variety of functions, and is introduced in patch #1. The following patch #2 introduces HalfSipHash, an optimization suitable for hash tables only. Finally, the last two patches in this series show two usages of the introduced siphash function family. It is expected that after this initial introductin, other usages will follow.

...

Quoted 6 lines

The use of SipHash is not limited to the networking subsystem -- indeed I would like to use it in other places too in the kernel. But after discussing with a few on this list and at Linus' suggestion, the initial import of these functions is coming through the networking tree. After these are merged, it will then be easier to expand use elsewhere.

Quoted 11 lines

Changes v1->v2:
- len in the macro is now (len).
- siphash_key_t is now a struct, so that passing by reference is more obvious and clear. This required changing all the call sites.
- Rather than calling le32_to_cpu(data[0]), where data is a u64, we now do the safer thing and call le32_to_cpup((const __le32 *)data).
- The alignment in the tests is now more explicit.
- Sparse no longer complains, after fixing up a few endian casts.
- White space fixups.
- Word wrapping fixes.
- The valid suggestions from checkpatch.

Hi Jason, thanks for doing this! Yes, I had gotten a little lost in the earlier discussions about the 'random' driver and other potential users of SipHash. I agree with the approach to just introduce the two uses in net/ to start with, and introduce more users later. The changes from v1 to v2 look good too.

Now that the HalfSipHash patch is Cc'ed to me too I do have one other small suggestion which is that this:

	#if BITS_PER_LONG == 64
	typedef siphash_key_t hsiphash_key_t;
	#define HSIPHASH_ALIGNMENT SIPHASH_ALIGNMENT
	#else
	typedef struct {
		u32 key[2];
	} hsiphash_key_t;
	#define HSIPHASH_ALIGNMENT __alignof__(u32)
	#endif

could cause confusion if someone accidentally uses 'siphash_key_t' instead of 'hsiphash_key_t', as their code would compile fine on a 64-bit platform but would fail to compile on a 32-bit platform. I think there should just always be a hsiphash_key_t struct defined, and it can use unsigned long (no need for an #ifdef):

	#define HSIPHASH_ALIGNMENT __alignof__(unsigned long)
	typedef struct {
		unsigned long key[2];
	} hsiphash_key_t;

There's also a small error in Documentation/siphash.txt: hsiphash() is shown as taking siphash_key_t instead of hsiphash_key_t.

The uses in net look good too. Something to watch out for is accidentally defining the structs in a way that leaves internal padding bytes, which could theoretically take on any value and cause the same input to produce different hashes. But AFAICS, in the proposed patch all the structs are laid out properly, so that won't happen.

'net_secret' could also be marked as __read_mostly, like the keys in syncookies.c, I suppose; it may not matter much.

Thanks!

Eric

maintainer
#4 lore raw

Re: [PATCH v2 net-next 3/4] secure_seq: use SipHash in place of MD5

In reply to Jason A. Donenfeld

From: "Jason A. Donenfeld" <[email protected]>
Date: Sat, 7 Jan 2017 15:40:56 +0100

Quoted 14 lines

This gives a clear speed and security improvement. Siphash is both faster and is more solid crypto than the aging MD5.

Rather than manually filling MD5 buffers, for IPv6, we simply create a layout by a simple anonymous struct, for which gcc generates rather efficient code. For IPv4, we pass the values directly to the short input convenience functions.

64-bit x86_64:

[    1.683628] secure_tcpv6_sequence_number_md5# cycles: 99563527
[    1.717350] secure_tcp_sequence_number_md5# cycles: 92890502
[    1.741968] secure_tcpv6_sequence_number_siphash# cycles: 67825362
[    1.762048] secure_tcp_sequence_number_siphash# cycles: 67485526
Quoted 7 lines

32-bit x86:

[    1.600012] secure_tcpv6_sequence_number_md5# cycles: 103227892
[    1.634219] secure_tcp_sequence_number_md5# cycles: 94732544
[    1.669102] secure_tcpv6_sequence_number_siphash# cycles: 96299384
[    1.700165] secure_tcp_sequence_number_siphash# cycles: 86015473

This and the next patch are a real shame, performance wise, on cpus that have single-instruction SHA1 and MD5 implementations. Sparc64 has both, and I believe x86_64 can do SHA1 these days.

It took so long to get those instructions into real silicon, and then have software implemented to make use of them as well.

Who knows when we'll see SipHash widely deployed in any instruction set, if at all, right? And by that time we'll possibly find out that "Oh shit, this SipHash thing has flaws!" and we'll need DIPPY_DO_DA_HASH and thus be forced back to a software implementation again.

I understand the reasons why these patches are being proposed, I just thought I'd mention the issue of cpus that implement secure hash algorithm instructions.

#5 lore raw

Re: [PATCH v2 net-next 3/4] secure_seq: use SipHash in place of MD5

Hi David,

Quoted 5 lines · David Miller

From: "Jason A. Donenfeld" <[email protected]>
Date: Sat, 7 Jan 2017 15:40:56 +0100

Quoted 2 lines

This gives a clear speed and security improvement. Siphash is both faster and is more solid crypto than the aging MD5.

[snip]

Quoted 14 lines

This and the next patch are a real shame, performance wise, on cpus that have single-instruction SHA1 and MD5 implementations. Sparc64 has both, and I believe x86_64 can do SHA1 these days.

It took so long to get those instructions into real silicon, and then have software implemented to make use of them as well.

Who knows when we'll see SipHash widely deployed in any instruction set, if at all, right? And by that time we'll possibly find out that "Oh shit, this SipHash thing has flaws!" and we'll need DIPPY_DO_DA_HASH and thus be forced back to a software implementation again.

Quoted 3 lines

I understand the reasons why these patches are being proposed, I just thought I'd mention the issue of cpus that implement secure hash algorithm instructions.

Well, except those instructions aren't actually used in these places. Although x86_64 SHA1-NI accelerated SHA-1 is available in the Linux crypto API, it seems that in kernel code it remains impractical to use these instructions on small amounts of data because they use XMM registers, which means the overhead of kernel_fpu_begin()/kernel_fpu_end() must be incurred. Furthermore, kernel_fpu_begin() is not allowed in all contexts so there has to be a fallback.

Out of curiosity, is this actually a solvable problem, e.g. by making the code using the XMM registers responsible for saving and restoring the ones clobbered, or by optimizing kernel_fpu_begin()/kernel_fpu_end()? Or does it in fact remain impractical for such instructions to be used for applications like this one?

Eric

maintainer
#6 lore raw

Re: [PATCH v2 net-next 3/4] secure_seq: use SipHash in place of MD5

From: Eric Biggers <[email protected]>
Date: Sat, 7 Jan 2017 14:09:11 -0800

Quoted 9 lines

Well, except those instructions aren't actually used in these places. Although x86_64 SHA1-NI accelerated SHA-1 is available in the Linux crypto API, it seems that in kernel code it remains impractical to use these instructions on small amounts of data because they use XMM registers, which means the overhead of kernel_fpu_begin()/kernel_fpu_end() must be incurred. Furthermore, kernel_fpu_begin() is not allowed in all contexts so there has to be a fallback.

Quoted 6 lines

Out of curiosity, is this actually a solvable problem, e.g. by making the code using the XMM registers responsible for saving and restoring the ones clobbered, or by optimizing kernel_fpu_begin()/kernel_fpu_end()? Or does it in fact remain impractical for such instructions to be used for applications like this one?

On x86 making the FPU save more tractible in situations like this is really hard and will make the code significantly more complex.

It's simpler and cheaper on sparc64, and unlike on x86 there aren't any fundament restrictions on where FPU stuff can be used. This is because we don't have "save all the FPU state" instructions and have to do it all by hand anyways.

However I will note that just like x86, sparc64 doesn't override the md5_transform() in lib/md5.c like it should.

author maintainer
#8 lore raw

Re: [PATCH v2 net-next 3/4] secure_seq: use SipHash in place of MD5

In reply to David Miller

Hi David,

Quoted 6 lines · David Miller

This and the next patch are a real shame, performance wise, on cpus that have single-instruction SHA1 and MD5 implementations. Sparc64 has both, and I believe x86_64 can do SHA1 these days.

It took so long to get those instructions into real silicon, and then have software implemented to make use of them as well.

Actually, from a performance perspective, these patches are strictly better than what was already there, since nothing actually used the special instructions. They're also better security wise, because the prior use of these functions was quite dubious. On x86, using the FPU isn't really an option in these situations, as you well know. On Sparc64, sure, I guess it's a bummer that silicon is lagging cryptography. If after merging these improvements, you want to start thinking about a special construction just for Sparc64 that would be faster and have a matching security level, this would of course be great. But so far, nobody even bothered to do this for the old insecure slow code that this is replacing.

Quoted 5 lines

Who knows when we'll see SipHash widely deployed in any instruction set, if at all, right? And by that time we'll possibly find out that "Oh shit, this SipHash thing has flaws!" and we'll need DIPPY_DO_DA_HASH and thus be forced back to a software implementation again.

The literature and cryptanalyses on SipHash have been quite positive. And as I mentioned earlier in patchset messages, SipHash is really _not_ some newfangled hipster thing, but rather something that's been around a while, pretty extensively studied, and considered quite venerable. I think if you're going to bet on something SipHash is one of the more safe bets to be made.

Quoted 3 lines

I understand the reasons why these patches are being proposed, I just thought I'd mention the issue of cpus that implement secure hash algorithm instructions.

Yea, agreed, it's a bummer. Hopefully silicon will catch up someday, and we'll all be happy. In the meantime, at least these patches improve the situation on Linux.

I interpret your letter's omission of any substantive comments on the code itself to be an indication that things are mostly sane. I'll follow up with Eric's suggestions to produce a v3, and then hopefully we can get this merged.

Regards,
Jason

author maintainer
#11 lore raw
In reply to Eric Biggers

Hi Eric,

Thanks for round two. I'll address these. Comments are inline below.

Quoted 4 lines · Eric Biggers

Hi Jason, thanks for doing this! Yes, I had gotten a little lost in the earlier discussions about the 'random' driver and other potential users of SipHash. I agree with the approach to just introduce the two uses in net/ to start with, and introduce more users later. The changes from v1 to v2 look good too.

Indeed the initial patchset was _insane_ and the discussion became sprawling and impossible. Everybody suggested I do baby steps, so voila, there's this more manageable patchset now.

Quoted 19 lines

Now that the HalfSipHash patch is Cc'ed to me too I do have one other small suggestion which is that this:

        #if BITS_PER_LONG == 64
        typedef siphash_key_t hsiphash_key_t;
        #define HSIPHASH_ALIGNMENT SIPHASH_ALIGNMENT
        #else
        typedef struct {
                u32 key[2];
        } hsiphash_key_t;
        #define HSIPHASH_ALIGNMENT __alignof__(u32)
        #endif

could cause confusion if someone accidentally uses 'siphash_key_t' instead of 'hsiphash_key_t', as their code would compile fine on a 64-bit platform but would fail to compile on a 32-bit platform. I think there should just always be a hsiphash_key_t struct defined, and it can use unsigned long (no need for an #ifdef):

Quoted 4 lines
        #define HSIPHASH_ALIGNMENT __alignof__(unsigned long)
        typedef struct {
                unsigned long key[2];
        } hsiphash_key_t;

Good idea. Will adjust. That makes things a lot simpler.

Quoted 2 lines

There's also a small error in Documentation/siphash.txt: hsiphash() is shown as taking siphash_key_t instead of hsiphash_key_t.

Arg, nice catch, fixing.

Quoted 5 lines

The uses in net look good too. Something to watch out for is accidentally defining the structs in a way that leaves internal padding bytes, which could theoretically take on any value and cause the same input to produce different hashes. But AFAICS, in the proposed patch all the structs are laid out properly, so that won't happen.

Indeed that's something closely examined. In fact, originally, just to be careful, I was using __packed, but David pointed out that using __packed makes gcc resort to byte-by-byte assignment, even if the alignment would otherwise be natural. So, instead I just made sure to list the members in descending order of size, and made sure to use offsetendof instead of sizeof. I'll be sure to document this precaution in the Documentation/siphash.txt file for the next version, alongside a simple example.

Quoted 2 lines

'net_secret' could also be marked as __read_mostly, like the keys in syncookies.c, I suppose; it may not matter much.

Good point. Fixing.

New version coming your way soon.

Thanks again,
Jason

#7 lore raw

RE: [PATCH v2 net-next 3/4] secure_seq: use SipHash in place of MD5

In reply to Eric Biggers

From: Eric Biggers

Quoted 1 line

Sent: 07 January 2017 22:09

..

Quoted 4 lines

Out of curiosity, is this actually a solvable problem, e.g. by making the code using the XMM registers responsible for saving and restoring the ones clobbered, or by optimizing kernel_fpu_begin()/kernel_fpu_end()? Or does it in fact remain impractical for such instructions to be used for applications like this one?

I think it should be possible to fast-save a couple of FP registers by telling the IPI save code where to save them from (to load into a different cpu).
But there might be issues with other parts of the FP state. This might be ok provided the kernel doesn't actually use FP instructions.

(I thought about this when adding AVX support to NetBSD.)

David