| 1 |
// Package testhelper provides some helper code for TPM transport tests. |
| 2 |
package testhelper |
| 3 |
|
| 4 |
import ( |
| 5 |
"bytes" |
| 6 |
"encoding/binary" |
| 7 |
"errors" |
| 8 |
"testing" |
| 9 |
|
| 10 |
"github.com/google/go-tpm/tpm2" |
| 11 |
"github.com/google/go-tpm/tpm2/transport" |
| 12 |
) |
| 13 |
|
| 14 |
// RunTest checks that the connection to the given TPM seems to be working. |
| 15 |
func RunTest(t *testing.T, skipErrs []error, tpmOpener func() (transport.TPMCloser, error)) { |
| 16 |
tpm, err := tpmOpener() |
| 17 |
for _, skipErr := range skipErrs { |
| 18 |
if errors.Is(err, skipErr) { |
| 19 |
t.Skipf("%v", err) |
| 20 |
} |
| 21 |
} |
| 22 |
if err != nil { |
| 23 |
t.Fatalf("Failed to open TPM: %v", err) |
| 24 |
} |
| 25 |
defer func(tpm transport.TPMCloser) { |
| 26 |
if err := tpm.Close(); err != nil { |
| 27 |
t.Fatalf("tpm.Close() = %v", err) |
| 28 |
} |
| 29 |
}(tpm) |
| 30 |
|
| 31 |
// Ping the TPM to ask it what the manufacturer is, as a basic consistency check. |
| 32 |
cap, err := tpm2.GetCapability{ |
| 33 |
Capability: tpm2.TPMCapTPMProperties, |
| 34 |
Property: uint32(tpm2.TPMPTManufacturer), |
| 35 |
PropertyCount: 1, |
| 36 |
}.Execute(tpm) |
| 37 |
|
| 38 |
// We might run into one of the known "skip if this error" cases. |
| 39 |
for _, skipErr := range skipErrs { |
| 40 |
if errors.Is(err, skipErr) { |
| 41 |
t.Skipf("%v", err) |
| 42 |
} |
| 43 |
} |
| 44 |
if err != nil { |
| 45 |
t.Fatalf("GetCapability() = %v", err) |
| 46 |
} |
| 47 |
props, err := cap.CapabilityData.Data.TPMProperties() |
| 48 |
if err != nil { |
| 49 |
t.Fatalf("cap.TPMProperties() = %v", err) |
| 50 |
} |
| 51 |
if len(props.TPMProperty) != 1 { |
| 52 |
t.Fatalf("GetCapability() = %v properties, want 1", len(props.TPMProperty)) |
| 53 |
} |
| 54 |
|
| 55 |
var idBuf bytes.Buffer |
| 56 |
idBuf.Grow(4) |
| 57 |
binary.Write(&idBuf, binary.BigEndian, props.TPMProperty[0].Value) |
| 58 |
t.Logf("Manufacturer ID: %q", idBuf.String()) |
| 59 |
} |