Black Lives Matter. Support the Equal Justice Initiative.

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

View as plain text