Debian Codegraph @

tpm2/transport/windowstpm/windowstpm.go

raw
1 //go:build windows
2
3 // Package windowstpm implements the TPM transport on Windows using tbs.dll.
4 package windowstpm
5
6 import (
7 "errors"
8 "fmt"
9 "io"
10
11 "github.com/google/go-tpm/tpm2/transport"
12 "github.com/google/go-tpm/tpmutil/tbs"
13 )
14
15 var (
16 // ErrNotTPM20 indicates that a TPM 2.0 was not found.
17 ErrNotTPM20 = errors.New("device is not a TPM 2.0")
18 )
19
20 const (
21 maxTPMResponse = 4096
22 )
23
24 // Open opens a channel to the TPM via TBS.
25 func Open() (transport.TPMCloser, error) {
26 info, err := tbs.GetDeviceInfo()
27 if err != nil {
28 return nil, err
29 }
30
31 if info.TPMVersion != tbs.TPMVersion20 {
32 return nil, fmt.Errorf("%w: %v", ErrNotTPM20, info.TPMVersion)
33 }
34
35 tpmContext, err := tbs.CreateContext(tbs.TPMVersion20, tbs.IncludeTPM20)
36 rwc := &winTPMBuffer{
37 context: tpmContext,
38 outBuffer: make([]byte, 0, maxTPMResponse),
39 }
40 return transport.FromReadWriteCloser(rwc), err
41 }
42
43 // winTPMBuffer is a ReadWriteCloser to access the TPM in Windows.
44 type winTPMBuffer struct {
45 context tbs.Context
46 outBuffer []byte
47 }
48
49 // Write implements the io.Writer interface.
50 //
51 // Executes the TPM command specified by commandBuffer (at Normal Priority), returning the number
52 // of bytes in the command and any error code returned by executing the TPM command. Command
53 // response can be read by calling Read().
54 func (rwc *winTPMBuffer) Write(commandBuffer []byte) (int, error) {
55 // TPM spec defines longest possible response to be maxTPMResponse.
56 rwc.outBuffer = rwc.outBuffer[:maxTPMResponse]
57
58 outBufferLen, err := rwc.context.SubmitCommand(
59 tbs.NormalPriority,
60 commandBuffer,
61 rwc.outBuffer,
62 )
63
64 if err != nil {
65 rwc.outBuffer = rwc.outBuffer[:0]
66 return 0, err
67 }
68 // Shrink outBuffer so it is length of response.
69 rwc.outBuffer = rwc.outBuffer[:outBufferLen]
70 return len(commandBuffer), nil
71 }
72
73 // Read implements the io.Reader interface.
74 //
75 // Provides TPM response from the command called in the last Write call.
76 func (rwc *winTPMBuffer) Read(responseBuffer []byte) (int, error) {
77 if len(rwc.outBuffer) == 0 {
78 return 0, io.EOF
79 }
80 lenCopied := copy(responseBuffer, rwc.outBuffer)
81 // Cut out the piece of slice which was just read out, maintaining original slice capacity.
82 rwc.outBuffer = append(rwc.outBuffer[:0], rwc.outBuffer[lenCopied:]...)
83 return lenCopied, nil
84 }
85
86 // Close implements the io.Closer interface.
87 func (rwc *winTPMBuffer) Close() error {
88 return rwc.context.Close()
89 }