Debian Codegraph @

tpmutil/run_windows.go

raw
1 // Copyright (c) 2018, Google LLC All rights reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 package tpmutil
16
17 import (
18 "io"
19
20 "github.com/google/go-tpm/tpmutil/tbs"
21 )
22
23 // winTPMBuffer is a ReadWriteCloser to access the TPM in Windows.
24 type winTPMBuffer struct {
25 context tbs.Context
26 outBuffer []byte
27 }
28
29 // Executes the TPM command specified by commandBuffer (at Normal Priority), returning the number
30 // of bytes in the command and any error code returned by executing the TPM command. Command
31 // response can be read by calling Read().
32 func (rwc *winTPMBuffer) Write(commandBuffer []byte) (int, error) {
33 // TPM spec defines longest possible response to be maxTPMResponse.
34 rwc.outBuffer = rwc.outBuffer[:maxTPMResponse]
35
36 outBufferLen, err := rwc.context.SubmitCommand(
37 tbs.NormalPriority,
38 commandBuffer,
39 rwc.outBuffer,
40 )
41
42 if err != nil {
43 rwc.outBuffer = rwc.outBuffer[:0]
44 return 0, err
45 }
46 // Shrink outBuffer so it is length of response.
47 rwc.outBuffer = rwc.outBuffer[:outBufferLen]
48 return len(commandBuffer), nil
49 }
50
51 // Provides TPM response from the command called in the last Write call.
52 func (rwc *winTPMBuffer) Read(responseBuffer []byte) (int, error) {
53 if len(rwc.outBuffer) == 0 {
54 return 0, io.EOF
55 }
56 lenCopied := copy(responseBuffer, rwc.outBuffer)
57 // Cut out the piece of slice which was just read out, maintaining original slice capacity.
58 rwc.outBuffer = append(rwc.outBuffer[:0], rwc.outBuffer[lenCopied:]...)
59 return lenCopied, nil
60 }
61
62 func (rwc *winTPMBuffer) Close() error {
63 return rwc.context.Close()
64 }
65
66 // OpenTPM creates a new instance of a ReadWriteCloser which can interact with a
67 // Windows TPM.
68 func OpenTPM() (io.ReadWriteCloser, error) {
69 tpmContext, err := tbs.CreateContext(tbs.TPMVersion20, tbs.IncludeTPM12|tbs.IncludeTPM20)
70 rwc := &winTPMBuffer{
71 context: tpmContext,
72 outBuffer: make([]byte, 0, maxTPMResponse),
73 }
74 return rwc, err
75 }
76
77 // FromContext creates a new instance of a ReadWriteCloser which can
78 // interact with a Windows TPM, using the specified TBS handle.
79 func FromContext(ctx tbs.Context) io.ReadWriteCloser {
80 return &winTPMBuffer{
81 context: ctx,
82 outBuffer: make([]byte, 0, maxTPMResponse),
83 }
84 }