-
Notifications
You must be signed in to change notification settings - Fork 20
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Simple secure random number generation #393
Comments
why can't |
So the |
I put that in future work: it's possible we might want to have a common type, or alternatively a common trait and two different types (so that the type system ensures you don't use an insecure RNG where you wanted a secure one). But that is likely to require further design, and I would like to leave that out of the initial design to keep the initial design simple. Past efforts to add an RNG have run into endless design issues and tradeoffs. The smaller the surface area, the fewer of those issues come up. |
You're entirely right; fixed. |
Do we need a more descriptive name than Also shouldn't this have a way to fill a buffer using the system crng? It's less convenient but it's the most basic building block that platforms provide so it may be worth having a cross-platform version exposed. |
I don't think we should make any guarantees that something is using the "system" RNG, just that it's using some cryptographically secure RNG. I do agree that "fill this buffer with randomness" is a useful building block, but the goal of this ACP was the simple end-user-targeted interface, since existing libraries already have those building blocks. |
The intent is that the seeded, insecure version is an API guarantee. The secure version makes no guarantees about algorithm, but the seeded version does. |
Sure, picking an algorithm for the insecure version is what I mean. That would need to be part of the proposal as it's part of the API, no? |
I am in favor of the general idea here. A domain question for folks using secure RNG: how do you write tests for the behavior of routines that make use of the secure RNG? Do you do it by providing it with a seed? I think the API as proposed would be insufficient for that because there's no way to create a secure RNG with a seed. I have some initial thoughts:
I kinda lean towards this in the affirmative. That is, that we should have type-level separation. The use cases are different enough that being able to say "this type is always going to do 'secure' rng" is likely quite valuable. I'm not sure we need to commit to this in the initial design, but I think we should leave room for it. For example, perhaps by renaming
This is a little concerning to me because it feels like a very strong guarantee that will lock us into something for eternity. But, I confess, I am a bit ignorant here, and perhaps this isn't as big of a deal as I think it is. Do other language ecosystems guarantee stability of seeded insecure RNGs? |
With a pluggable RNG implementing a trait. In I've asked this in #393 (comment) and here the reply #393 (comment) |
@ChrisDenton wrote:
You're right, I should spell that out more explicitly. My intention was that we initially use the same RNG implementation for both, but if any security issue ever arises that requires us to change the RNG implementation, we'll change the secure one and leave the insecure one. |
@BurntSushi wrote:
As @the8472 wrote, likely by using a trait.
I think I'm convinced by this, yeah: let's keep the types distinct, and then we can provide a trait for any code that wants to be generic over the RNG. But I still think this should be future work, to avoid increasing the initial surface area we need to get consensus on.
To the extent other languages provide stability guarantees, yes, some other languages/libraries do provide seeded RNGs and guarantee that the same seed produces the same sequence of values. For instance, Python provides an insecure seedable RNG in the |
Should the |
To me it feels like we are trying to go too high level too quickly, especially with the pub fn getrandom(dest: &mut [u8]) -> Result<(), Error>; and / or: pub fn getrandom_uninit(dest: &mut [MaybeUninit<u8>]) -> Result<&mut [u8], Error>; It feels like a big mistake not to support slices, as you would otherwise need to create a loop to fill the buffer, causing a huge syscall overhead that isn't necessary, because the underlying OS primitives all (from what I'm seeing) support buffers. In fact std internally already has its own I'm certainly not opposed to having more higher level APIs available in the initial API as well, but a |
@pitaj wrote:
That's in the future work section. I absolutely think we should, but I'm trying to minimize the initial surface area. |
That solves a completely different problem. That's a building block that would live underneath the higher-level interface most people are actually looking for, and it wouldn't solve the problem most people are pulling in crates for. An order of magnitude more crates depend on |
The initial RFC does support arrays: you can do |
Will the stable RNG be stable across different targets? (especially bit-size and endianness) |
@cuviper It should be, yes. I'll document that. |
@rust-lang/libs-api I've now split this ACP. This ACP provides only the simple secure random number generation. It has a mention, in the "Future work" section, of a possible "phase 2" design for a seedable secure RNG. The separate ACP #394 provides the seedable insecure random number generation that's stable across Rust versions. |
Thanks @joshtriplett for this. It's a lot. The phrase "cryptographically secure" is being used here. We should be clear what is meant. [Nakov, Wikipedia]. Prediction resistance, presumably — would we allow something weaker? State compromise resistance, probably? |
as a proposed algorithm, I think https://en.wikipedia.org/wiki/Fortuna_(PRNG) could be good. it would collect entropy from |
What led you to pick this working on integers & bool, rather than exposing something more raw? For example, one basic version of this would be to offer an For the implementation side, do we really need to maintain something in std? Can we just be a thin layer around The solution sketch here mentions "thread-local" in the documentation for the function. Is that observable at all? Is there a way that the caller could tell anything different between it being thread-local or global and mutexed? |
relying on the OS and not implementing your own CSRNG may be best, plus some OSes go to great lengths to make getting randomness fast, e.g. https://www.phoronix.com/news/Linux-Random-vDSO-2024 |
@scottmcm wrote:
This interface also allows writing I don't think providing exclusively an interface for filling buffers will serve many potential users; with such an interface, most users would end up having to wrap it for usability, at which point they're using an external crate anyway, so we didn't solve the underlying problem of "why do I need an external crate just to get a random number?". I think we need
I would argue that most applications with a dependency on secure randomness are not prepared to do without it, and panicking is the appropriate response. We could add fallible interfaces like
We can use any implementation we want. That includes directly using OS randomness (e.g. on a target that provides it via something like the Linux VDSO) if available, which has multiple advantages, including support for unusual things like vmfork operations (forking a virtual machine and reseeding randomness). This ACP is not attempting to commit to any particular implementation strategy. I do expect, in practice, that there may exist some targets for which we need to use a seeded CSPRNG, because we can get small amounts of randomness but not large amounts.
I rewrote the doc comment. For the secure RNG, there's no way to tell the difference. In practice, I don't think we should use global-and-mutexed for performance reasons, but that's an issue of implementation quality, not something this ACP is trying to mandate. (The difference would only arise for seedable RNGs, which this ACP is not proposing.) |
I'm in favour of a high level API but if we then have two APIs that use an OS entropy source (Rng and RandomState) then it becomes increasingly silly that we don't expose direct access to it. So it'd be good to have a raw |
@matklad I don't think this is an incorrect category: both of those use cases are fundamentally about randomness, and both should be a We can always provide an insecure, seedable random source, if people want fast or reproducible randomness. Whether we achieve cryptographically secure randomness by getting it directly from the OS every time or by using a userspace CSPRNG seems to me like an implementation detail. The tradeoffs there are between performance (OS randomness is likely to be slower, though current Linux is in the process of fixing that), complexity (OS randomness is simpler), and some potentially useful OS features (such as support for OS-triggered reseeding for use cases like forking virtual machines). |
Since there isn't a tracking issue yet, might as well comment here: I think that it would make a lot more sense to lean into what these APIs are designed for, seeding RNGs, rather than just treating them like a proper random number source. From that perspective, using the term "entropy" like the other ACP might make a bit more sense. We could then potentially do something similar to This could also help simplify the move of |
The point of this ACP is to be an easily available random number source; everything else is an implementation detail. We could certainly debate whether we should be using OS randomness directly or to seed our own CSPRNG, but whichever one we do, the point is to provide a useful default random number source, not to provide solely an ingredient for users to build their own. (We should also provide the trait that helps users build their own in an interface-compatible way, but we should have a useful default implementation of that trait.)
I think it'd be a serious mistake to allow replacing the default RNG, and would lead to people not wanting to use the default RNG lest it be replaced by something insecure (or with less clear security properties). People can always use a different |
I personally lean significantly towards no answer to this question. As I've learned from rust-lang/rust#129120, what I mentioned under "there are two ways you can implement DefaultRng" seems to be a non-theoretical concern: some underlying OS API instruct you to use the function to seed a user-space CSPRNG. This puts us in bind with // In `std::random`:
vary by target and by Rust version.
#[derive(Default, Copy, Clone, Debug)]
pub struct DefaultRng; setup: if we don't cache the OS-produced entropy in an in-process CSPRNG, than we are violating API expectations, which probably leads to significantly reduced performance on some OSes. If we do cache, then we'll need to solve the nasty problem of where to cache, which requires us to have thread-local storage, needs special handling during fork, and makes people generating keypairs uneasy because, ideally, they'd prefer for there to be nothing between the key material and the underlying OS API. Consider this alternative: pub mod crypto {
/// Get entropy directly from OS, corresponds to single syscall/vDSO invocation.
pub fn get_entropy(buf: &mut MaybeUninit<[u8]>) -> &mut [u8]
}
pub mod random {
pub struct DefaultRandomSource(ASecurePrng);
impl DefaultRandomSource {
// Get an instance of cryptographically secure random number generator seeded
// from `crypto::get_entropy`.
pub fn new() -> DefaultRandomSource {
let mut seed_buf = [u8; 128];
let seed = crate::crypto::get_entropy(&mut seed_buf);
DefaultRandomSource::with_seed(&seed)
}
pub fn with_seed(seed: &[u8]) -> DefaultRandomSource {
}
}
} It dodges the tradeoff. |
(casually dropping in to mention #159 which aims to solve the "get entropy from the system" part) |
@matklad Again, that still just seems like an argument for what the default RandomSource should be; there's no obvious reason a "guaranteed to be directly from the OS" source couldn't be a RandomSource rather than a different function. |
If that's the case, then I think that it would be wrong to simply offer "a random Like, don't get me wrong, I like the idea of effectively incorporating the
And I personally think that it's unlikely we'll get
Note that I'm not proposing this for users to replace the OS RNG; I'm proposing it so that |
I think something like pub mod crypto {
struct OsRandomSource;
impl crate::random::RandomSource for OsRandomSource { ... }
}
pub mod random {
struct DefaultRandomSource(ASecurePrng);
impl DefaultRandomSource {
pub fn new() -> DefaultRandomSource;
}
impl RandomSource for DefaultRandomSource { ... }
} would also address my concern about mixing up two distinct uses of randomness, yeah, as long as we don't try to shove "get randomness from OS directly" and "get randomness sufficiently quickly" in literally the same function in an elf file. I'd guess even just pub mod random {
struct DefaultRandomSource(ASecurePrng);
impl DefaultRandomSource {
pub fn new() -> DefaultRandomSource;
}
impl RandomSource for DefaultRandomSource { ... }
} would address it: here we explicitly don't provide direct access to OS randomness, and instead just give you an RNG for a guessing game or hash map init. It's just that |
I mean, like I said, I think that the bar for including a proper "RNG" in the standard library would require at minimum the ability to generate a uniform integer or float in a given range, which itself is quite a lot of code from And the default RNG should be cryptographically secure, if we're only providing one. Since just offering bytes from the OS entropy fails both of those by default, I would say it's fit for seeding other RNGs, but not offering as a general random number generator. And having an interface for |
I don't think we'll end up with all of
Having to explicitly pass around an RNG state would be painful for many common uses; having global functions like I'm hoping that on at least some platforms we can avoid doing thread-local shenanigans, but we may end up there eventually on platforms that lack a fast |
Yeah, I should clarify, there are plenty of things in Of course, libstd has its own handful of very complex routines too. The entire formatting circuitry comes to mind. So, it wouldn't be too much of a stretch to include that in libcore, since it should get LTO'd out if it's unused. |
That should be the case on most platforms:
The only problem is Linux, |
Given that it's a new API in std, falling back to thread-local shenanigans for even slightly older systems seems totally fine to me as a user. Either I didn't read the docs and so I probably don't care too much, or I did read the docs and so I knew what I was getting myself into. (I'm ignoring issues like the maintenance or testing burden of having extra code paths.) /2c |
I've opened rust-lang/rust#129201 as an alternative version that uses |
@joboet I think "it's functional in all supported versions but only performant on newer versions" is sufficient to avoid maintaining the fallback, at least for Linux. In practice, even the non-VDSO version is likely to be fast enough for most users. |
Implements the ACP rust-lang/libs-team#393.
Implements the ACP rust-lang/libs-team#393.
Implements the ACP rust-lang/libs-team#393.
Implements the ACP rust-lang/libs-team#393.
…shtriplett std: implement the `random` feature (alternative version) Implements the ACP rust-lang/libs-team#393. This PR is an alternative version of rust-lang#129120 that replaces `getentropy` with `CCRandomGenerateBytes` (on macOS) and `arc4random_buf` (other BSDs), since that function is not suited for generating large amounts of data and should only be used to seed other CPRNGs. `CCRandomGenerateBytes`/`arc4random_buf` on the other hand is (on modern platforms) just as secure and uses its own, very strong CPRNG (ChaCha20 on the BSDs, AES on macOS) periodically seeded with `getentropy`.
…triplett std: implement the `random` feature (alternative version) Implements the ACP rust-lang/libs-team#393. This PR is an alternative version of rust-lang#129120 that replaces `getentropy` with `CCRandomGenerateBytes` (on macOS) and `arc4random_buf` (other BSDs), since that function is not suited for generating large amounts of data and should only be used to seed other CPRNGs. `CCRandomGenerateBytes`/`arc4random_buf` on the other hand is (on modern platforms) just as secure and uses its own, very strong CPRNG (ChaCha20 on the BSDs, AES on macOS) periodically seeded with `getentropy`.
Implements the ACP rust-lang/libs-team#393.
…shtriplett std: implement the `random` feature (alternative version) Implements the ACP rust-lang/libs-team#393. This PR is an alternative version of rust-lang#129120 that replaces `getentropy` with `CCRandomGenerateBytes` (on macOS) and `arc4random_buf` (other BSDs), since that function is not suited for generating large amounts of data and should only be used to seed other CPRNGs. `CCRandomGenerateBytes`/`arc4random_buf` on the other hand is (on modern platforms) just as secure and uses its own, very strong CPRNG (ChaCha20 on the BSDs, AES on macOS) periodically seeded with `getentropy`.
…shtriplett std: implement the `random` feature (alternative version) Implements the ACP rust-lang/libs-team#393. This PR is an alternative version of rust-lang#129120 that replaces `getentropy` with `CCRandomGenerateBytes` (on macOS) and `arc4random_buf` (other BSDs), since that function is not suited for generating large amounts of data and should only be used to seed other CPRNGs. `CCRandomGenerateBytes`/`arc4random_buf` on the other hand is (on modern platforms) just as secure and uses its own, very strong CPRNG (ChaCha20 on the BSDs, AES on macOS) periodically seeded with `getentropy`.
Rollup merge of rust-lang#129201 - joboet:random_faster_sources, r=joshtriplett std: implement the `random` feature (alternative version) Implements the ACP rust-lang/libs-team#393. This PR is an alternative version of rust-lang#129120 that replaces `getentropy` with `CCRandomGenerateBytes` (on macOS) and `arc4random_buf` (other BSDs), since that function is not suited for generating large amounts of data and should only be used to seed other CPRNGs. `CCRandomGenerateBytes`/`arc4random_buf` on the other hand is (on modern platforms) just as secure and uses its own, very strong CPRNG (ChaCha20 on the BSDs, AES on macOS) periodically seeded with `getentropy`.
std: implement the `random` feature (alternative version) Implements the ACP rust-lang/libs-team#393. This PR is an alternative version of #129120 that replaces `getentropy` with `CCRandomGenerateBytes` (on macOS) and `arc4random_buf` (other BSDs), since that function is not suited for generating large amounts of data and should only be used to seed other CPRNGs. `CCRandomGenerateBytes`/`arc4random_buf` on the other hand is (on modern platforms) just as secure and uses its own, very strong CPRNG (ChaCha20 on the BSDs, AES on macOS) periodically seeded with `getentropy`.
I want to highlight this comment. I also think that it's a mistake to expose the wrong kind of primitive to generate a dice roll (like the motivating example). Is there a real-world use case for generating a uniformly random |
It's kind of late, I know (I only became aware of this ACP relatively recently), but can I (maintainer of Yes, it's already a closed issue. There have however been criticisms of the design raised both here and on the tracking issue. Moreover, this issue covers quite a lot of ground making discussion a little difficult... I would suggest the ACP be closed and re-started with multiple smaller ACPs (listed below).
Are we talking about having some entropy source (that could replace the
The first example may want a fast and seedable generator. The second and third examples don't set out any particular requirements. The final case is, uh, somewhat different (quickcheck has its own
This sounds like a return of
Yeah, this is an important thing to discuss.
I'm not all that keen on the design, but fail to see a better one for general utility (though it may be that on some platforms the OS RNG performs much better). The current
While introducing As for whether there is performance justification to having these, it does depend on which use-cases you care to support, but
If we're talking about
At this point,
And from comments:
Yes, some people do want generators with portable output. This is not worth much without random algorithms also being stable, however. In my opinion, is a good argument for usage of an external crate, which supports versioning (see Reproducibility in The Rand Book).
I dislike this argument. (Yes, there is potentially much less quality control and security oversight for crates than there is for the standard library. This is a separate problem however, and If anything, this argument should be used to push for more optimisations (e.g. to solve rust-random/rand#592) and low-level functionality (e.g.
No, it has a I, personally, think this ACP should be replaced with a set of lower-level ACPs, as summarised here (with more questions than answers). Let me know if you'd like me to write any, though probably @newpavlov or @josephlr would do a better job on the first of these. Fresh (external) randomnessThis appears to be the primary raison d'être of Are errors possible? Yes ( Should there be an API for getting potentially-insecure random data? This is already used to seed Should the interface support getting random word-sized values or only filling byte-slices? Some sources such as RDRAND and WASI support direct generation of Default (fast, secure) randomnessThis would be built on top of the above. It might be the same thing (as in the On some platforms, making this truly fast requires a thread-local RNG, as noted above. But, is there good justification for including this as standard behaviour, when the performance-sensitive users could be encouraged to cache their own local generator? This is a tricky question to answer in general. It may even be worth letting the Random generation traits, seedability and portabilityThis is more the topic of #394, except that Should Random uniformly-distributed value generationThis is discussed above under Related to this is the question of whether to provide a Choose and shuffle methodsOne of the most useful pieces of high-level random number functionality is the ability to randomly choose elements and shuffle slices. String and UTF-8 charactersAs a starting point, |
API design partially based on discussions with @BartMassey. Revised based on feedback, in particular from @Amanieu.
Proposal
Problem statement
People regularly want to generate random numbers for a variety of use cases. Doing so currently requires using a crate from
crates.io
.rand
is the 6th most downloaded crate oncrates.io
, andfastrand
is quite popular as well. Many, many people over the years have expressed frustration that random number generation is not available in the standard library (despite the standard library using randomness internally forHashMap
).There are multiple reasons why we have not historically added this capability. Primarily, there are three capabilities people want, and those capabilities seem to present a "pick any two" constraint:
These constraints arise from the possibility of a secure random number generator potentially requiring updates for security reasons. Changing the random number generator would result in different sequences for the same seed.
In addition to that primary constraint, there have also been design difficulties: there are numerous pieces of additional functionality people may want surrounding random number generation, which makes any proposal for it subject to massive scope creep and bikeshed painting. Most notably: users of random numbers may want to represent the state of the RNG explicitly as something they can pass around, or implicitly as global state for simplicity.
This ACP proposes a solution that aims to be as simple as possible, satisfy all the stated constraints on the problem, and allow for future expansion if desired. This ACP proposes a generator that is secure, but not stable across versions of Rust; this allows us to update the secure RNG if any issue or potential improvement arises.
Separately, ACP 394 proposes an RNG that is seedable and guarantees identical seeding across Rust versions, but is not a secure RNG.
Motivating examples or use cases
Solution sketch
The trait
Random
will initially be implemented for all iN and uN integer types,isize
/usize
, andbool
, as well as arrays and tuples of such values.Notably,
Random
will not initially be implemented for floating-point values (to initially avoid questions of distribution), strings/paths/etc (to avoid questions of length and character selection), orchar
(to avoid questions of what subset of values to generate). We can consider such additions in the future; see the section on future work below.The random number generator may use OS randomness directly, if available, or use a CSPRNG seeded from OS/hardware randomness.
Alternatives
We could do nothing, and continue to refer people to external crates like
rand
andfastrand
.We could eliminate the convenience functions that implicitly use
DefaultRng
, and require all users to pass around a RandomSource directly. However, this would add complexity to many simple use cases.We could allow
gen_bytes
to fill an uninitialized buffer. This would be a more complex interface, however. We could potentially introduce such an interface later, when we've stabilized the types to make it simpler.We could use
Read
to get data from random sources (e.g.trait RandomSource: Read
). This would have the advantage of letting us useread_buf
once we stabilize that. However, this would prevent us from puttingRandomSource
incore
.We could allow
gen_bytes
to fail and return aResult
. However, it seems unlikely that most consumers of randomness would be able to handle not having access to it. The higher-level functions will almost certainly want to panic rather than returning a result, for convenience of invocation, and having callers who can deal with an absence of randomness call the low-level interface directly doesn't seem like a sufficiently useful interface to support. We also don't want to introduce a whole family of paralleltry_random
/try_random_range
/etc functions. We could always introduce atry_gen_bytes
interface later, if there's a need for one. (In addition, we would not want to useio::Result
here, as that would preventRandomSource
from living incore
.)We could rename
Random::random
toRandom::random_with
or similar, and userandom
for a function that callsrandom_with(DefaultRng)
. This would make it convenient to call, for instance,u32::random()
. This doesn't seem like an important convenience, however, as it's just as easy to callrandom::<u32>()
(or in most contexts justrandom()
with type inference).Future work
We should support randomly shuffling arrays:
If we need it for performance, we could add functions like
gen_u64
orgen_u32
toRandomSource
(with default implementations based ongen_bytes
), to help RNGs that can implement those more efficiently than they can implementgen_bytes
. This is inspired byHasher
doing something similar. I propose that we initially have justgen_bytes
, and require benchmarks demonstrating a substantial speedup before we consider the additional complexity and interface surface area.We should support random generation in ranges (e.g.
random_range(1..6)
). Providing a correct implementation will steer people away from the most common open-coded implementation (using%
), which introduces bias.We could support choosing a random item from an iterator. (This can be done more optimally when the iterator implements some additional traits.)
We can implement
Random
for many more types, such asNonZero<T>
andWrapping<T>
.We should support
derive(Random)
for types whose fields all implementRandom
. This is relatively straightforward for structs. However, supporting this for enums would require some additional care to handle discriminants: should a randomOption<u8>
be 50%None
, or 1/257None
? The latter is much more difficult to implement correctly.We could add additional
RandomSource
implementations to the standard library, including seeded sources. This would enable purposes such as testing, reproducing the creation of objects whose algorithms require randomness to generate, replaying processes such as fuzz testing, supporting game seeds or replays, and various others. Note that this would not be the same type asDefaultRng
.We should not allow seeding the
DefaultRng
state, as that would affect all users rather than only affecting those that are opting into supporting seeding, and would also preclude designs that don't involve a seed (e.g. obtaining random numbers directly from the OS).We could consider, in the future, introducing random float generation, or random character generation, or generation of various other types. A careful design could allow using the same mechanisms for this as for random generation in ranges (e.g. a
Distribution<T>
trait to sample from). Alternatively, we could leave the full breadth of this to the ecosystem, and just support random ranges directly, as well as some common specific ways to generate floats and characters.We could provide a trait to fill an existing value rather than creating a new one.
What happens now?
This issue contains an API change proposal (or ACP) and is part of the libs-api team feature lifecycle. Once this issue is filed, the libs-api team will review open proposals as capability becomes available. Current response times do not have a clear estimate, but may be up to several months.
Possible responses
The libs team may respond in various different ways. First, the team will consider the problem (this doesn't require any concrete solution or alternatives to have been proposed):
Second, if there's a concrete solution:
The text was updated successfully, but these errors were encountered: