Skip to content

Commit ddfe7b3

Browse files
Michael McConvillebradfitz
Michael McConville
authored andcommitted
crypto/rand: use the getentropy syscall on OpenBSD
Go already supports Linux's getrandom, which is a slightly modified version of getentropy. getentropy was added in OpenBSD 5.6. All supported versions of OpenBSD include it so, unlike with Linux and getrandom, we don't need to test for its presence. Fixes #13785. Change-Id: Ib536b96675f257cd8c5de1e3a36165e15c9abac9 Reviewed-on: https://go-review.googlesource.com/18219 Run-TryBot: Brad Fitzpatrick <[email protected]> TryBot-Result: Gobot Gobot <[email protected]> Reviewed-by: Brad Fitzpatrick <[email protected]>
1 parent ee17727 commit ddfe7b3

File tree

3 files changed

+55
-1
lines changed

3 files changed

+55
-1
lines changed

src/crypto/rand/rand.go

+2-1
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,9 @@ import "io"
1111
// Reader is a global, shared instance of a cryptographically
1212
// strong pseudo-random generator.
1313
//
14-
// On Unix-like systems, Reader reads from /dev/urandom.
1514
// On Linux, Reader uses getrandom(2) if available, /dev/urandom otherwise.
15+
// On OpenBSD, Reader uses getentropy(2).
16+
// On other Unix-like systems, Reader reads from /dev/urandom.
1617
// On Windows systems, Reader uses the CryptGenRandom API.
1718
var Reader io.Reader
1819

src/crypto/rand/rand_openbsd.go

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
// Copyright 2016 The Go Authors. All rights reserved.
2+
// Use of this source code is governed by a BSD-style
3+
// license that can be found in the LICENSE file.
4+
5+
package rand
6+
7+
import (
8+
"internal/syscall/unix"
9+
)
10+
11+
func init() {
12+
altGetRandom = getRandomOpenBSD
13+
}
14+
15+
func getRandomOpenBSD(p []byte) (ok bool) {
16+
// getentropy(2) returns a maximum of 256 bytes per call
17+
for i := 0; i < len(p); i += 256 {
18+
end := i + 256
19+
if len(p) < end {
20+
end = len(p)
21+
}
22+
err := unix.GetEntropy(p[i:end])
23+
if err != nil {
24+
return false
25+
}
26+
}
27+
return true
28+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
// Copyright 2016 The Go Authors. All rights reserved.
2+
// Use of this source code is governed by a BSD-style
3+
// license that can be found in the LICENSE file.
4+
5+
package unix
6+
7+
import (
8+
"syscall"
9+
"unsafe"
10+
)
11+
12+
// getentropy(2)'s syscall number, from /usr/src/sys/kern/syscalls.master
13+
const entropyTrap uintptr = 7
14+
15+
// GetEntropy calls the OpenBSD getentropy system call.
16+
func GetEntropy(p []byte) error {
17+
_, _, errno := syscall.Syscall(entropyTrap,
18+
uintptr(unsafe.Pointer(&p[0])),
19+
uintptr(len(p)),
20+
0)
21+
if errno != 0 {
22+
return errno
23+
}
24+
return nil
25+
}

0 commit comments

Comments
 (0)