10 ms·
Linux Kernel RNG is now Blake2 instead of SHA1 and 3x faster
- tptacek 5y agoThis is an egregiously editorialized headline, but this was the easiest way to submit two separate links to LKML in one HN submission --- link to Fillipo's tweet about those links. The @zx2c4 Filippo is referring to is Jason Donenfeld, of WireGuard fame. It was news to me that he'd taken over the Linux kernel random driver! But it's welcome news indeed.
- garmaine 5y agoWhy is it not SHA2 which would be faster still with hardware support?
- normaler 5y agoBecause Hardware support is not available in alot oft devices and then blake2 beats sha2.
- willis936 5y agoI wonder if there are more virtual machines than bare metal hosts. There must be, right? Even with paravirtualization as an option I feel like many users of VMs would opt for the advantages of full virtualization.
- yjftsjthsd-h 5y agoMy vague understanding was that KVM-accelerated virtualization still let you use Virtio RNG, although I guess I don't know what the relative performance looks like at that point.
- loeg 5y agoVirtio-rng is good for getting quality seed material into the guest, but you don’t want to use it for bulk generation. Some hypervisor environments impose arbitrary and low throttles on guest virtio-rng use (think kB/s).
- cperciva 5y agoBetter question, why not use whatever hash is fastest on the system in question? We're talking about a RNG here -- it's not like we need to make sure that two different systems produce the same random numbers!
- nerdponx 5y agoMaybe this is a silly question, but why should RNG even be part of the kernel in the first place? It's convenient having it in a device file, but why couldn't that be provided by some userspace program or daemon?
- lisper 5y agoNot a silly question at all. It's because having a reliable and uncompromised source of randomness is essential for cryptographic applications. Having the RNG in user space would make it more vulnerable to attack.
- tptacek 5y agoTwo good reasons: 1. The kernel has access to unpredictable events that make good key fodder for the CSPRNG itself, which would be more annoying and less efficient to percolate into userland. 2. The kernel can assure all the processes on the device that they're getting random bits from a known source of unpredictable bits, and refuse to deliver those bits if its state hasn't been sufficiently populated; this has been a recurring source of systems vulnerabilities in programs with userland CSPRNGs. To that, add the convenience factor of always knowing how to get random bits and not having to set up userland dependencies and ensure they're started in the right order &c. You should generally use your kernel's CSPRNG in preference to other ones, and break that rule of thumb only if you know exactly what you're doing.
- foxfluff 5y agoThe kernel needs randomness too. If it's done there right once, why duplicate the effort in userspace (and watch all the hilarious ways userspace solutions fail)? getrandom was motivated by the fact that using device files has many failure modes.
- pedrocr 5y agoSpeed was probably not the criteria otherwise blake3 seems like an even better choice: https://github.com/BLAKE3-team/BLAKE3 https://github.com/BLAKE3-team/BLAKE3
- tptacek 5y agoI think speed is definitely a big part of this, though the speedup comes primarily from getting rid of superfluous calls to RDRAND. Blake2s is already in the kernel (after a fashion) for WireGuard itself; I don't think Blake3 is. An additional nerdy point here is that the extraction phase of the LKRNG is already using ChaCha (there's a sense in which a CSPRNG is really just the keystream of a stream cipher), and Blake2s and ChaCha are closely related.
- pedrocr 5y agoSo should we expect a blake3 switch sometime in the future? It seems to be a refinement of blake2 to make it more amenable to optimization while keeping most (all?) its qualities. Being well suited for optimization across architectures would also make it ideal for the kernel and it seems the reference implementation has already done a lot of the heavy lifting.
- tptacek 5y agoI doubt it, but who knows?
- Kubuxu 5y agoBlake3 will only result in small incremental perf improvement due to reduced number of rounds (10 to 7). Majority of Blake3's perf benefit manifests from merkle-tree structure and SIMD processing of multiple input streams at the same time.
- oconnor663 5y ago> multiple input streams at the same time Just in case this isn't clear, BLAKE3 breaks a single large input up into many chunks, and it hashes those chunks in parallel. The caller doesn't need to provide mulitple separate inputs to take advantage of the SIMD optimizations. (If you do have multiple separate inputs, you can actually use similar SIMD optimizations with almost any hash function. But because this situation is rare, libraries that provide this sort of API are also rare. Here's one of mine: https://docs.rs/blake2s_simd/1.0.0/blake2s_simd/many/index.html https://docs.rs/blake2s_simd/1.0.0/blake2s_simd/many/index.h....)
- wahern 5y agoAFAICT, BLAKE2s (previously SHA-1) is only being used for the forward secrecy element, in this case mixing a hash of the pool back into the core state, which is actually still using ChaCha20 for expansion. From quick inspection (never read this code before) I think the number of bytes in the pool is 416 (104 * 4). (See poolwords defined at https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/drivers/char/random.c?h=v5.16-rc7#n433 https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/lin...) For such relatively small messages and based on the cycles-per-byte performance numbers from https://w3.lasca.ic.unicamp.br/media/publications/p9-faz-hernandez.pdf https://w3.lasca.ic.unicamp.br/media/publications/p9-faz-her... (SHA-NI benchmarks), https://www.blake2.net/blake2_20130129.pdf https://www.blake2.net/blake2_20130129.pdf (BLAKE2 paper), and https://bench.cr.yp.to/results-hash.html https://bench.cr.yp.to/results-hash.html (comprehensive table of measurements), I don't see any performance reasons for choosing BLAKE2s over SHA-256. Rather, software SHA-256 and BLAKE2s seem comparable (and that's being charitable to BLAKE2s), and SHA-NI is definitely faster. Perhaps there were other considerations at play. Maybe something as simple as the author's preference. One thing that probably wasn't a consideration is FIPS compliance--the core function is ChaCha20 so FIPS kernels require a completely different CSPRNG, anyhow.
- maqp 5y agohttps://github.com/BLAKE3-team/BLAKE3/blob/master/media/speed.svg https://github.com/BLAKE3-team/BLAKE3/blob/master/media/spee... argues BLAKE2s is twice as fast compared to SHA256. One aspect switching from SHA1 to BLAKE2s does is it increases the total entropy a single compression operation adds to ChaCha20. This increases speed when folded BLAKE2s adds 128 bits per operation instead of folded SHA-1 that adds 80 bits. So that's two calls instead of four (I'm assuming they kept the folding). Another speedup comes from the fact the hash function constants aren't being filled with RDRAND inputs for every call. Finally, I'm not completely sure if increasing the hash size itself adds computational security against an attack where the internal state is compromised once, and the attacker tries to brute force the new state based on new output; My conjecture is the reseeding operation is atomic, i.e. that ChaCha20 won't yield anything until the reseed is complete. There shouldn't thus be any difference in this regard. I'd appreciate clarification wrt this.
- deleted 5y ago[deleted]
- magila 5y agoNote for those who only read the headline: the 3x speedup was achieved by removing a call to RDRAND in the extraction path, not the change in hash function.
- str4d 5y agoThe change in hash function did also result in speed improvements. Quoting the commit messages: Change to BLAKE2s: > This also has the advantage of supplying 16 bytes at a time rather than SHA1's 10 bytes, which, in addition to having a faster compression function to begin with, means faster extraction in general. On an Intel i7-11850H, this commit makes initial seeding around 131% faster. RDRAND call removal: > Removing the call there improves performance on an i7-11850H by 370%. In other words, the vast majority of the work done by extract_crng() prior to this commit was devoted to fetching 32 bits of RDRAND.
- wahern 5y agoFor such small message sizes (416 bytes, AFAICT), it's plausible that refactor-induced compiler optimizations are responsible for much of the gains over SHA-1. Note that the old code invokes (assuming 104 32-bit pool words) sha1_transform 16 times, whereas the new code calls into the blake2s library twice--blake2s_update and then blake2s_final. That suggests the new code is likely spending much more time in tight, inlined loops as I doubt the hash library entry points are being inlined into that driver. Most of the performance metrics people cite when discussing hash functions are for large messages. For small message sizes hash initialization and finalization costs tend to dominate, and costs one might otherwise ignore, such as function calls, can become noteworthy.
- xarope 5y ago"Perfection is achieved, not when there is nothing more to add, but when there is nothing left to take away."
- CalChris 5y agoThe commit message criticizes SHA1 pretty well but why did they specifically choose Blake2? Donenfeld is clearly very smart but did they have a bake off? https://lwn.net/Articles/879391/ https://lwn.net/Articles/879391/
- loeg 5y agoBlake is one of the faster SHA3 finalists out there and the ‘s’ variety is fast on 32-bit hardware. I don’t know why they chose Blake2 instead of Blake3, though.
- maqp 5y agoNot to nitpick but BLAKE was the SHA3 finalist, not BLAKE2 which is an improvement. To quote Wikipedia: >BLAKE2 removes addition of constants to message words from BLAKE round function, changes two rotation constants, simplifies padding, adds parameter block that is XOR'ed with initialization vectors, and reduces the number of rounds from 16 to 12 for BLAKE2b (successor of BLAKE-512), and from 14 to 10 for BLAKE2s (successor of BLAKE-256). https://en.wikipedia.org/wiki/BLAKE_(hash_function)#BLAKE2 https://en.wikipedia.org/wiki/BLAKE_(hash_function)#BLAKE2 Reducing the rounds by 4 might raise eyebrows wrt security, but Aumasson's 'Too Much Crypto' discusses BLAKE vs BLAKE2 among other things: https://eprint.iacr.org/2019/1492.pdf https://eprint.iacr.org/2019/1492.pdf Why kernel devs didn't go with BLAKE3, I can't say.
- giantrobot 5y ago> Why they didn't go with BLAKE3, I can't say. Maybe people just liked it better that way?
- iruoy 5y agoBLAKE3 is written in Rust wile BLAKE2s is written in C. That is probably a lot easier to push through. It also seems to be almost as fast according to the BLAKE3 specs PDF (page 11). https://github.com/BLAKE3-team/BLAKE3-specs/blob/master/blake3.pdf https://github.com/BLAKE3-team/BLAKE3-specs/blob/master/blak...
- throwaway1492 5y agoCan anyone provide links or references to current techniques and methods for performing cryptanalysis against hash functions and prngs? I frequently find myself trapped in a loop thinking a long the lines of “they’re just bits there has to be a pattern”. Border line obsessing on these things, blake2b in particular. Does anyone else have this problem?
- hinkley 5y agoIf encrypted data has a pattern, then it is leaking data. There are some famous examples of this with block cyphers. If the encrypted data is indistinguishable from white noise, then the CSPRNG you built on top of it can also be made indistinguishable.
- hinkley 5y agoNo comments, just downvotes. The ECB Penguin is an example of information - patterns - leaking out of encrypted data. This is a cryptographic failure mode and the solution is a better algorithm. https://blog.filippo.io/the-ecb-penguin/ https://blog.filippo.io/the-ecb-penguin/ Low entropy means predictability in the input versus the output. Properly encrypted data has high entropy, which is why you can’t compress it after encryption. Random number generators need to be high entropy, which is where the idea of CSPRNGs comes from.
- edoceo 5y agoStart looking at code in libsodium. Crypto is too hard for me and I just trust the libs - but I can read the code (sorta). The stuff in OpenSSL is crazy to me but libsodium I can almost understand. I feel like I can know it but not KNOW it.
- SAI_Peregrinus 5y agoMostly similar to block ciphers or permutations. Differential cryptanalysis is a good starting point. Usually one starts with a reduced-round version, often a single round. Break one round, then see if that can be extended to 2, etc, etc. The cryptanalysis of Meow Hash[1] is instructive, since it's a weak hash and actually vulnerable in full. There's also a good Differential propagation analysis of Keccak[1] paper, using a reduced-round Keccak. There's also Rotational cryptanalysis. Here's a paper on Keccak uses that technique.[3] It was first formally defined by Khovratovich and Nikolić.[4] [1] https://peter.website/meow-hash-cryptanalysis https://peter.website/meow-hash-cryptanalysis [2] https://eprint.iacr.org/2012/163.pdf https://eprint.iacr.org/2012/163.pdf [3] https://eprint.iacr.org/2012/546.pdf https://eprint.iacr.org/2012/546.pdf [4] https://www.iacr.org/archive/fse2010/61470339/61470339.pdf https://www.iacr.org/archive/fse2010/61470339/61470339.pdf
- garbagecoder 5y agoWait, it uses the same algorithm regardless of hardware??
- maqp 5y agoThe actual DRNG algorithm Linux kernel uses is ChaCha20, which runs in constant time regardless of underlying hardware. BLAKE2 is below ChaCha20: it reseeds the ChaCha20 DRNG from a 4096-byte input_pool every 300 seconds.
- garbagecoder 5y agoOK, but many have SHA in hardware.
- gerdesj 5y agoWhat would happen if your hardware implemented a ROT13 "engine" as its primary crypto thingie? A responsible approach to crypto should be quite shy. It might drop it's drawers and bare all (source code) but no more. It might show some ankle towards some beefy hardware but only when escorted. A software crypto thingie cannot and should not assume that hardware is trustworthy. However, you can stir some randomness from an untrustworthy source into your entropy pool and not find your knickers around your ankles, if you are careful. Feel free to present your credentials.
- password4321 5y agoRDRAND on AMD Ryzen 9 5900X is flakey https://news.ycombinator.com/item?id=25733285 https://news.ycombinator.com/item?id=25733285
- nsajko 5y agoThe popularity of the Blake family annoys me, as I feel that it's overhyped. Sure, they're fast (on current hardware), but they're supposed to be cryptographic hash functions. I know that BLAKE received some scrutiny in this regard, as part of the SHA3 competition. But then BLAKE was obsoleted by BLAKE2, which in turn was obsoleted by BLAKE3, making the claims to security less and less sensible. And all this is before the actual winner of SHA3 comes into the picture. With parameters as specified by SHA3 it's a lot slower than BLAKE3, but it is my understanding (IANAC) that (1) The SHA3 security margin can safely be decreased, as NIST set the security requirements too high. This is one of the reasons for the speed difference. (2) The sponge-based crypto popularized by Keccak (the SHA3 winner) is much more amenable to cryptanalysis than the more traditional crypto such as the functions in the Blake family. This means that Blake's security would be less sure even had it received the same level of scrutiny. But AFAIK Blake received much less scrutiny than Keccak, or even other sponge-based functions, such as the ones in the NIST Lightweight Crypto competition. https://csrc.nist.gov/Projects/lightweight-cryptography https://csrc.nist.gov/Projects/lightweight-cryptography https://keccak.team/2017/not_arx.html https://keccak.team/2017/not_arx.html
- kortex 5y agoA) I am not sure I'd say blake2 obsoletes blake, and certainly blake3 does not obsolete b2. They are a family, but still different algorithms. B) blake3, afaik, is not yet as thoroughly vetted as b2. C) I think some of the hype around b3 is deserved. It's crazy fast. If you don't care about crypto at all (e.g. file dedup), it's absolutely phenomenal. But the main downside of B3 right now is just novelty. Cryto algos are like fine wines. D) I don't know enough about Keccak vs Blake, but just because Blake2 has received less scrutiny, doesn't mean it's insufficient. I'm sure there are tradeoffs that the kernel editors have chosen. E: here's a link to some discussion: https://crypto.stackexchange.com/questions/31674/what-advantages-does-keccak-sha-3-have-over-blake2 https://crypto.stackexchange.com/questions/31674/what-advant...
- tptacek 5y agoBlake2 is already in lib/crypto in the kernel (it's needed for WireGuard, by the same author as this change); SHA3 and Blake3 are not. It's probably that simple.
- obert 5y agoWhen you make rng good and fast you get to use it everywhere, which ends up making things more secure and robust <3
- MF_POOP 5y ago
- Ecco 5y agoDumb question: why would a RNG need a crypto hash function? I get why it would be useful for a PRNG, but isn’t a true RNG simply supposed to gather entropy from the real world and just spit it back?
- Kubuxu 5y agoIt uses it to expose part of the randomness without exposing internal state and mixing in new random events into the randomness pool. In essence hash functions are frequently used as Pseudo Random Functions as hash functions are PRFs with input compression.
- edflsafoiewq 5y agoThe universe does not provide bits of pure, sublimated entropy. There's a little entropy in the low bits of the interrupt timings, but you don't know exactly where it is. You need to "stir" it to get the entropy to affect the whole pool.
- tptacek 5y agoNo. The high-level design of most CSPRNGs is roughly that of a stream cipher. With an ordinary stream cipher like AES-CTR, we need a 128 bit key; if we had a password or a DH shared secret, we'd get the 128 bit key from a KDF, whose core would be a hash function. With a CSPRNG, in lieu of a key we have an (often indeterminate) stream of unpredictable events --- but we still have the equivalent of a KDF, a "mixing function", whose core is typically a hash function. Adding new "entropy" means feeding it through the mixing function. Getting random bytes means running the stream cipher and spitting out the keystream directly, instead of XORing it against a plaintext. Cryptographically speaking, the problem of taking a small secret and extracting a very large number of cryptographically unpredictable bytes is pretty fundamental to the whole project --- you know, of, like, cryptography. But for the fact that you'd like to be able to theoretically recover from a bug that discloses your random state (your "key"), you wouldn't really need more than a "seed"'s worth of entropy to run the CSPRNG indefinitely.
- _vvhw 5y agoBy the way, thanks Thomas... I've always enjoyed and benefitted from your "CSPRNGs are essentially a stream cipher, and now you finally also understand what a stream cipher really is" explanations on HN over the years. I remember the first time I grokked it from one of your comments, and it was much clearer than anything I could find on Cryptography Stack Exchange (yes, I know!). Since then, I've used the AES-CTR trick for non-critical random generators for many user space fuzz test harnesses, and it's helped speed them up while also being stronger than a PRNG, without a repeating period.
- londons_explore 5y ago
- ayende 5y agoJason is very well known, already has code in the kernel and is touching a _highly_ visible part of the code. That's a pretty bold statement on your part, especially because there are many other, simpler, mechanisms that can be used for subverting/back dooring without such costs
- buro9 5y agohttps://www.blake2.net/ https://www.blake2.net/ says: "CONSIDER USING BLAKE3, faster than BLAKE2, see https://github.com/BLAKE3-team/BLAKE3 https://github.com/BLAKE3-team/BLAKE3" I'm glad we're on Blake2 and seeing the benefits, but why not go straight to Blake3? What are the differences and why do they matter in this instance?
- joconde 5y agoBLAKE3 was published in 2020. I don't think anyone would seriously use a hash function, cipher, or RNG that has been studied for only two years, let alone in the Linux kernel.
- adrian_b 5y agoThe main reason why BLAKE3 is much faster than most other hash algorithms is that it can be computed in parallel on many cores. Inside the kernel and especially in something running continuously like the RNG, you do not want to make all the cores busy without any reason, so the hash computation should be restricted to 1 thread. In that case, BLAKE3 does not have any important advantages. When restricted to a single-thread, BLAKE3 is slower than hash algorithms that have hardware support on the CPU, e.g. SHA-256 on most recent CPUs. (But the Linux kernel must support many older CPUs without hardware for hash algorithms, so BLAKE2 is a better choice).
- eps 5y agoBlake3 is faster because it allows for very efficient SIMD implementations. That alone blows all competition out of the water, with a single thread. The ability to further parallelize it on multiple cores is just a cherry on top.
- adrian_b 5y agoTrue, but the use of SIMD is also restricted in the kernel, so that would not matter for the Linux kernel. In comparison with the hardware instructions for SHA-2 or SHA-3, on those CPUs which have them, BLAKE3 is not faster, because those instructions also use the same SIMD registers, processing the same number of bits per operation. I use every day BLAKE3, for file checksumming. For this application, on my Zen 3 with hardware SHA-2, BLAKE3 greatly outperforms everything else, but only due to multithreading. On older CPUs, without SIMD SHA instructions, you are right that BLAKE3 can be faster than other algorithms even in single-thread, by exploiting the parallelism of the BLAKE3 algorithm with a SIMD implementation. For other hashes, SIMD may not accelerate the computation of a single hash, but when you need to compute multiple hashes you can interleave their computations and obtain similar speedups with SIMD instructions.