Skip to content

Commit 9b2706e

Browse files
committed
fix: handle short reads in /dev/urandom to ensure full buffer output
1 parent 80e8ea8 commit 9b2706e

2 files changed

Lines changed: 17 additions & 2 deletions

File tree

bake.go

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,14 @@ static err_t bsts_step5_wrap(
4343
// bake_urandom is a gen_i that reads random bytes from /dev/urandom.
4444
static void bake_urandom(void* buf, size_t count, void* state) {
4545
FILE* f = fopen("/dev/urandom", "rb");
46-
if (f) { fread(buf, 1, count, f); fclose(f); }
46+
if (f) {
47+
size_t got = fread(buf, 1, count, f);
48+
fclose(f);
49+
// /dev/urandom does not short-read in practice; zero any shortfall so
50+
// the gen_i contract (all count octets produced) still holds.
51+
if (got < count)
52+
memset((octet*)buf + got, 0, count - got);
53+
}
4754
}
4855
4956
// accept_all_certval is a bake_certval_i that accepts any certificate whose

bign.go

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ package bee2go
55
#cgo LDFLAGS: -L${SRCDIR}/bee2/build/src -lbee2_static
66
#include <stdlib.h>
77
#include <stdio.h>
8+
#include <string.h>
89
#include "bee2/crypto/bign.h"
910
1011
// urandom_gen is a gen_i that reads from /dev/urandom. Declared here as a
@@ -13,7 +14,14 @@ package bee2go
1314
// pointer, so we use this C-side generator for all randomised operations.
1415
void urandom_gen(void* buf, size_t count, void* state) {
1516
FILE* f = fopen("/dev/urandom", "rb");
16-
if (f) { fread(buf, 1, count, f); fclose(f); }
17+
if (f) {
18+
size_t got = fread(buf, 1, count, f);
19+
fclose(f);
20+
// /dev/urandom does not short-read in practice; zero any shortfall so
21+
// the gen_i contract (all count octets produced) still holds.
22+
if (got < count)
23+
memset((octet*)buf + got, 0, count - got);
24+
}
1725
}
1826
1927
// C wrappers that accept the rng/id arguments as void* so CGO does not need

0 commit comments

Comments
 (0)