github.com/insolar/x-crypto@v0.0.0-20191031140942-75fab8a325f6/rand/rand_unix.go (about)

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