Skip to content

auth: keep /dev/urandom open for get_random_bytes - #17972

Merged
tchaikov merged 7 commits into
ceph:masterfrom
cbodley:wip-21401
Oct 13, 2017
Merged

tchaikov merged 7 commits into
ceph:masterfrom
cbodley:wip-21401

Conversation

@cbodley

@cbodley cbodley commented Sep 26, 2017 •

Copy link
Copy Markdown
Contributor

to address the issue of fd exhaustion from reading /dev/urandom, the implementation now opens /dev/urandom on startup and caches its fd. if the open fails, an exception is thrown and the process fails to start

when available, getentropy() (based on the getrandom syscall) 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 for get_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 call getentropy() in a loop

the CryptoRandom class was introduced to provide the build-time abstraction for this, depending on whether cmake sets HAVE_GETENTROPY. an instance of CryptoRandom is stored in CephContext, so that it can be initialized during common_init() and accessed by callers that have a cct

some existing users of get_random_bytes() did not need cryptographic randomness, and were converted to the new ceph::util library in include/random.h which uses a faster thread-local std::default_random_engine that doesn't require locking

the 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 a std::runtime_exception like the standard library's random engines do. this makes it impossible for callers to inadvertently ignore failures

Fixes: http://tracker.ceph.com/issues/21401

@adamemerson adamemerson left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread src/rgw/rgw_rados.cc Outdated

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yay!

Comment thread src/auth/Crypto.cc Outdated

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add something like

ceph_assertf_always(r.entropy != 0,
                    "Random device is psuedorandom, refusing to generate insecure cryptographic tokens.");

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@chardan chardan Sep 26, 2017 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Comment thread src/auth/Crypto.cc Outdated

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@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.

Comment thread src/auth/Crypto.cc Outdated

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

+1

Comment thread src/msg/async/AsyncConnection.h Outdated

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good. I hate when people leave return values on functions that can only return success.

Comment thread src/msg/simple/Pipe.cc Outdated

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread src/objclass/class_api.cc Outdated

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Surely this function should just return void?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i'm assuming this is part of the public cls api, so i opted not to change it

Comment thread src/rgw/rgw_common.h Outdated

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread src/rgw/rgw_crypt.cc Outdated

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

+1

@yehudasa yehudasa left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@cbodley overall ok, see my comment

@chardan chardan left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread src/auth/Crypto.cc Outdated

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread src/auth/Crypto.cc Outdated

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Did we want thread_local rather than static? (Applies to other uses of static in this patch.)

Comment thread src/auth/Crypto.cc Outdated

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would prefer to see globals collected toward the top of the file, preferably commented.

Comment thread src/auth/Crypto.cc Outdated

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Perhaps remove the comment (although it harms nothing, the following line has no other meaning).

Comment thread src/auth/Crypto.cc Outdated

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Much enjoying watching code disappear! :-)

Comment thread src/msg/async/AsyncConnection.cc Outdated

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please consider C++ style casts.

Comment thread src/rgw/rgw_common.cc Outdated

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I hope I can get back to battling against VLAs soon...

Comment thread src/auth/Crypto.cc Outdated

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

+1

Comment thread src/rgw/rgw_crypt.cc Outdated

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

+1

@cbodley

cbodley commented Sep 27, 2017

Copy link
Copy Markdown
Contributor Author

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 getrandom() system call instead of reading from /dev/urandom, which according to the man page "does not involve the use of pathnames or file descriptors", so would also be a valid fix for the issue of fd exhaustion

@chardan

chardan commented Sep 27, 2017

Copy link
Copy Markdown
Contributor

@cbodley I think you're ok with std::random_device. Benchmark result is unfortunate, though!

@cbodley
cbodley force-pushed the wip-21401 branch 2 times, most recently from 46f46d3 to 90d0476 Compare September 28, 2017 20:45
@cbodley

cbodley commented Sep 28, 2017

Copy link
Copy Markdown
Contributor Author

I pushed an updated benchmark that adds the flags --with-getrandom to test the getrandom() system call, and --with-random-device for a thread_local std::random_device

single-threaded results: bin/bench_crypto_random --threads 1 --count 100000

Benchmark Time (ms)
mt:19937 232905
/dev/urandom 130279
getrandom() 33934
std::random_device 364015

I also found that std::random_device would sometimes throw a std::runtime_error("random_device::__x86_rdrand(void)") and terminate the benchmark. I didn't see this at --threads 1, but it happened intermittently at --threads 4 and reproduced consistently at --threads 8. I omitted it from the multi-threaded results.

multi-threaded results (on a cpu with 8 hw threads): bin/bench_crypto_random --threads 8 --count 100000

Benchmark Time (ms)
mt:19937 638997
/dev/urandom 474267
getrandom() 458149

getrandom() looks like a winner so far. It wasn't added to the kernel until 3.17 (post-trusty), and isn't present in glibc until v2.25 - I'm running 2.24, so I had to use syscall() directly (more on that here).

@tchaikov tchaikov left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

does not compile on centos7 and trusty.

Comment thread src/test/bench_crypto_random.cc Outdated

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

/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

@cbodley cbodley changed the title auth: use standard library for get_random_bytes auth: keep /dev/urandom open for get_random_bytes Oct 4, 2017
Comment thread src/include/random.h Outdated

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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! ;->).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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>()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@cbodley I'm ok with your change, just make IntegerT = int. Reverting is fine too, but I like what you did.

@cbodley

cbodley commented Oct 5, 2017

Copy link
Copy Markdown
Contributor Author

thanks for the reviews so far. based on the benchmark results and further discussions, i decided to stick with /dev/urandom here. i updated the pr description with details, please take another look!

Comment thread src/auth/Crypto.cc Outdated

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)
...

Comment thread src/auth/Crypto.h Outdated

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Non-throwing dtors in C++11 are implicitly noexcept.

Comment thread src/include/random.h Outdated

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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).

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we have the generic version and make a few aliases?

generate_random_int, generate_random_long…

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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…

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@cbodley
cbodley force-pushed the wip-21401 branch 3 times, most recently from 4fedbcf to 436e136 Compare October 6, 2017 18:21
@cbodley

cbodley commented Oct 11, 2017

Copy link
Copy Markdown
Contributor Author

@tchaikov could you take another look please?

Comment thread src/include/random.h
(min, max);
using limits = std::numeric_limits<IntegerT>;
return detail::generate_random_number<IntegerT, DistributionT, EngineT>
(limits::min(), limits::max());

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice!

@tchaikov
tchaikov merged commit f782281 into ceph:master Oct 13, 2017
@cbodley
cbodley deleted the wip-21401 branch October 13, 2017 13:30
cbodley added a commit to cbodley/ceph that referenced this pull request Jan 8, 2018
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)
@cbodley cbodley mentioned this pull request Dec 6, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants