Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions tpm2/policy.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,15 @@ func NewPolicyCalculator(alg TPMIAlgHash) (*PolicyCalculator, error) {
}, nil
}

// Clone copies the internal state of the policy to a new calculator
func (p *PolicyCalculator) Clone() *PolicyCalculator {
return &PolicyCalculator{
alg: p.alg,
hash: p.hash,
state: bytes.Clone(p.state),
}
}

// Reset resets the internal state of the policy hash to all 0x00.
func (p *PolicyCalculator) Reset() {
p.state = make([]byte, p.hash.Size())
Expand Down
62 changes: 62 additions & 0 deletions tpm2/test/policy_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"bytes"
"crypto/sha1"
"crypto/sha256"
"encoding/hex"
"testing"

. "github.com/google/go-tpm/tpm2"
Expand Down Expand Up @@ -1125,3 +1126,64 @@ func TestPolicyDuplicationSelectUpdate(t *testing.T) {
})
}
}

func mustHexToBytes(t *testing.T, s string) []byte {
t.Helper()
bytes, err := hex.DecodeString(s)
if err != nil {
t.Fatal("failed decoding hex string to bytes")
}
return bytes
}

func TestPolicyCalculatorClone(t *testing.T) {
pol, err := NewPolicyCalculator(TPMAlgSHA256)
if err != nil {
t.Fatalf("creating policy calculator: %v", err)
}

err = PolicyPCR{
Pcrs: TPMLPCRSelection{
PCRSelections: []TPMSPCRSelection{
{
Hash: TPMAlgSHA256,
PCRSelect: PCClientCompatible.PCRs(1),
},
},
},
}.Update(pol)
if err != nil {
t.Fatal(err)
}

if !bytes.Equal(pol.Hash().Digest, mustHexToBytes(t, "9541398bf83ab69f0df3a54ed4dd51ce04a0497196696a32bb93da77a4545aa7")) {
t.Fatalf("PolicyCalculator does not match expected hash digest, got: %x", pol.Hash().Digest)
}

// Clone the new policy and copy the state
newPol := pol.Clone()

err = PolicyPCR{
Pcrs: TPMLPCRSelection{
PCRSelections: []TPMSPCRSelection{
{
Hash: TPMAlgSHA256,
PCRSelect: PCClientCompatible.PCRs(2),
},
},
},
}.Update(newPol)
if err != nil {
t.Fatal(err)
}

// Check that the old PolicyCalculator is unchange
if !bytes.Equal(pol.Hash().Digest, mustHexToBytes(t, "9541398bf83ab69f0df3a54ed4dd51ce04a0497196696a32bb93da77a4545aa7")) {
t.Fatalf("PolicyCalculator does not match expected hash digest, got: %x", pol.Hash().Digest)
}

// Check that the new instance has the updated checksum
if !bytes.Equal(newPol.Hash().Digest, mustHexToBytes(t, "20f15aec09d69e75070296a5a1b613502678a9f0e1c5615736414e99073807b0")) {
t.Fatalf("PolicyCalculator does not match expected hash digest, got: %x", newPol.Hash().Digest)
}
}