feature/tpm: protect all TPM handle operations with a mutex (#17708)

In particular on Windows, the `transport.TPMCloser` we get is not safe
for concurrent use. This is especially noticeable because
`tpm.attestationKey.Clone` uses the same open handle as the original
key. So wrap the operations on ak.tpm with a mutex and make a deep copy
with a new connection in Clone.

Updates #15830
Updates #17662
Updates #17644

Signed-off-by: Andrew Lytvynov <awly@tailscale.com>
This commit is contained in:
Andrew Lytvynov
2025-10-30 10:32:30 -07:00
committed by GitHub
parent b6c6960e40
commit f522b9dbb7
2 changed files with 100 additions and 6 deletions
+66
View File
@@ -10,6 +10,8 @@ import (
"crypto/rand"
"crypto/sha256"
"encoding/json"
"runtime"
"sync"
"testing"
)
@@ -62,6 +64,37 @@ func TestAttestationKeySign(t *testing.T) {
}
}
func TestAttestationKeySignConcurrent(t *testing.T) {
skipWithoutTPM(t)
ak, err := newAttestationKey()
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
if err := ak.Close(); err != nil {
t.Errorf("ak.Close: %v", err)
}
})
data := []byte("secrets")
digest := sha256.Sum256(data)
wg := sync.WaitGroup{}
for range runtime.GOMAXPROCS(-1) {
wg.Go(func() {
// Check signature/validation round trip.
sig, err := ak.Sign(rand.Reader, digest[:], crypto.SHA256)
if err != nil {
t.Fatal(err)
}
if !ecdsa.VerifyASN1(ak.Public().(*ecdsa.PublicKey), digest[:], sig) {
t.Errorf("ecdsa.VerifyASN1 failed")
}
})
}
wg.Wait()
}
func TestAttestationKeyUnmarshal(t *testing.T) {
skipWithoutTPM(t)
ak, err := newAttestationKey()
@@ -96,3 +129,36 @@ func TestAttestationKeyUnmarshal(t *testing.T) {
t.Error("unmarshalled public key is not the same as the original public key")
}
}
func TestAttestationKeyClone(t *testing.T) {
skipWithoutTPM(t)
ak, err := newAttestationKey()
if err != nil {
t.Fatal(err)
}
ak2 := ak.Clone()
if ak2 == nil {
t.Fatal("Clone failed")
}
t.Cleanup(func() {
if err := ak2.Close(); err != nil {
t.Errorf("ak2.Close: %v", err)
}
})
// Close the original key, ak2 should remain open and usable.
if err := ak.Close(); err != nil {
t.Fatal(err)
}
data := []byte("secrets")
digest := sha256.Sum256(data)
// Check signature/validation round trip using cloned key.
sig, err := ak2.Sign(rand.Reader, digest[:], crypto.SHA256)
if err != nil {
t.Fatal(err)
}
if !ecdsa.VerifyASN1(ak2.Public().(*ecdsa.PublicKey), digest[:], sig) {
t.Errorf("ecdsa.VerifyASN1 failed")
}
}