File: simulator_enabled.go

package info (click to toggle)
golang-github-smallstep-crypto 0.57.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 3,284 kB
  • sloc: sh: 53; makefile: 36
file content (99 lines) | stat: -rw-r--r-- 1,985 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
//go:build tpmsimulator
// +build tpmsimulator

package simulator

import (
	"bytes"
	"encoding/binary"
	"encoding/hex"
	"fmt"
	"io"

	gotpm "github.com/google/go-tpm-tools/simulator"
)

type WrappingSimulator struct {
	wrapped *gotpm.Simulator
	seed    *int64
}

type NewSimulatorOption func(ws *WrappingSimulator) error

func WithSeed(seed string) NewSimulatorOption {
	return func(ws *WrappingSimulator) error {
		b, err := hex.DecodeString(seed)
		if err != nil {
			return fmt.Errorf("failed decoding %q: %w", seed, err)
		}
		if len(b) != 8 {
			return fmt.Errorf("%q has wrong number of bytes (%d)", seed, len(b))
		}
		var intSeed int64
		buf := bytes.NewBuffer(b)
		if err := binary.Read(buf, binary.BigEndian, &intSeed); err != nil {
			return fmt.Errorf("failed reading %q into int64: %w", seed, err)
		}
		ws.seed = &intSeed
		return nil
	}
}

func New(opts ...NewSimulatorOption) (Simulator, error) {
	ws := &WrappingSimulator{}
	for _, applyTo := range opts {
		if err := applyTo(ws); err != nil {
			return nil, fmt.Errorf("failed initializing TPM simulator: %w", err)
		}
	}
	return ws, nil
}

func (s *WrappingSimulator) Open() error {
	var sim *gotpm.Simulator
	var err error
	if s.wrapped == nil {
		if s.seed == nil {
			sim, err = gotpm.Get()
		} else {
			sim, err = gotpm.GetWithFixedSeedInsecure(*s.seed)
		}
		if err != nil {
			return err
		}
	}
	s.wrapped = sim
	return nil
}

func (s *WrappingSimulator) Close() error {
	if s.wrapped == nil {
		return nil
	}

	if s.wrapped.IsClosed() {
		return nil
	}

	if err := s.wrapped.Close(); err != nil {
		return fmt.Errorf("failed closing TPM simulator: %w", err)
	}

	s.wrapped = nil

	return nil
}

func (s *WrappingSimulator) MeasurementLog() ([]byte, error) {
	return nil, nil
}

func (s *WrappingSimulator) Read(p []byte) (int, error) {
	return s.wrapped.Read(p)
}

func (s *WrappingSimulator) Write(p []byte) (int, error) {
	return s.wrapped.Write(p)
}

var _ io.ReadWriteCloser = (*WrappingSimulator)(nil)