...

Source file src/crypto/rand/rand_unix.go

Documentation: crypto/rand

		 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  //go:build aix || darwin || dragonfly || freebsd || linux || netbsd || openbsd || plan9 || solaris
		 6  // +build aix darwin dragonfly freebsd linux netbsd openbsd plan9 solaris
		 7  
		 8  // Unix cryptographically secure pseudorandom number
		 9  // generator.
		10  
		11  package rand
		12  
		13  import (
		14  	"bufio"
		15  	"crypto/aes"
		16  	"crypto/cipher"
		17  	"encoding/binary"
		18  	"io"
		19  	"os"
		20  	"runtime"
		21  	"sync"
		22  	"sync/atomic"
		23  	"time"
		24  )
		25  
		26  const urandomDevice = "/dev/urandom"
		27  
		28  // Easy implementation: read from /dev/urandom.
		29  // This is sufficient on Linux, OS X, and FreeBSD.
		30  
		31  func init() {
		32  	if runtime.GOOS == "plan9" {
		33  		Reader = newReader(nil)
		34  	} else {
		35  		Reader = &devReader{name: urandomDevice}
		36  	}
		37  }
		38  
		39  // A devReader satisfies reads by reading the file named name.
		40  type devReader struct {
		41  	name string
		42  	f		io.Reader
		43  	mu	 sync.Mutex
		44  	used int32 // atomic; whether this devReader has been used
		45  }
		46  
		47  // altGetRandom if non-nil specifies an OS-specific function to get
		48  // urandom-style randomness.
		49  var altGetRandom func([]byte) (err error)
		50  
		51  func warnBlocked() {
		52  	println("crypto/rand: blocked for 60 seconds waiting to read random data from the kernel")
		53  }
		54  
		55  func (r *devReader) Read(b []byte) (n int, err error) {
		56  	if atomic.CompareAndSwapInt32(&r.used, 0, 1) {
		57  		// First use of randomness. Start timer to warn about
		58  		// being blocked on entropy not being available.
		59  		t := time.AfterFunc(60*time.Second, warnBlocked)
		60  		defer t.Stop()
		61  	}
		62  	if altGetRandom != nil && r.name == urandomDevice && altGetRandom(b) == nil {
		63  		return len(b), nil
		64  	}
		65  	r.mu.Lock()
		66  	defer r.mu.Unlock()
		67  	if r.f == nil {
		68  		f, err := os.Open(r.name)
		69  		if f == nil {
		70  			return 0, err
		71  		}
		72  		if runtime.GOOS == "plan9" {
		73  			r.f = f
		74  		} else {
		75  			r.f = bufio.NewReader(hideAgainReader{f})
		76  		}
		77  	}
		78  	return r.f.Read(b)
		79  }
		80  
		81  var isEAGAIN func(error) bool // set by eagain.go on unix systems
		82  
		83  // hideAgainReader masks EAGAIN reads from /dev/urandom.
		84  // See golang.org/issue/9205
		85  type hideAgainReader struct {
		86  	r io.Reader
		87  }
		88  
		89  func (hr hideAgainReader) Read(p []byte) (n int, err error) {
		90  	n, err = hr.r.Read(p)
		91  	if err != nil && isEAGAIN != nil && isEAGAIN(err) {
		92  		err = nil
		93  	}
		94  	return
		95  }
		96  
		97  // Alternate pseudo-random implementation for use on
		98  // systems without a reliable /dev/urandom.
		99  
	 100  // newReader returns a new pseudorandom generator that
	 101  // seeds itself by reading from entropy. If entropy == nil,
	 102  // the generator seeds itself by reading from the system's
	 103  // random number generator, typically /dev/random.
	 104  // The Read method on the returned reader always returns
	 105  // the full amount asked for, or else it returns an error.
	 106  //
	 107  // The generator uses the X9.31 algorithm with AES-128,
	 108  // reseeding after every 1 MB of generated data.
	 109  func newReader(entropy io.Reader) io.Reader {
	 110  	if entropy == nil {
	 111  		entropy = &devReader{name: "/dev/random"}
	 112  	}
	 113  	return &reader{entropy: entropy}
	 114  }
	 115  
	 116  type reader struct {
	 117  	mu									 sync.Mutex
	 118  	budget							 int // number of bytes that can be generated
	 119  	cipher							 cipher.Block
	 120  	entropy							io.Reader
	 121  	time, seed, dst, key [aes.BlockSize]byte
	 122  }
	 123  
	 124  func (r *reader) Read(b []byte) (n int, err error) {
	 125  	r.mu.Lock()
	 126  	defer r.mu.Unlock()
	 127  	n = len(b)
	 128  
	 129  	for len(b) > 0 {
	 130  		if r.budget == 0 {
	 131  			_, err := io.ReadFull(r.entropy, r.seed[0:])
	 132  			if err != nil {
	 133  				return n - len(b), err
	 134  			}
	 135  			_, err = io.ReadFull(r.entropy, r.key[0:])
	 136  			if err != nil {
	 137  				return n - len(b), err
	 138  			}
	 139  			r.cipher, err = aes.NewCipher(r.key[0:])
	 140  			if err != nil {
	 141  				return n - len(b), err
	 142  			}
	 143  			r.budget = 1 << 20 // reseed after generating 1MB
	 144  		}
	 145  		r.budget -= aes.BlockSize
	 146  
	 147  		// ANSI X9.31 (== X9.17) algorithm, but using AES in place of 3DES.
	 148  		//
	 149  		// single block:
	 150  		// t = encrypt(time)
	 151  		// dst = encrypt(t^seed)
	 152  		// seed = encrypt(t^dst)
	 153  		ns := time.Now().UnixNano()
	 154  		binary.BigEndian.PutUint64(r.time[:], uint64(ns))
	 155  		r.cipher.Encrypt(r.time[0:], r.time[0:])
	 156  		for i := 0; i < aes.BlockSize; i++ {
	 157  			r.dst[i] = r.time[i] ^ r.seed[i]
	 158  		}
	 159  		r.cipher.Encrypt(r.dst[0:], r.dst[0:])
	 160  		for i := 0; i < aes.BlockSize; i++ {
	 161  			r.seed[i] = r.time[i] ^ r.dst[i]
	 162  		}
	 163  		r.cipher.Encrypt(r.seed[0:], r.seed[0:])
	 164  
	 165  		m := copy(b, r.dst[0:])
	 166  		b = b[m:]
	 167  	}
	 168  
	 169  	return n, nil
	 170  }
	 171  

View as plain text