Debian Codegraph @

legacy/tpm2/open_other.go

raw
1 //go:build !windows
2
3 // Copyright (c) 2019, Google LLC All rights reserved.
4 //
5 // Licensed under the Apache License, Version 2.0 (the "License");
6 // you may not use this file except in compliance with the License.
7 // You may obtain a copy of the License at
8 //
9 // http://www.apache.org/licenses/LICENSE-2.0
10 //
11 // Unless required by applicable law or agreed to in writing, software
12 // distributed under the License is distributed on an "AS IS" BASIS,
13 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 // See the License for the specific language governing permissions and
15 // limitations under the License.
16
17 package tpm2
18
19 import (
20 "errors"
21 "fmt"
22 "io"
23 "os"
24
25 "github.com/google/go-tpm/tpmutil"
26 )
27
28 // OpenTPM opens a channel to the TPM at the given path. If the file is a
29 // device, then it treats it like a normal TPM device, and if the file is a
30 // Unix domain socket, then it opens a connection to the socket.
31 //
32 // This function may also be invoked with no paths, as tpm2.OpenTPM(). In this
33 // case, the default paths on Linux (/dev/tpmrm0 then /dev/tpm0), will be used.
34 func OpenTPM(path ...string) (tpm io.ReadWriteCloser, err error) {
35 switch len(path) {
36 case 0:
37 tpm, err = tpmutil.OpenTPM("/dev/tpmrm0")
38 if errors.Is(err, os.ErrNotExist) {
39 tpm, err = tpmutil.OpenTPM("/dev/tpm0")
40 }
41 case 1:
42 tpm, err = tpmutil.OpenTPM(path[0])
43 default:
44 return nil, errors.New("cannot specify multiple paths to tpm2.OpenTPM")
45 }
46 if err != nil {
47 return nil, err
48 }
49
50 // Make sure this is a TPM 2.0
51 _, err = GetManufacturer(tpm)
52 if err != nil {
53 tpm.Close()
54 return nil, fmt.Errorf("open %s: device is not a TPM 2.0", path)
55 }
56 return tpm, nil
57 }