Merge pull request #8842 from LemonBoy/thinko

Some TLCSPRNG fixes
This commit is contained in:
Jakub Konka 2021-05-20 16:53:24 +02:00 committed by GitHub
commit b09936d728
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -48,6 +48,16 @@ const Context = struct {
gimli: std.crypto.core.Gimli,
};
var install_atfork_handler = std.once(struct {
// Install the global handler only once.
// The same handler is shared among threads and is inherinted by fork()-ed
// processes.
fn do() void {
const r = std.c.pthread_atfork(null, null, childAtForkHandler);
std.debug.assert(r == 0);
}
}.do);
threadlocal var wipe_mem: []align(mem.page_size) u8 = &[_]u8{};
fn tlsCsprngFill(_: *const std.rand.Random, buffer: []u8) void {
@ -107,13 +117,9 @@ fn tlsCsprngFill(_: *const std.rand.Random, buffer: []u8) void {
break :wof;
} else |_| {}
os.madvise(
wipe_mem.ptr,
wipe_mem.len,
os.MADV_WIPEONFORK,
) catch {
if (os.madvise(wipe_mem.ptr, wipe_mem.len, os.MADV_WIPEONFORK)) |_| {
return initAndFill(buffer);
};
} else |_| {}
}
if (std.Thread.use_pthreads) {
@ -139,17 +145,14 @@ fn tlsCsprngFill(_: *const std.rand.Random, buffer: []u8) void {
}
fn setupPthreadAtforkAndFill(buffer: []u8) void {
const failed = std.c.pthread_atfork(null, null, childAtForkHandler) != 0;
if (failed) {
const ctx = @ptrCast(*Context, wipe_mem.ptr);
ctx.init_state = .failed;
return fillWithOsEntropy(buffer);
} else {
return initAndFill(buffer);
}
install_atfork_handler.call();
return initAndFill(buffer);
}
fn childAtForkHandler() callconv(.C) void {
// The atfork handler is global, this function may be called after
// fork()-ing threads that never initialized the CSPRNG context.
if (wipe_mem.len == 0) return;
std.crypto.utils.secureZero(u8, wipe_mem);
}