Permalink
Browse files

Add TPM2 random number generator support

This should work on any platform with a tpm2 device or vtpm.

Signed-off-by: Justin Cormack <justin@specialbusservice.com>
  • Loading branch information...
justincormack committed Sep 4, 2018
1 parent c8449ba commit 8cf88e42caab21abf4abaabbe6670f43535c1f67
@@ -6,3 +6,5 @@ config:
readonly: true
net: new
ipc: new
binds:
- /dev:/dev
@@ -23,8 +23,9 @@ func main() {
timeout = 0
}

tpm, err := initTPM()
supported := initRand()
if !supported {
if !supported && err != nil {
log.Fatalf("No random source available")
}

@@ -53,12 +54,28 @@ func main() {
count := 0

for {
// write some entropy
n, err := writeEntropy(random)
if err != nil {
log.Fatalf("write entropy: %v", err)
if supported {
r, err := rand()
if err != nil {
// assume can fail occasionally
n, err := writeEntropy(random, r)
if err != nil {
log.Fatalf("write entropy: %v", err)
}
count += n
}
}
if tpm != nil {
r, err := tpmRand(tpm)
if err != nil {
// assume can fail occasionally
n, err := writeEntropy(random, r)
if err != nil {
log.Fatalf("write entropy: %v", err)
}
count += n
}
}
count += n
// sleep until we can write more
nevents, err := unix.EpollWait(epfd, events[:], timeout)
if err != nil {
@@ -80,12 +97,7 @@ type randInfo struct {
buf uint64
}

func writeEntropy(random *os.File) (int, error) {
r, err := rand()
if err != nil {
// assume can fail occasionally
return 0, nil
}
func writeEntropy(random *os.File, r uint64) (int, error) {
const entropy = 64 // they are good random numbers, Brent
info := randInfo{entropy, 8, r}
ret, _, err := unix.Syscall(unix.SYS_IOCTL, uintptr(random.Fd()), uintptr(C.rndaddentropy), uintptr(unsafe.Pointer(&info)))
@@ -0,0 +1,28 @@
package main

import (
"encoding/binary"
"errors"
"io"

"github.com/google/go-tpm/tpm2"
"github.com/google/go-tpm/tpmutil"
)

const device = "/dev/tpm0"

func initTPM() (io.ReadWriteCloser, error) {
return tpmutil.OpenTPM(device)
}

func tpmRand(tpm io.ReadWriteCloser) (uint64, error) {
data, err := tpm2.GetRandom(tpm, 8)
if err != nil {
return 0, err
}
ui, len := binary.Uvarint(data)
if len <= 0 {
return 0, errors.New("bad data")
}
return ui, nil
}
@@ -1 +1,2 @@
github.com/google/go-tpm cf513cbc2b1463408c269cd80616839c163ca376
golang.org/x/sys e312636bdaa2fac4f0acde9d17ab9fbad2b4ad10

Some generated files are not rendered by default. Learn more.

Oops, something went wrong.

Some generated files are not rendered by default. Learn more.

Oops, something went wrong.

Some generated files are not rendered by default. Learn more.

Oops, something went wrong.
Oops, something went wrong.

0 comments on commit 8cf88e4

Please sign in to comment.