Repository: google/go-tpm
Pull request #341 (2023-08-04 20:24:30)

tpm2: Implement TPM2_Import
This is an attempt from me to try and implement `TPM2_Import`, but I suspect I picked a non-obvious thing to implement.

Useage I have is to take a pre-existing EC key and import it into the TPM. But I suspect there is a bunch of wrapping with the `duplicate` argument I just don't understand. The `legacy/tpm2` implementation seemed to just do things with the `Private` struct, but transferring that to the `tpmdirect` API is very non-obvious.


The outline for the test I have been trying to write for the implementation>

Any help our guidance would be appreicated.

```go
package tpm2test

import (
	"crypto/ecdsa"
	"crypto/elliptic"
	"crypto/rand"
	"crypto/x509"
	"testing"

	. "github.com/google/go-tpm/tpm2"
	"github.com/google/go-tpm/tpm2/transport/simulator"
)

func TestImport(t *testing.T) {
	thetpm, err := simulator.OpenSimulator()
	if err != nil {
		t.Fatalf("could not connect to TPM simulator: %v", err)
	}
	defer thetpm.Close()

	srkCreate := CreatePrimary{
		PrimaryHandle: TPMRHOwner,
		InPublic:      New2B(ECCSRKTemplate),
	}

	srkCreateRsp, err := srkCreate.Execute(thetpm)
	if err != nil {
		t.Fatalf("could not generate SRK: %v", err)
	}
	defer func() {
		flush := FlushContext{
			FlushHandle: srkCreateRsp.ObjectHandle,
		}
		_, err := flush.Execute(thetpm)
		if err != nil {
			t.Fatalf("could not flush SRK: %v", err)
		}
	}()

	pk, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	if err != nil {
		t.Fatalf("something")
	}
	b, err := x509.MarshalECPrivateKey(pk)
	if err != nil {
		t.Fatalf("failed DER encoding")
	}

	tpmdata := TPM2BPrivate{
		Buffer: b,
	}
	m := Marshal(tpmdata)

	_, err = Import{
		ParentHandle: &AuthHandle{
			Handle: srkCreateRsp.ObjectHandle,
			Name:   srkCreateRsp.Name,
			Auth:   PasswordAuth(nil),
		},
		Duplicate: TPM2BPrivate{Buffer: m},
		ObjectPublic: New2B(TPMTPublic{
			Type:    TPMAlgECC,
			NameAlg: TPMAlgSHA256,
			ObjectAttributes: TPMAObject{
				SignEncrypt:         true,
				SensitiveDataOrigin: true,
			},
			Parameters: NewTPMUPublicParms(
				TPMAlgECC,
				&TPMSECCParms{
					CurveID: TPMECCNistP256,
					Scheme: TPMTECCScheme{
						Scheme: TPMAlgECDSA,
						Details: NewTPMUAsymScheme(
							TPMAlgECDSA,
							&TPMSSigSchemeECDSA{
								HashAlg: TPMAlgSHA256,
							},
						),
					},
				},
			),
		}),
	}.Execute(thetpm)
	if err != nil {
		t.Fatalf("could not import: %v", err)
	}
}
```

chrisfenner: ```go
pk, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	if err != nil {
		t.Fatalf("something")
	}
	b, err := x509.MarshalECPrivateKey(pk)
	if err != nil {
		t.Fatalf("failed DER encoding")
	}

	tpmdata := TPM2BPrivate{
		Buffer: b,
	}
	m := Marshal(tpmdata)
```

This might cause a problem, because TPMs don't deal in DER-encoded data. Instead, you probably want to create a [`TPMT_SENSITIVE`](https://trustedcomputinggroup.org/wp-content/uploads/TCG_TPM2_r1p59_Part2_Structures_pub.pdf#page=162) and then encrypt it (using the parent's public key) using a similar method to go-tpm-tools. Heck, I'd probably just use go-tpm-tools for the test: let somebody else take up the separate work of dealing with import blobs.
chrisfenner: TPM2_Import might be the hardest possible command to build a test for. So once you've cracked this, you should feel prepared to deal with anything. 😎
Foxboron: > This might cause a problem, because TPMs don't deal in DER-encoded data. 

I might have been tricked by the `tpm2_tools` implementation as they said it could be DER and I never found a place in the C code where they did anything with the bytes at all and assumed as a result it would be fine.

> TPM2_Import might be the hardest possible command to build a test for. So once you've cracked this, you should feel prepared to deal with anything. sunglasses

I'm glad to see I involuntarily stumbled into the worst of them :upside_down_face: 
Foxboron: Actually, with the links I was able to figure out how to pass the `duplicate` blob unencrypted.

I forgot filling out `Unique` with the public key parts and filling out `TPM2BPrivate{}` in the struct had me take a loop through `Marshal()` which seems a bit awkward.

If the outline for the test looks sane'ish I'll clean up this PR to undraft it.

Thanks for the help :)

```go
package tpm2test

import (
	"crypto/ecdsa"
	"crypto/elliptic"
	"crypto/rand"
	"testing"

	. "github.com/google/go-tpm/tpm2"
	"github.com/google/go-tpm/tpm2/transport/simulator"
)

func TestImport(t *testing.T) {
	thetpm, err := simulator.OpenSimulator()
	if err != nil {
		t.Fatalf("could not connect to TPM simulator: %v", err)
	}
	defer thetpm.Close()

	srkCreate := CreatePrimary{
		PrimaryHandle: TPMRHOwner,
		InPublic:      New2B(ECCSRKTemplate),
	}

	srkCreateRsp, err := srkCreate.Execute(thetpm)
	if err != nil {
		t.Fatalf("could not generate SRK: %v", err)
	}
	defer func() {
		flush := FlushContext{
			FlushHandle: srkCreateRsp.ObjectHandle,
		}
		_, err := flush.Execute(thetpm)
		if err != nil {
			t.Fatalf("could not flush SRK: %v", err)
		}
	}()

	pk, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	if err != nil {
		t.Fatalf("something")
	}

	sens2B := New2B(TPMTSensitive{
		SensitiveType: TPMAlgECC,
		Sensitive: NewTPMUSensitiveComposite(
			TPMAlgECC,
			&TPM2BECCParameter{Buffer: pk.D.FillBytes(make([]byte, 32))},
		),
	})

	l := Marshal(TPM2BPrivate{Buffer: sens2B.Bytes()})

	_, err = Import{
		ParentHandle: &AuthHandle{
			Handle: srkCreateRsp.ObjectHandle,
			Name:   srkCreateRsp.Name,
			Auth:   PasswordAuth(nil),
		},
		Duplicate: TPM2BPrivate{Buffer: l},
		ObjectPublic: New2B(TPMTPublic{
			Type:    TPMAlgECC,
			NameAlg: TPMAlgSHA256,
			ObjectAttributes: TPMAObject{
				SignEncrypt:          true,
				SensitiveDataOrigin:  false,
				EncryptedDuplication: false,
			},
			Parameters: NewTPMUPublicParms(
				TPMAlgECC,
				&TPMSECCParms{
					CurveID: TPMECCNistP256,
					Scheme: TPMTECCScheme{
						Scheme: TPMAlgECDSA,
						Details: NewTPMUAsymScheme(
							TPMAlgECDSA,
							&TPMSSigSchemeECDSA{
								HashAlg: TPMAlgSHA256,
							},
						),
					},
				},
			),
			Unique: NewTPMUPublicID(
				TPMAlgECC,
				&TPMSECCPoint{
					X: TPM2BECCParameter{
						Buffer: pk.X.FillBytes(make([]byte, 32)),
					},
					Y: TPM2BECCParameter{
						Buffer: pk.Y.FillBytes(make([]byte, 32)),
					},
				},
			),
		}),
	}.Execute(thetpm)
	if err != nil {
		t.Fatalf("could not import: %v", err)
	}
}
```
chrisfenner: Feel free to test only based on unencrypted import; I have a hard time seeing a bug you could introduce here that would succeed for unencrypted import but fail for encrypted.
chrisfenner: If your current plan for testing looks like the draft above (minus the DERification), seems totally reasonable!
Foxboron: I've implemented  a feature using this into `ssh-tpm-agent` with a integration test suite, and it seems to work :)

https://github.com/Foxboron/ssh-tpm-agent/pull/16

Patch:
diff --git a/tpm2/tpm2.go b/tpm2/tpm2.go
index c4e2baa..88be3e5 100644
--- a/tpm2/tpm2.go
+++ b/tpm2/tpm2.go
@@ -1493,6 +1493,48 @@ func (cmd EvictControl) Execute(t transport.TPM, s ...Session) (*EvictControlRes
 	return &rsp, nil
 }
 
+// Import is the input to TPM2_Import.
+// See definition in Part 3, Commands, section 13.3
+type Import struct {
+	// handle of parent for new object
+	ParentHandle handle `gotpm:"handle,auth"`
+
+	// The optional symmetric encryption key used as the inner wrapper for duplicate
+	// If SymmetricAlg is TPM_ALG_NULL, then this parametert shall be the Empty Buffer
+	EncryptionKey TPM2BData
+
+	// The public area of the object to be imported
+	ObjectPublic TPM2BPublic
+
+	// The symmetrically encrypted duplicate object that may contain an inner
+	// symmetric wrapper
+	Duplicate TPM2BPrivate
+
+	// The seed for the symmetric key and HMAC key
+	InSymSeed TPM2BEncryptedSecret
+
+	// Definition of the symmetric algorithm to use for the inner wrapper
+	Symmetric TPMTSymDef
+}
+
+// ImportResponse is the response from TPM2_Import.
+type ImportResponse struct {
+	// the private portion of the object
+	OutPrivate TPM2BPrivate
+}
+
+// Command implements the Command interface.
+func (Import) Command() TPMCC { return TPMCCImport }
+
+// Execute executes the command and returns the response.
+func (cmd Import) Execute(t transport.TPM, s ...Session) (*ImportResponse, error) {
+	var rsp ImportResponse
+	if err := execute[ImportResponse](t, cmd, &rsp, s...); err != nil {
+		return nil, err
+	}
+	return &rsp, nil
+}
+
 // GetCapability is the input to TPM2_GetCapability.
 // See definition in Part 3, Commands, section 30.2
 type GetCapability struct {


Test patch:
diff --git a/tpm2/test/import_test.go b/tpm2/test/import_test.go
new file mode 100644
index 0000000..fceb563
--- /dev/null
+++ b/tpm2/test/import_test.go
@@ -0,0 +1,100 @@
+package tpm2test
+
+import (
+	"crypto/ecdsa"
+	"crypto/elliptic"
+	"crypto/rand"
+	"testing"
+
+	. "github.com/google/go-tpm/tpm2"
+	"github.com/google/go-tpm/tpm2/transport/simulator"
+)
+
+func TestImport(t *testing.T) {
+	thetpm, err := simulator.OpenSimulator()
+	if err != nil {
+		t.Fatalf("could not connect to TPM simulator: %v", err)
+	}
+	defer thetpm.Close()
+
+	srkCreate := CreatePrimary{
+		PrimaryHandle: TPMRHOwner,
+		InPublic:      New2B(ECCSRKTemplate),
+	}
+
+	srkCreateRsp, err := srkCreate.Execute(thetpm)
+	if err != nil {
+		t.Fatalf("could not generate SRK: %v", err)
+	}
+	defer func() {
+		flush := FlushContext{
+			FlushHandle: srkCreateRsp.ObjectHandle,
+		}
+		_, err := flush.Execute(thetpm)
+		if err != nil {
+			t.Fatalf("could not flush SRK: %v", err)
+		}
+	}()
+
+	pk, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
+	if err != nil {
+		t.Fatalf("failed to generate ecdsa key: %v", err)
+	}
+
+	sens2B := Marshal(TPMTSensitive{
+		SensitiveType: TPMAlgECC,
+		Sensitive: NewTPMUSensitiveComposite(
+			TPMAlgECC,
+			&TPM2BECCParameter{Buffer: pk.D.FillBytes(make([]byte, 32))},
+		),
+	})
+
+	l := Marshal(TPM2BPrivate{Buffer: sens2B})
+
+	_, err = Import{
+		ParentHandle: &AuthHandle{
+			Handle: srkCreateRsp.ObjectHandle,
+			Name:   srkCreateRsp.Name,
+			Auth:   PasswordAuth(nil),
+		},
+		Duplicate: TPM2BPrivate{Buffer: l},
+		ObjectPublic: New2B(TPMTPublic{
+			Type:    TPMAlgECC,
+			NameAlg: TPMAlgSHA256,
+			ObjectAttributes: TPMAObject{
+				SignEncrypt:          true,
+				SensitiveDataOrigin:  false,
+				EncryptedDuplication: false,
+			},
+			Parameters: NewTPMUPublicParms(
+				TPMAlgECC,
+				&TPMSECCParms{
+					CurveID: TPMECCNistP256,
+					Scheme: TPMTECCScheme{
+						Scheme: TPMAlgECDSA,
+						Details: NewTPMUAsymScheme(
+							TPMAlgECDSA,
+							&TPMSSigSchemeECDSA{
+								HashAlg: TPMAlgSHA256,
+							},
+						),
+					},
+				},
+			),
+			Unique: NewTPMUPublicID(
+				TPMAlgECC,
+				&TPMSECCPoint{
+					X: TPM2BECCParameter{
+						Buffer: pk.X.FillBytes(make([]byte, 32)),
+					},
+					Y: TPM2BECCParameter{
+						Buffer: pk.Y.FillBytes(make([]byte, 32)),
+					},
+				},
+			),
+		}),
+	}.Execute(thetpm)
+	if err != nil {
+		t.Fatalf("could not import: %v", err)
+	}
+}