Skip to content

Commit d94f42f

Browse files
aykevldeadprogram
authored andcommitted
crypto/rand: replace this package with a TinyGo version
This package provides access to an operating system resource (cryptographic numbers) and so needs to be replaced with a TinyGo version that does this in a different way. I've made the following choices while adding this feature: - I'm using the getentropy call whenever possible (most POSIX like systems), because it is easier to use and more reliable. Linux is the exception: it only added getentropy relatively recently. - I've left bare-metal implementations to a future patch. This because it's hard to reliably get cryptographically secure random numbers on embedded devices: most devices do not have a hardware PRNG for this purpose.
1 parent d8ac7cc commit d94f42f

File tree

7 files changed

+298
-15
lines changed

7 files changed

+298
-15
lines changed

loader/goroot.go

Lines changed: 36 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,14 @@ package loader
22

33
// This file constructs a new temporary GOROOT directory by merging both the
44
// standard Go GOROOT and the GOROOT from TinyGo using symlinks.
5+
//
6+
// The goal is to replace specific packages from Go with a TinyGo version. It's
7+
// never a partial replacement, either a package is fully replaced or it is not.
8+
// This is important because if we did allow to merge packages (e.g. by adding
9+
// files to a package), it would lead to a dependency on implementation details
10+
// with all the maintenance burden that results in. Only allowing to replace
11+
// packages as a whole avoids this as packages are already designed to have a
12+
// public (backwards-compatible) API.
513

614
import (
715
"crypto/sha512"
@@ -139,6 +147,7 @@ func mergeDirectory(goroot, tinygoroot, tmpgoroot, importPath string, overrides
139147
if err != nil {
140148
return err
141149
}
150+
hasTinyGoFiles := false
142151
for _, e := range tinygoEntries {
143152
if e.IsDir() {
144153
// A directory, so merge this thing.
@@ -154,6 +163,7 @@ func mergeDirectory(goroot, tinygoroot, tmpgoroot, importPath string, overrides
154163
if err != nil {
155164
return err
156165
}
166+
hasTinyGoFiles = true
157167
}
158168
}
159169

@@ -164,21 +174,30 @@ func mergeDirectory(goroot, tinygoroot, tmpgoroot, importPath string, overrides
164174
return err
165175
}
166176
for _, e := range gorootEntries {
167-
if !e.IsDir() {
168-
// Don't merge in files from Go. Otherwise we'd end up with a
169-
// weird syscall package with files from both roots.
170-
continue
171-
}
172-
if _, ok := overrides[path.Join(importPath, e.Name())+"/"]; ok {
173-
// Already included above, so don't bother trying to create this
174-
// symlink.
175-
continue
176-
}
177-
newname := filepath.Join(tmpgoroot, "src", importPath, e.Name())
178-
oldname := filepath.Join(goroot, "src", importPath, e.Name())
179-
err := symlink(oldname, newname)
180-
if err != nil {
181-
return err
177+
if e.IsDir() {
178+
if _, ok := overrides[path.Join(importPath, e.Name())+"/"]; ok {
179+
// Already included above, so don't bother trying to create this
180+
// symlink.
181+
continue
182+
}
183+
newname := filepath.Join(tmpgoroot, "src", importPath, e.Name())
184+
oldname := filepath.Join(goroot, "src", importPath, e.Name())
185+
err := symlink(oldname, newname)
186+
if err != nil {
187+
return err
188+
}
189+
} else {
190+
// Only merge files from Go if TinyGo does not have any files.
191+
// Otherwise we'd end up with a weird mix from both Go
192+
// implementations.
193+
if !hasTinyGoFiles {
194+
newname := filepath.Join(tmpgoroot, "src", importPath, e.Name())
195+
oldname := filepath.Join(goroot, "src", importPath, e.Name())
196+
err := symlink(oldname, newname)
197+
if err != nil {
198+
return err
199+
}
200+
}
182201
}
183202
}
184203
}
@@ -201,6 +220,8 @@ func needsSyscallPackage(buildTags []string) bool {
201220
func pathsToOverride(needsSyscallPackage bool) map[string]bool {
202221
paths := map[string]bool{
203222
"/": true,
223+
"crypto/": true,
224+
"crypto/rand/": false,
204225
"device/": false,
205226
"examples/": false,
206227
"internal/": true,

src/crypto/rand/rand.go

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
// Copyright 2010 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 implements a cryptographically secure
6+
// random number generator.
7+
package rand
8+
9+
import "io"
10+
11+
// Reader is a global, shared instance of a cryptographically
12+
// secure random number generator.
13+
var Reader io.Reader
14+
15+
// Read is a helper function that calls Reader.Read using io.ReadFull.
16+
// On return, n == len(b) if and only if err == nil.
17+
func Read(b []byte) (n int, err error) {
18+
return io.ReadFull(Reader, b)
19+
}

src/crypto/rand/rand_getentropy.go

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
// +build darwin freebsd wasi
2+
3+
// This implementation of crypto/rand uses the getentropy system call (available
4+
// on both MacOS and WASI) to generate random numbers.
5+
6+
package rand
7+
8+
import (
9+
"errors"
10+
"unsafe"
11+
)
12+
13+
var errReadFailed = errors.New("rand: could not read random bytes")
14+
15+
func init() {
16+
Reader = &reader{}
17+
}
18+
19+
type reader struct {
20+
}
21+
22+
func (r *reader) Read(b []byte) (n int, err error) {
23+
if len(b) != 0 {
24+
if len(b) > 256 {
25+
b = b[:256]
26+
}
27+
result := libc_getentropy(unsafe.Pointer(&b[0]), len(b))
28+
if result < 0 {
29+
// Maybe we should return a syscall.Errno here?
30+
return 0, errReadFailed
31+
}
32+
}
33+
return len(b), nil
34+
}
35+
36+
// int getentropy(void *buf, size_t buflen);
37+
//export getentropy
38+
func libc_getentropy(buf unsafe.Pointer, buflen int) int

src/crypto/rand/rand_urandom.go

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
// +build linux,!baremetal,!wasi
2+
3+
// This implementation of crypto/rand uses the /dev/urandom pseudo-file to
4+
// generate random numbers.
5+
// TODO: convert to the getentropy or getrandom libc function on Linux once it
6+
// is more widely supported.
7+
8+
package rand
9+
10+
import (
11+
"syscall"
12+
)
13+
14+
func init() {
15+
Reader = &reader{}
16+
}
17+
18+
type reader struct {
19+
fd int
20+
}
21+
22+
func (r *reader) Read(b []byte) (n int, err error) {
23+
if len(b) == 0 {
24+
return
25+
}
26+
27+
// Open /dev/urandom first if needed.
28+
if r.fd == 0 {
29+
fd, err := syscall.Open("/dev/urandom", syscall.O_RDONLY, 0)
30+
if err != nil {
31+
return 0, err
32+
}
33+
r.fd = fd
34+
}
35+
36+
// Read from the file.
37+
return syscall.Read(r.fd, b)
38+
}

src/crypto/rand/util.go

Lines changed: 143 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,143 @@
1+
// Copyright 2011 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+
"errors"
9+
"io"
10+
"math/big"
11+
)
12+
13+
// smallPrimes is a list of small, prime numbers that allows us to rapidly
14+
// exclude some fraction of composite candidates when searching for a random
15+
// prime. This list is truncated at the point where smallPrimesProduct exceeds
16+
// a uint64. It does not include two because we ensure that the candidates are
17+
// odd by construction.
18+
var smallPrimes = []uint8{
19+
3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53,
20+
}
21+
22+
// smallPrimesProduct is the product of the values in smallPrimes and allows us
23+
// to reduce a candidate prime by this number and then determine whether it's
24+
// coprime to all the elements of smallPrimes without further big.Int
25+
// operations.
26+
var smallPrimesProduct = new(big.Int).SetUint64(16294579238595022365)
27+
28+
// Prime returns a number, p, of the given size, such that p is prime
29+
// with high probability.
30+
// Prime will return error for any error returned by rand.Read or if bits < 2.
31+
func Prime(rand io.Reader, bits int) (p *big.Int, err error) {
32+
if bits < 2 {
33+
err = errors.New("crypto/rand: prime size must be at least 2-bit")
34+
return
35+
}
36+
37+
b := uint(bits % 8)
38+
if b == 0 {
39+
b = 8
40+
}
41+
42+
bytes := make([]byte, (bits+7)/8)
43+
p = new(big.Int)
44+
45+
bigMod := new(big.Int)
46+
47+
for {
48+
_, err = io.ReadFull(rand, bytes)
49+
if err != nil {
50+
return nil, err
51+
}
52+
53+
// Clear bits in the first byte to make sure the candidate has a size <= bits.
54+
bytes[0] &= uint8(int(1<<b) - 1)
55+
// Don't let the value be too small, i.e, set the most significant two bits.
56+
// Setting the top two bits, rather than just the top bit,
57+
// means that when two of these values are multiplied together,
58+
// the result isn't ever one bit short.
59+
if b >= 2 {
60+
bytes[0] |= 3 << (b - 2)
61+
} else {
62+
// Here b==1, because b cannot be zero.
63+
bytes[0] |= 1
64+
if len(bytes) > 1 {
65+
bytes[1] |= 0x80
66+
}
67+
}
68+
// Make the value odd since an even number this large certainly isn't prime.
69+
bytes[len(bytes)-1] |= 1
70+
71+
p.SetBytes(bytes)
72+
73+
// Calculate the value mod the product of smallPrimes. If it's
74+
// a multiple of any of these primes we add two until it isn't.
75+
// The probability of overflowing is minimal and can be ignored
76+
// because we still perform Miller-Rabin tests on the result.
77+
bigMod.Mod(p, smallPrimesProduct)
78+
mod := bigMod.Uint64()
79+
80+
NextDelta:
81+
for delta := uint64(0); delta < 1<<20; delta += 2 {
82+
m := mod + delta
83+
for _, prime := range smallPrimes {
84+
if m%uint64(prime) == 0 && (bits > 6 || m != uint64(prime)) {
85+
continue NextDelta
86+
}
87+
}
88+
89+
if delta > 0 {
90+
bigMod.SetUint64(delta)
91+
p.Add(p, bigMod)
92+
}
93+
break
94+
}
95+
96+
// There is a tiny possibility that, by adding delta, we caused
97+
// the number to be one bit too long. Thus we check BitLen
98+
// here.
99+
if p.ProbablyPrime(20) && p.BitLen() == bits {
100+
return
101+
}
102+
}
103+
}
104+
105+
// Int returns a uniform random value in [0, max). It panics if max <= 0.
106+
func Int(rand io.Reader, max *big.Int) (n *big.Int, err error) {
107+
if max.Sign() <= 0 {
108+
panic("crypto/rand: argument to Int is <= 0")
109+
}
110+
n = new(big.Int)
111+
n.Sub(max, n.SetUint64(1))
112+
// bitLen is the maximum bit length needed to encode a value < max.
113+
bitLen := n.BitLen()
114+
if bitLen == 0 {
115+
// the only valid result is 0
116+
return
117+
}
118+
// k is the maximum byte length needed to encode a value < max.
119+
k := (bitLen + 7) / 8
120+
// b is the number of bits in the most significant byte of max-1.
121+
b := uint(bitLen % 8)
122+
if b == 0 {
123+
b = 8
124+
}
125+
126+
bytes := make([]byte, k)
127+
128+
for {
129+
_, err = io.ReadFull(rand, bytes)
130+
if err != nil {
131+
return nil, err
132+
}
133+
134+
// Clear bits in the first byte to increase the probability
135+
// that the candidate is < max.
136+
bytes[0] &= uint8(int(1<<b) - 1)
137+
138+
n.SetBytes(bytes)
139+
if n.Cmp(max) < 0 {
140+
return
141+
}
142+
}
143+
}

testdata/env.go

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package main
22

33
import (
4+
"crypto/rand"
45
"os"
56
)
67

@@ -20,4 +21,26 @@ func main() {
2021
for _, arg := range os.Args[1:] {
2122
println("arg:", arg)
2223
}
24+
25+
// Check for crypto/rand support.
26+
checkRand()
27+
}
28+
29+
func checkRand() {
30+
buf := make([]byte, 500)
31+
n, err := rand.Read(buf)
32+
if n != len(buf) || err != nil {
33+
println("could not read random numbers:", err)
34+
}
35+
36+
// Very simple test that random numbers are at least somewhat random.
37+
sum := 0
38+
for _, b := range buf {
39+
sum += int(b)
40+
}
41+
if sum < 95*len(buf) || sum > 159*len(buf) {
42+
println("random numbers don't seem that random, the average byte is", sum/len(buf))
43+
} else {
44+
println("random number check was successful")
45+
}
2346
}

testdata/env.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,3 +3,4 @@ ENV2: VALUE2
33

44
arg: first
55
arg: second
6+
random number check was successful

0 commit comments

Comments
 (0)