From: Jason A. Donenfeld Date: Thu, 9 Dec 2021 14:24:38 +0000 (+0100) Subject: crypto/rand: separate out plan9 X9.31 /dev/random expander X-Git-Tag: go1.19beta1~1167 X-Git-Url: http://www.git.cypherpunks.su/?a=commitdiff_plain;h=c9b60632ebb08a428a9bd15a89798a693667cb05;p=gostls13.git crypto/rand: separate out plan9 X9.31 /dev/random expander The X9.31 expander is now only used for plan9. Perhaps once upon a time there was a use for abstraction, but the code is now covered in hacky "fileName == urandomDevice" and "GOOS == plan9" checks, to the point where the abstraction is much too leaky. Since plan9 is the only platform that has a /dev/random without a /dev/urandom, we can simplify both the generic urandom code and the plan9 X9.31 code by separating them into different files, each focusing on doing one thing well. Change-Id: I0ca43b748a0fbbd60f2ec7819688a540506d34df Reviewed-on: https://go-review.googlesource.com/c/go/+/370580 Trust: Jason Donenfeld Run-TryBot: Jason Donenfeld TryBot-Result: Gopher Robot Reviewed-by: Filippo Valsorda --- diff --git a/src/crypto/rand/eagain.go b/src/crypto/rand/eagain.go deleted file mode 100644 index f018e75931..0000000000 --- a/src/crypto/rand/eagain.go +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -//go:build aix || darwin || dragonfly || freebsd || linux || netbsd || openbsd || solaris - -package rand - -import ( - "io/fs" - "syscall" -) - -func init() { - isEAGAIN = unixIsEAGAIN -} - -// unixIsEAGAIN reports whether err is a syscall.EAGAIN wrapped in a PathError. -// See golang.org/issue/9205 -func unixIsEAGAIN(err error) bool { - if pe, ok := err.(*fs.PathError); ok { - if errno, ok := pe.Err.(syscall.Errno); ok && errno == syscall.EAGAIN { - return true - } - } - return false -} diff --git a/src/crypto/rand/rand_plan9.go b/src/crypto/rand/rand_plan9.go new file mode 100644 index 0000000000..b81d73ca80 --- /dev/null +++ b/src/crypto/rand/rand_plan9.go @@ -0,0 +1,109 @@ +// Copyright 2010 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Plan9 cryptographically secure pseudorandom number +// generator. + +package rand + +import ( + "crypto/aes" + "crypto/cipher" + "encoding/binary" + "io" + "os" + "sync" + "sync/atomic" + "time" +) + +const randomDevice = "/dev/random" + +func init() { + Reader = &reader{} +} + +// reader is a new pseudorandom generator that seeds itself by +// reading from /dev/random. The Read method on the returned +// reader always returns the full amount asked for, or else it +// returns an error. The generator uses the X9.31 algorithm with +// AES-128, reseeding after every 1 MB of generated data. +type reader struct { + mu sync.Mutex + budget int // number of bytes that can be generated + cipher cipher.Block + entropy io.Reader + entropyUsed int32 // atomic; whether entropy has been used + time, seed, dst, key [aes.BlockSize]byte +} + +func warnBlocked() { + println("crypto/rand: blocked for 60 seconds waiting to read random data from the kernel") +} + +func (r *reader) readEntropy(b []byte) error { + if atomic.CompareAndSwapInt32(&r.entropyUsed, 0, 1) { + // First use of randomness. Start timer to warn about + // being blocked on entropy not being available. + t := time.AfterFunc(time.Minute, warnBlocked) + defer t.Stop() + } + var err error + if r.entropy == nil { + r.entropy, err = os.Open(randomDevice) + if err != nil { + return err + } + } + _, err = io.ReadFull(r.entropy, b) + return err +} + +func (r *reader) Read(b []byte) (n int, err error) { + r.mu.Lock() + defer r.mu.Unlock() + n = len(b) + + for len(b) > 0 { + if r.budget == 0 { + err = r.readEntropy(r.seed[0:]) + if err != nil { + return n - len(b), err + } + err = r.readEntropy(r.key[0:]) + if err != nil { + return n - len(b), err + } + r.cipher, err = aes.NewCipher(r.key[0:]) + if err != nil { + return n - len(b), err + } + r.budget = 1 << 20 // reseed after generating 1MB + } + r.budget -= aes.BlockSize + + // ANSI X9.31 (== X9.17) algorithm, but using AES in place of 3DES. + // + // single block: + // t = encrypt(time) + // dst = encrypt(t^seed) + // seed = encrypt(t^dst) + ns := time.Now().UnixNano() + binary.BigEndian.PutUint64(r.time[:], uint64(ns)) + r.cipher.Encrypt(r.time[0:], r.time[0:]) + for i := 0; i < aes.BlockSize; i++ { + r.dst[i] = r.time[i] ^ r.seed[i] + } + r.cipher.Encrypt(r.dst[0:], r.dst[0:]) + for i := 0; i < aes.BlockSize; i++ { + r.seed[i] = r.time[i] ^ r.dst[i] + } + r.cipher.Encrypt(r.seed[0:], r.seed[0:]) + + m := copy(b, r.dst[0:]) + b = b[m:] + } + + return n, nil +} diff --git a/src/crypto/rand/rand_unix.go b/src/crypto/rand/rand_unix.go index 40347874c5..b800ec8fb7 100644 --- a/src/crypto/rand/rand_unix.go +++ b/src/crypto/rand/rand_unix.go @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -//go:build aix || darwin || dragonfly || freebsd || linux || netbsd || openbsd || plan9 || solaris +//go:build aix || darwin || dragonfly || freebsd || linux || netbsd || openbsd || solaris // Unix cryptographically secure pseudorandom number // generator. @@ -11,36 +11,26 @@ package rand import ( "bufio" - "crypto/aes" - "crypto/cipher" - "encoding/binary" + "errors" "io" "os" - "runtime" "sync" "sync/atomic" + "syscall" "time" ) const urandomDevice = "/dev/urandom" -// Easy implementation: read from /dev/urandom. -// This is sufficient on Linux, OS X, and FreeBSD. - func init() { - if runtime.GOOS == "plan9" { - Reader = newReader(nil) - } else { - Reader = &devReader{name: urandomDevice} - } + Reader = &reader{} } -// A devReader satisfies reads by reading the file named name. -type devReader struct { - name string +// A reader satisfies reads by reading from urandomDevice +type reader struct { f io.Reader mu sync.Mutex - used int32 // atomic; whether this devReader has been used + used int32 // atomic; whether this reader has been used } // altGetRandom if non-nil specifies an OS-specific function to get @@ -51,34 +41,28 @@ func warnBlocked() { println("crypto/rand: blocked for 60 seconds waiting to read random data from the kernel") } -func (r *devReader) Read(b []byte) (n int, err error) { +func (r *reader) Read(b []byte) (n int, err error) { if atomic.CompareAndSwapInt32(&r.used, 0, 1) { // First use of randomness. Start timer to warn about // being blocked on entropy not being available. - t := time.AfterFunc(60*time.Second, warnBlocked) + t := time.AfterFunc(time.Minute, warnBlocked) defer t.Stop() } - if altGetRandom != nil && r.name == urandomDevice && altGetRandom(b) { + if altGetRandom != nil && altGetRandom(b) { return len(b), nil } r.mu.Lock() defer r.mu.Unlock() if r.f == nil { - f, err := os.Open(r.name) - if f == nil { + f, err := os.Open(urandomDevice) + if err != nil { return 0, err } - if runtime.GOOS == "plan9" { - r.f = f - } else { - r.f = bufio.NewReader(hideAgainReader{f}) - } + r.f = bufio.NewReader(hideAgainReader{f}) } return r.f.Read(b) } -var isEAGAIN func(error) bool // set by eagain.go on unix systems - // hideAgainReader masks EAGAIN reads from /dev/urandom. // See golang.org/issue/9205 type hideAgainReader struct { @@ -87,83 +71,8 @@ type hideAgainReader struct { func (hr hideAgainReader) Read(p []byte) (n int, err error) { n, err = hr.r.Read(p) - if err != nil && isEAGAIN != nil && isEAGAIN(err) { + if errors.Is(err, syscall.EAGAIN) { err = nil } return } - -// Alternate pseudo-random implementation for use on -// systems without a reliable /dev/urandom. - -// newReader returns a new pseudorandom generator that -// seeds itself by reading from entropy. If entropy == nil, -// the generator seeds itself by reading from the system's -// random number generator, typically /dev/random. -// The Read method on the returned reader always returns -// the full amount asked for, or else it returns an error. -// -// The generator uses the X9.31 algorithm with AES-128, -// reseeding after every 1 MB of generated data. -func newReader(entropy io.Reader) io.Reader { - if entropy == nil { - entropy = &devReader{name: "/dev/random"} - } - return &reader{entropy: entropy} -} - -type reader struct { - mu sync.Mutex - budget int // number of bytes that can be generated - cipher cipher.Block - entropy io.Reader - time, seed, dst, key [aes.BlockSize]byte -} - -func (r *reader) Read(b []byte) (n int, err error) { - r.mu.Lock() - defer r.mu.Unlock() - n = len(b) - - for len(b) > 0 { - if r.budget == 0 { - _, err := io.ReadFull(r.entropy, r.seed[0:]) - if err != nil { - return n - len(b), err - } - _, err = io.ReadFull(r.entropy, r.key[0:]) - if err != nil { - return n - len(b), err - } - r.cipher, err = aes.NewCipher(r.key[0:]) - if err != nil { - return n - len(b), err - } - r.budget = 1 << 20 // reseed after generating 1MB - } - r.budget -= aes.BlockSize - - // ANSI X9.31 (== X9.17) algorithm, but using AES in place of 3DES. - // - // single block: - // t = encrypt(time) - // dst = encrypt(t^seed) - // seed = encrypt(t^dst) - ns := time.Now().UnixNano() - binary.BigEndian.PutUint64(r.time[:], uint64(ns)) - r.cipher.Encrypt(r.time[0:], r.time[0:]) - for i := 0; i < aes.BlockSize; i++ { - r.dst[i] = r.time[i] ^ r.seed[i] - } - r.cipher.Encrypt(r.dst[0:], r.dst[0:]) - for i := 0; i < aes.BlockSize; i++ { - r.seed[i] = r.time[i] ^ r.dst[i] - } - r.cipher.Encrypt(r.seed[0:], r.seed[0:]) - - m := copy(b, r.dst[0:]) - b = b[m:] - } - - return n, nil -}