rand_fill.mx raw

   1  // Regression: random bytes must actually land in the buffer the caller passed.
   2  //
   3  // There is no expected value for a random byte, which is exactly why this went
   4  // unnoticed: three windows on the way from the kernel to the caller (sysrand's
   5  // getrandom and urandom paths, the wasm bridge, and the DRBG's Generate call)
   6  // filled a COPY of the destination under the slice rule, so every read returned
   7  // zeros - silently, with no error, no panic and no short count. RSA key
   8  // generation was the first thing to notice: its Miller-Rabin bases were zero,
   9  // every base was rejected as out-of-range, and the prime search never
  10  // terminated (19 minutes, then "arena: region table full").
  11  //
  12  // The assertions are "not all zero" and "two reads differ", which is all a test
  13  // without a reference output can say. The DRBG read crosses its 64 KiB request
  14  // boundary so the chunking loop is exercised, not just the first call.
  15  package main
  16  
  17  import (
  18  	"bytes"
  19  	"crypto/internal/fips140/drbg"
  20  	"crypto/rand"
  21  	"os"
  22  )
  23  
  24  func allZero(b []byte) (z bool) {
  25  	z = true
  26  	for i := 0; i < len(b); i++ {
  27  		if b[i] != 0 {
  28  			return false
  29  		}
  30  	}
  31  	return z
  32  }
  33  
  34  func main() {
  35  	// Termination: a batch program must still be stoppable, so the entry
  36  	// handles the channel the runtime closes on SIGINT/SIGTERM.
  37  	select {
  38  	case <-shutdown:
  39  		return
  40  	default:
  41  	}
  42  
  43  	// crypto/rand: the /dev/urandom reader and io.ReadFull.
  44  	a := []byte{:64}
  45  	n, err := rand.Read(a)
  46  	if err != nil || n != 64 {
  47  		os.Exit(1)
  48  	}
  49  	if allZero(a) {
  50  		os.Exit(2) // 64 zero bytes: the read filled something else
  51  	}
  52  	b := []byte{:64}
  53  	if _, err = rand.Read(b); err != nil {
  54  		os.Exit(3)
  55  	}
  56  	if bytes.Equal(a, b) {
  57  		os.Exit(4) // two reads agree: nothing was read
  58  	}
  59  
  60  	// The DRBG directly, under the request size and past it.
  61  	c := []byte{:32}
  62  	drbg.Read(c)
  63  	if allZero(c) {
  64  		os.Exit(5)
  65  	}
  66  	d := []byte{:70000}
  67  	drbg.Read(d)
  68  	if allZero(d) {
  69  		os.Exit(6)
  70  	}
  71  	// The tail of a multi-chunk read must be filled too: a chunking loop that
  72  	// re-slices its destination fills only the first chunk.
  73  	tail := d[65536:]
  74  	if allZero(tail) {
  75  		os.Exit(7)
  76  	}
  77  
  78  	os.Exit(0)
  79  }
  80