| 1 |
package client |
| 2 |
|
| 3 |
import ( |
| 4 |
"fmt" |
| 5 |
|
| 6 |
"github.com/google/go-tpm-tools/internal" |
| 7 |
pb "github.com/google/go-tpm-tools/proto/tpm" |
| 8 |
"github.com/google/go-tpm/legacy/tpm2" |
| 9 |
"github.com/google/go-tpm/tpmutil" |
| 10 |
) |
| 11 |
|
| 12 |
func loadHandle(k *Key, blob *pb.ImportBlob) (tpmutil.Handle, error) { |
| 13 |
auth, err := k.session.Auth() |
| 14 |
if err != nil { |
| 15 |
return tpm2.HandleNull, err |
| 16 |
} |
| 17 |
private, err := tpm2.Import(k.rw, k.Handle(), auth, blob.PublicArea, blob.Duplicate, blob.EncryptedSeed, nil, nil) |
| 18 |
if err != nil { |
| 19 |
return tpm2.HandleNull, fmt.Errorf("import failed: %w", err) |
| 20 |
} |
| 21 |
|
| 22 |
auth, err = k.session.Auth() |
| 23 |
if err != nil { |
| 24 |
return tpm2.HandleNull, err |
| 25 |
} |
| 26 |
handle, _, err := tpm2.LoadUsingAuth(k.rw, k.Handle(), auth, blob.PublicArea, private) |
| 27 |
if err != nil { |
| 28 |
return tpm2.HandleNull, fmt.Errorf("load failed: %w", err) |
| 29 |
} |
| 30 |
return handle, nil |
| 31 |
} |
| 32 |
|
| 33 |
// Import decrypts the secret contained in an encoded import request. |
| 34 |
// The key used must be an encryption key (signing keys cannot be used). |
| 35 |
// The req parameter should come from server.CreateImportBlob. |
| 36 |
func (k *Key) Import(blob *pb.ImportBlob) ([]byte, error) { |
| 37 |
handle, err := loadHandle(k, blob) |
| 38 |
if err != nil { |
| 39 |
return nil, err |
| 40 |
} |
| 41 |
defer tpm2.FlushContext(k.rw, handle) |
| 42 |
|
| 43 |
unsealSession, err := NewPCRSession(k.rw, internal.PCRSelection(blob.Pcrs)) |
| 44 |
if err != nil { |
| 45 |
return nil, err |
| 46 |
} |
| 47 |
defer unsealSession.Close() |
| 48 |
|
| 49 |
auth, err := unsealSession.Auth() |
| 50 |
if err != nil { |
| 51 |
return nil, err |
| 52 |
} |
| 53 |
out, err := tpm2.UnsealWithSession(k.rw, auth.Session, handle, "") |
| 54 |
if err != nil { |
| 55 |
return nil, fmt.Errorf("unseal failed: %w", err) |
| 56 |
} |
| 57 |
return out, nil |
| 58 |
} |
| 59 |
|
| 60 |
// ImportSigningKey returns the signing key contained in an encoded import request. |
| 61 |
// The parent key must be an encryption key (signing keys cannot be used). |
| 62 |
// The req parameter should come from server.CreateSigningKeyImportBlob. |
| 63 |
func (k *Key) ImportSigningKey(blob *pb.ImportBlob) (key *Key, err error) { |
| 64 |
handle, err := loadHandle(k, blob) |
| 65 |
if err != nil { |
| 66 |
return nil, err |
| 67 |
} |
| 68 |
key = &Key{rw: k.rw, handle: handle} |
| 69 |
|
| 70 |
defer func() { |
| 71 |
if err != nil { |
| 72 |
key.Close() |
| 73 |
} |
| 74 |
}() |
| 75 |
|
| 76 |
if key.pubArea, _, _, err = tpm2.ReadPublic(k.rw, handle); err != nil { |
| 77 |
return |
| 78 |
} |
| 79 |
if key.session, err = NewPCRSession(k.rw, internal.PCRSelection(blob.Pcrs)); err != nil { |
| 80 |
return |
| 81 |
} |
| 82 |
return key, key.finish() |
| 83 |
} |