Debian Codegraph @

attest/tpm_linux.go

raw
1 // Copyright 2019 Google Inc.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License"); you may not
4 // use this file except in compliance with the License. You may obtain a copy of
5 // 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, WITHOUT
11 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 // License for the specific language governing permissions and limitations under
13 // the License.
14
15 //go:build linux && !gofuzz
16 // +build linux,!gofuzz
17
18 package attest
19
20 import (
21 "io"
22 "os"
23 "path"
24 "strings"
25
26 "github.com/google/go-tpm/legacy/tpm2"
27 )
28
29 const (
30 tpmRoot = "/sys/class/tpm"
31 )
32
33 // InjectSimulatedTPMForTest returns a fake TPM that interfaces with
34 // the provided simulated TPM. This method should be used for testing
35 // only.
36 func InjectSimulatedTPMForTest(rwc io.ReadWriteCloser) *TPM {
37 return &TPM{tpm: &wrappedTPM20{
38 interf: TPMInterfaceCommandChannel,
39 rwc: &fakeCmdChannel{rwc},
40 }}
41 }
42
43 func probeSystemTPMs() ([]string, error) {
44 var tpms []string
45
46 tpmDevs, err := os.ReadDir(tpmRoot)
47 if err != nil && !os.IsNotExist(err) {
48 return nil, err
49 }
50 if err == nil {
51 for _, tpmDev := range tpmDevs {
52 if strings.HasPrefix(tpmDev.Name(), "tpm") {
53 tpmPath := path.Join(tpmRoot, tpmDev.Name())
54
55 if _, err := os.Stat(path.Join(tpmPath, "caps")); err == nil {
56 continue
57 } else if !os.IsNotExist(err) {
58 return nil, err
59 }
60 tpms = append(tpms, tpmPath)
61 }
62 }
63 }
64
65 return tpms, nil
66 }
67
68 type linuxCmdChannel struct {
69 io.ReadWriteCloser
70 }
71
72 // MeasurementLog implements CommandChannelTPM20.
73 func (cc *linuxCmdChannel) MeasurementLog() ([]byte, error) {
74 return os.ReadFile("/sys/kernel/security/tpm0/binary_bios_measurements")
75 }
76
77 func openTPM(tpmPath string) (*TPM, error) {
78 interf := TPMInterfaceDirect
79 // If the TPM has a kernel-provided resource manager, we should
80 // use that instead of communicating directly.
81 devPath := path.Join("/dev", path.Base(tpmPath))
82 f, err := os.ReadDir(path.Join(tpmPath, "device", "tpmrm"))
83 if err != nil {
84 if !os.IsNotExist(err) {
85 return nil, err
86 }
87 } else if len(f) > 0 {
88 devPath = path.Join("/dev", f[0].Name())
89 interf = TPMInterfaceKernelManaged
90 }
91
92 rwc, err := tpm2.OpenTPM(devPath)
93 if err != nil {
94 return nil, err
95 }
96
97 return &TPM{tpm: &wrappedTPM20{
98 interf: interf,
99 rwc: &linuxCmdChannel{rwc},
100 }}, nil
101 }