Repository navigation
auth: keep /dev/urandom open for get_random_bytes - #17972
Conversation
adamemerson
left a comment
There was a problem hiding this comment.
I approve of this patch!
The only change I really insist on is a check of the random device's entropy and a hard STOP if it turns out to be deterministic.
There was a problem hiding this comment.
Add something like
ceph_assertf_always(r.entropy != 0,
"Random device is psuedorandom, refusing to generate insecure cryptographic tokens.");
There was a problem hiding this comment.
i don't think we can rely on the entropy being accurate. quoting cppreference on random_device::entropy():
Notes
This function is not fully implemented in some standard libraries. For example, GNU libstdc++ and LLVM libc++ always return zero even though the device is non-deterministic (for libstdc++, see bug 67578). In comparison, Microsoft Visual C++ implementation always returns 32, and boost.random returns 10.
There was a problem hiding this comment.
Ahura H. Mazda that's infuriating. I can understand them not calculating it accurately, but at least giving a basic guidance as to whether they failed to open /dev/urandom and fell back to something deterministic should be a minimum.
All right, never mind that then.
There was a problem hiding this comment.
The standard says (26.5.6) that entropy() returns 0.0 if the implementation uses a random number engine, otherwise an entropy estimate. See the full entry for details of how that's calculated. (That doesn't really help with incomplete standard library implementations!) As I read it, it doesn't mean you will necessarily have poor random numbers (as in @cbodley 's example, where it actually /is/ using a non-deterministic device). Anyway, not sure that helps with anything, but maybe it's worth a peek under the covers.
There was a problem hiding this comment.
Oh! std::random_device()'s constructor throws if it can't initialize. (At least in the case of libc++, that means on a failure to open /dev/urandom.)
@adamemerson
There was a problem hiding this comment.
Are we sure we want a random mutex instead of per-thread engines? If we're using this to make key material for RGW the contention might be a limiting factor, I'm not sure.
There was a problem hiding this comment.
that's a good question. i considered that, but worry about the per-thread memory overhead of std::mt19937 - with gcc, sizeof(std::mt19937) is 5000. with respect to contention, i would expect these critical sections to be pretty small - and likely to match what the kernel was doing when reading from /dev/urandom. i'll write a little benchmark to get some comparisons
There was a problem hiding this comment.
@cbodley @adamemerson yeah, I'm not excited about introducing this potential bottleneck. Maybe we can have a pool of engines to reduce potential contention? Can then select which engine to use by thread_id % num_engines or so.
There was a problem hiding this comment.
I wonder if it would be worthwhile to have a version that just returns a std:array of random bytes when we know the number of bytes needed at compile time.
(I'm tempted to import span from the GSL sometime since it supports using compile time information when we know what it is.)
There was a problem hiding this comment.
i think it would be cool to have an interface based on iterators so you could use it with any container or raw pointer. for now though, i'd rather limit the changes to call sites
There was a problem hiding this comment.
Good. I hate when people leave return values on functions that can only return success.
There was a problem hiding this comment.
Also really the error handling we DID have was horrible. If we can't get actual random bytes in a cryptographic context it's better to just halt, or at least refuse the operation.
There was a problem hiding this comment.
Surely this function should just return void?
There was a problem hiding this comment.
i'm assuming this is part of the public cls api, so i opted not to change it
There was a problem hiding this comment.
Not directly related to your patch, but we should really kill 'extern' on function prototypes when we're changing them. Function prototypes are extern, there's no reason to add it, it just adds noise.
There was a problem hiding this comment.
This is an example of a case where I think something like
template<std::size_t N>
std::array<char, N> get_random_bytes()
would be useful.
chardan
left a comment
There was a problem hiding this comment.
This is looking good so far! A few things for you to peek at and/or consider. The concern about per-thread engines seems worth mulling over, too.
There was a problem hiding this comment.
Alternatively, you could consider adding SFINAE selection in ceph::util::random() to set up this engine. See randomize_rng()-- it may be trickier to shoehorn in than necessary, but OTOH it would be nice to be able to go through it here. OTOH, that library isn't really mean to be suited to specialized tasks, which this may be.
There was a problem hiding this comment.
Did we want thread_local rather than static? (Applies to other uses of static in this patch.)
There was a problem hiding this comment.
I would prefer to see globals collected toward the top of the file, preferably commented.
There was a problem hiding this comment.
Perhaps remove the comment (although it harms nothing, the following line has no other meaning).
There was a problem hiding this comment.
Much enjoying watching code disappear! :-)
There was a problem hiding this comment.
Please consider C++ style casts.
There was a problem hiding this comment.
I hope I can get back to battling against VLAs soon...
|
i added a benchmark that compares the new implementation against the old one, and std::mt19937 is considerably slower. even with a single thread and the mutex removed (and warming up the mt19937 engine before benchmarking), mt19937 takes almost twice as long. this is surprising, and i'll have to reconsider using it at all @adamemerson suggested using the |
|
@cbodley I think you're ok with std::random_device. Benchmark result is unfortunate, though! |
46f46d3 to
90d0476
Compare
|
I pushed an updated benchmark that adds the flags single-threaded results:
I also found that multi-threaded results (on a cpu with 8 hw threads):
|
tchaikov
left a comment
There was a problem hiding this comment.
does not compile on centos7 and trusty.
There was a problem hiding this comment.
/home/jenkins-build/build/workspace/ceph-dev-new-build/ARCH/x86_64/AVAILABLE_ARCH/x86_64/AVAILABLE_DIST/centos7/DIST/centos7/MACHINE_SIZE/huge/release/13.0.0-1476-g1c8dc07/rpm/el7/BUILD/ceph-13.0.0-1476-g1c8dc07/src/test/bench_crypto_random.cc: In function 'int my_getrandom(void*, size_t)':
/home/jenkins-build/build/workspace/ceph-dev-new-build/ARCH/x86_64/AVAILABLE_ARCH/x86_64/AVAILABLE_DIST/centos7/DIST/centos7/MACHINE_SIZE/huge/release/13.0.0-1476-g1c8dc07/rpm/el7/BUILD/ceph-13.0.0-1476-g1c8dc07/src/test/bench_crypto_random.cc:74:18: error: 'SYS_getrandom' was not declared in this scope
return syscall(SYS_getrandom, buf, buflen, 0);
^
[ 58%] Building CXX object src/librbd/CMakeFiles/rbd_internal.dir/operation/MetadataRemoveRequest.cc.o
/home/jenkins-build/build/workspace/ceph-dev-new-build/ARCH/x86_64/AVAILABLE_ARCH/x86_64/AVAILABLE_DIST/centos7/DIST/centos7/MACHINE_SIZE/huge/release/13.0.0-1476-g1c8dc07/rpm/el7/BUILD/ceph-13.0.0-1476-g1c8dc07/src/test/bench_crypto_random.cc:75:1: warning: control reaches end of non-void function [-Wreturn-type]
}
^
make[2]: *** [src/test/CMakeFiles/bench_crypto_random.dir/bench_crypto_random.cc.o] Error 1
There was a problem hiding this comment.
@chardan how do you feel about this change? i was trying to use generate_random_number<uint64_t>() and found that this was only specialized for int. making this generic has the side effect that it can return negative numbers for int instead of starting at int min = 0. but i think it's more natural for generate_random_number<T>() to use the entire range of values available to T
There was a problem hiding this comment.
I'm of two minds here. I'm ok with allowing different integer types, but if we allow negatives ranges we'll have to update the tests as well. The reason the range is from 0 to max is because the original mission was to replace rand(), which provides a similar range. So the minimal change here might be to take a parametric type (default to int) and keep the 0 range; add a test that checks the parametric type works with a few different kinds of int. If we want to move from 0, there will need to probably be more checking, but I'm not opposed to it (just more work for you! ;->).
There was a problem hiding this comment.
okay. i think the defaults for some of these overloads are confusing as is - for example, generate_random_number(5) uses min=0 and max=5 despite 5 being the first argument
so i'd rather have the callers be explicit about the range they request, even if it means they have to mess with with std::numeric_limits themselves. i'll revert this change, and avoid the calls to generate_random_number<uint64_t>()
There was a problem hiding this comment.
@cbodley I'm ok with your change, just make IntegerT = int. Reverting is fine too, but I like what you did.
|
thanks for the reviews so far. based on the benchmark results and further discussions, i decided to stick with |
There was a problem hiding this comment.
Note that C++ lets you declare a variable in a branch, so you can do this in one step if you want:
if(auto ret = safe_read_exact(fd, buf, len) > 0)
...
There was a problem hiding this comment.
Non-throwing dtors in C++11 are implicitly noexcept.
There was a problem hiding this comment.
Can the compiler deduce that..? Otherwise all calls will have to look like:
generate_random_number()?
...which I don't think we want. Ok if the default is "int" and we use the explicit parameter for special cases, though (that was the original intent).
There was a problem hiding this comment.
Could we have the generic version and make a few aliases?
generate_random_int, generate_random_long…
There was a problem hiding this comment.
We could, but I think that if int is indeed the type we want the most, it's best to just leave that as default and just use explicit specialization for when we need them. There's also no reason that in any particular module one couldn't write:
auto gen_double = [](double min, double max) {
return ceph::util::generate_random_number(min, max);
};
...or something. Unless you feel like such aliases would be really frequently useful?
There was a problem hiding this comment.
Well, I tend to rarely use straight-up int when I'm writing code. If I were making a library for myself I'd mostly just take the generic version because I'll always want a uint32_t or a uint16_t or an int64_t or…
There was a problem hiding this comment.
One of the reasons for that design choice (and this also is why min defaults to 0) is that the main purpose of the library is to be a drop-in replacement for rand(), which implies int and (0-max]. But, if we're finding ourselves needing a specific size all the time, having alternatives with certain sizes or different ranges starts to make sense; I see no reason we couldn't add them, but I don't think they'd be right for replacing the main interface since they'd break the contract.
4fedbcf to
436e136
Compare
Signed-off-by: Casey Bodley <[email protected]>
Signed-off-by: Casey Bodley <[email protected]>
Signed-off-by: Casey Bodley <[email protected]>
Signed-off-by: Casey Bodley <[email protected]>
Signed-off-by: Casey Bodley <[email protected]>
Signed-off-by: Casey Bodley <[email protected]>
Signed-off-by: Casey Bodley <[email protected]>
|
@tchaikov could you take another look please? |
| (min, max); | ||
| using limits = std::numeric_limits<IntegerT>; | ||
| return detail::generate_random_number<IntegerT, DistributionT, EngineT> | ||
| (limits::min(), limits::max()); |
adds a more specific option for this boost::context dependency, which was previously only used by the radosgw beast frontend. see http://tracker.ceph.com/issues/20048 for more background Signed-off-by: Casey Bodley <[email protected]> (cherry picked from commit b589b73) Conflicts: src/include/config-h.in.cmake (missing HAVE_GETENTROPY from ceph#17972)
to address the issue of fd exhaustion from reading
/dev/urandom, the implementation now opens/dev/urandomon startup and caches its fd. if the open fails, an exception is thrown and the process fails to startwhen available,
getentropy()(based on thegetrandomsyscall) will be used instead to bypass the filesystem and read from the same urandom source. note that it does introduce the restriction that you can only read up to 256 bytes at a time - this is reasonable for all current uses forget_random_bytes(), and is a good way to prevent callers from exhausting the system entropy. if it becomes necessary to provide more than that at a time, we can always callgetentropy()in a loopthe
CryptoRandomclass was introduced to provide the build-time abstraction for this, depending on whether cmake setsHAVE_GETENTROPY. an instance ofCryptoRandomis stored inCephContext, so that it can be initialized duringcommon_init()and accessed by callers that have acctsome existing users of
get_random_bytes()did not need cryptographic randomness, and were converted to the newceph::utillibrary ininclude/random.hwhich uses a faster thread-localstd::default_random_enginethat doesn't require lockingthe remaining users were modified to remove their error handling, now that
CryptoRandom::get_bytes()returns void. if the implementation encounters an error condition, it throws astd::runtime_exceptionlike the standard library's random engines do. this makes it impossible for callers to inadvertently ignore failuresFixes: http://tracker.ceph.com/issues/21401