tpm2

package module
v1.7.7 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 14, 2024 License: LGPL-3.0 Imports: 24 Imported by: 47

README

go-tpm2

Tests GoDoc

This repository contains a go library for interacting with TPM 2.0 devices. Some currently supported features are:

  • All authorization modes: cleartext password, HMAC session based and policy session based.
  • All session configurations: salted or unsalted + bound or unbound.
  • Session-based command and response parameter encryption using AES-CFB or XOR obfuscation.
  • Session-based command auditing.
  • Backends for Linux TPM character devices and TPM simulators implementing the Microsoft TPM 2.0 simulator interface.

The current support status for each command group is detailed below.

Command group Support Comment
Start-up Full
Testing Full
Session Commands Full
Object Commands Full
Duplication Commands Partial TPM2_Duplicate and TPM2_Import are supported
Asymmetric Primitives None
Symmetric Primitives None
Random Number Generator Full
Hash/HMAC/Event Sequences Full
Attestation Commands Full
Ephemeral EC Keys None
Signing and Signature Verification Full
Command Audit Full
Integrity Collection (PCR) Partial TPM2_PCR_Extend, TPM2_PCR_Event, TPM2_PCR_Read and TPM2_PCR_Reset are supported
Enhanced Authorization (EA) Commands Partial All commands are supported except for TPM2_PolicyLocality, TPM2_PolicyPhysicalPresence, TPM2_PolicyTemplate and TPM2_PolicyAuthorizeNV
Hierarchy Commands Partial TPM2_CreatePrimary, TPM2_HierarchyControl, TPM2_Clear, TPM2_ClearControl and TPM2_HierarchyChangeAuth are supported
Dictionary Attack Functions Full
Miscellaneous Management Functions None
Field Upgrade None
Context Management Full
Clocks and Timers Partial TPM2_ReadClock is supported
Capability Commands Full
Non-Volatile Storage Partial All commands are supported except for TPM2_NV_Certify
Vendor Specific None

Documentation

Overview

Package tpm2 implements an API for communicating with TPM 2.0 devices.

This documentation refers to TPM commands and types that are described in more detail in the TPM 2.0 Library Specification. Knowledge of this specification is assumed in this documentation.

Communication with Linux TPM character devices and TPM simulators implementing the Microsoft TPM2 simulator interface is supported.

The core type by which consumers of this package communicate with a TPM is TPMContext.

Example (SealingASecret)
package main

import (
	"fmt"
	"os"

	"github.com/canonical/go-tpm2"
	"github.com/canonical/go-tpm2/linux"
	"github.com/canonical/go-tpm2/mu"
	"github.com/canonical/go-tpm2/objectutil"
	"github.com/canonical/go-tpm2/util"
)

// srkHandle defines the handle for the SRK
const srkHandle = 0x81000001

// seal protects the supplied secret in the storage hierarchy of the TPM using
// a simple authorization policy that is gated on the current values of the PCRs
// included in the specified selection. The sealed object and metadata are
// serialized and returned in a form that can be passed to the unseal function.
func seal(secret []byte, pcrSelection tpm2.PCRSelectionList) ([]byte, error) {
	device, err := linux.DefaultTPM2Device()
	if err != nil {
		return nil, err
	}
	tpm, err := tpm2.OpenTPMDevice(device)
	if err != nil {
		return nil, err
	}
	defer tpm.Close()

	// Use the shared SRK as the storage object, and assume that it already exists.
	srk, err := tpm.NewResourceContext(srkHandle)
	if err != nil {
		return nil, err
	}

	// Build the sealed object template
	template := objectutil.NewSealedObjectTemplate(
		objectutil.WithUserAuthMode(objectutil.RequirePolicy))

	// Compute a simple PCR policy using the TPM's current values
	_, values, err := tpm.PCRRead(pcrSelection)
	if err != nil {
		return nil, err
	}

	digest, err := util.ComputePCRDigest(tpm2.HashAlgorithmSHA256, pcrSelection, values)
	if err != nil {
		return nil, err
	}

	trial := util.ComputeAuthPolicy(tpm2.HashAlgorithmSHA256)
	trial.PolicyPCR(digest, pcrSelection)

	template.AuthPolicy = trial.GetDigest()

	sensitive := &tpm2.SensitiveCreate{Data: secret}

	// Create the sealed object
	priv, pub, _, _, _, err := tpm.Create(srk, sensitive, template, nil, nil, nil)
	if err != nil {
		return nil, err
	}

	// Encode and return the sealed object
	return mu.MarshalToBytes(priv, pub, pcrSelection)
}

// unseal attempts to recover a secret from the supplied blob previously created by the seal
// function.
func unseal(data []byte) ([]byte, error) {
	// Decode the sealed object
	var priv tpm2.Private
	var pub *tpm2.Public
	var pcrSelection tpm2.PCRSelectionList
	if _, err := mu.UnmarshalFromBytes(data, &priv, &pub, &pcrSelection); err != nil {
		return nil, err
	}

	device, err := linux.DefaultTPM2Device()
	if err != nil {
		return nil, err
	}
	tpm, err := tpm2.OpenTPMDevice(device)
	if err != nil {
		return nil, err
	}
	defer tpm.Close()

	srk, err := tpm.NewResourceContext(srkHandle)
	if err != nil {
		return nil, err
	}

	// Load the sealed object into the TPM
	object, err := tpm.Load(srk, priv, pub, nil)
	if err != nil {
		return nil, err
	}
	defer tpm.FlushContext(object)

	// Run a policy session with the PCR assertion
	session, err := tpm.StartAuthSession(nil, nil, tpm2.SessionTypePolicy, nil, tpm2.HashAlgorithmSHA256)
	if err != nil {
		return nil, err
	}
	defer tpm.FlushContext(session)

	if err := tpm.PolicyPCR(session, nil, pcrSelection); err != nil {
		return nil, err
	}

	return tpm.Unseal(object, session)
}

func main() {
	// Seal a secret to the storage hierarchy of the TPM using an authorization policy
	// that is gated on the current value of PCR7.
	//
	// Don't assume that this is a secure way to protect a key - it's just an example!

	secret := []byte("secret data")
	pcrSelection := tpm2.PCRSelectionList{{Hash: tpm2.HashAlgorithmSHA256, Select: []int{7}}}

	sealedData, err := seal(secret, pcrSelection)
	if err != nil {
		fmt.Fprintln(os.Stderr, "cannot seal:", err)
		return
	}

	// sealedData contains a serialized blob containing our secret that has been protected by the
	// TPM. It could be written somewhere to be read back later on.

	recoveredSecret, err := unseal(sealedData)
	if err != nil {
		fmt.Fprintln(os.Stderr, "cannot unseal:", err)
		return
	}

	fmt.Println("recovered secret:", recoveredSecret)
}
Output:

Index

Examples

Constants

View Source
const (
	// CFBKey is used as the label for the symmetric key derivation used in parameter encryption.
	CFBKey = "CFB"

	// DuplicateString is used as the label for key establishment for object duplication.
	DuplicateString = "DUPLICATE"

	// IdentityKey is used as the label for key establishment when issuing and using activation
	// credentials.
	IdentityKey = "IDENTITY"

	// IntegrityKey is used as the label for the HMAC key derivation used for outer wrappers.
	IntegrityKey = "INTEGRITY"

	// SecretKey is used as the label for salt establishment when starting a salted session.
	SecretKey = "SECRET"

	// SessionKey is used as the label for the session key derivation.
	SessionKey = "ATH"

	// StorageKey is used as the label for the symmetric key derivation used for encrypting and
	// decrypting outer wrappers.
	StorageKey = "STORAGE"
)
View Source
const (
	// AnyCommandCode is used to match any command code when using IsTPMError,
	// IsTPMHandleError, IsTPMParameterError, IsTPMSessionError and IsTPMWarning.
	// As this sets the reserved bits, this can always be distringuished from a
	// valid command code.
	AnyCommandCode CommandCode = 0xc0000000

	// AnyErrorCode is used to match any error code when using IsTPMError,
	// IsTPMHandleError, IsTPMParameterError and IsTPMSessionError. As this
	// is beyond the value of any error code, it can always be distinguished from
	// a valid error code.
	AnyErrorCode ErrorCode = 0xff

	// AnyHandle is used to match any handle when using IsResourceUnavailableError.
	AnyHandle Handle = 0xffffffff

	// AnyHandleIndex is used to match any handle when using IsTPMHandleError.
	AnyHandleIndex int = -1

	// AnyParameterIndex is used to match any parameter when using IsTPMParameterError.
	AnyParameterIndex int = -1

	// AnySessionIndex is used to match any session when using IsTPMSessionError.
	AnySessionIndex int = -1

	// AnyWarningCode is used to match any warning code when using IsTPMWarning. As this
	// is beyond the value of any warning code, it can always be distinguished from a valid
	// warning code.
	AnyWarningCode WarningCode = 0xff

	// AnyVendorResponseCode is used to match any response code when using IsTPMVendorError.
	// As bit 10 is set, this is always an invalid vendor code so can be distinguished from
	// a valid vendor code.
	AnyVendorResponseCode ResponseCode = 0x900
)
View Source
const (
	CapabilityMaxProperties uint32 = math.MaxUint32
)
View Source
const (
	DefaultRSAExponent = 65537
)
View Source
const (
	// EventMaxSize indicates the maximum size of arguments of the Event type.
	EventMaxSize = 1024
)
View Source
const InfiniteTimeout = -1 * time.Millisecond

InfiniteTimeout can be used to configure an infinite timeout.

Variables

View Source
var ErrTimeoutNotSupported = errors.New("configurable command timeouts are not supported")

ErrTimeoutNotSupported indicates that a Transport implementation does not support configuring the command timeout.

Functions

func DecodeResponseCode

func DecodeResponseCode(command CommandCode, resp ResponseCode) error

DecodeResponseCode decodes the ResponseCode provided via resp. If the specified response code is ResponseSuccess, it returns no error, else it returns an error that is appropriate for the response code. The command code is used for adding context to the returned error.

If the response code is invalid, an InvalidResponseCodeError error will be returned.

func IsResourceUnavailableError

func IsResourceUnavailableError(err error, handle Handle) bool

IsResourceUnavailableError indicates whether an error is a ResourceUnavailableError with the specified handle. To test for any handle, use AnyHandle.

func IsTPMError

func IsTPMError(err error, code ErrorCode, command CommandCode) bool

IsTPMError indicates whether the error or any error within its chain is a *TPMError with the specified ErrorCode and CommandCode. To test for any error code, use AnyErrorCode. To test for any command code, use AnyCommandCode.

func IsTPMHandleError

func IsTPMHandleError(err error, code ErrorCode, command CommandCode, handle int) bool

IsTPMHandleError indicates whether the error or any error within its chain is a *TPMHandleError with the specified ErrorCode, CommandCode and handle index. To test for any error code, use AnyErrorCode. To test for any command code, use AnyCommandCode. To test for any handle index, use AnyHandleIndex.

func IsTPMParameterError

func IsTPMParameterError(err error, code ErrorCode, command CommandCode, param int) bool

IsTPMParameterError indicates whether the error or any error within its chain is a *TPMParameterError with the specified ErrorCode, CommandCode and parameter index. To test for any error code, use AnyErrorCode. To test for any command code, use AnyCommandCode. To test for any parameter index, use AnyParameterIndex.

func IsTPMSessionError

func IsTPMSessionError(err error, code ErrorCode, command CommandCode, session int) bool

IsTPMSessionError indicates whether the error or any error within its chain is a *TPMSessionError with the specified ErrorCode, CommandCode and session index. To test for any error code, use AnyErrorCode. To test for any command code, use AnyCommandCode. To test for any session index, use AnySessionIndex.

func IsTPMVendorError added in v1.7.7

func IsTPMVendorError(err error, rc ResponseCode, command CommandCode) bool

IsTPMVendorError indicates whether the error or any error within its chain is a *TPMVendorError with the specified ResponseCode and CommandCode. To test for any response code, use AnyVendorResponseCode. To test for any command code, use AnyCommandCode.

func IsTPMWarning

func IsTPMWarning(err error, code WarningCode, command CommandCode) bool

IsTPMWarning indicates whether the error or any error within its chain is a *TPMWarning with the specified WarningCode and CommandCode. To test for any warning code, use AnyWarningCode. To test for any command code, use AnyCommandCode.

func ReadCommandPacket added in v1.4.0

func ReadCommandPacket(r io.Reader, numHandles int) (command CommandCode, handles HandleList, authArea []AuthCommand, parameters []byte, err error)

ReadCommandPacket reads a command packet from the supplied reader, returning the command code, handles, auth area and parameters. The parameters will still be in the TPM wire format. The number of command handles associated with the command must be supplied by the caller.

func ReadResponsePacket added in v1.4.0

func ReadResponsePacket(r io.Reader, handle *Handle) (rc ResponseCode, parameters []byte, authArea []AuthResponse, err error)

ReadResponsePacket reads a response packet from the supplied reader, returning the response code, parameters, and auth area. The parameters will still be in the TPM wire format. The response handle will be written to the memory pointed to by the supplied handle argument if provided.

func RegisterCipher

func RegisterCipher(alg SymAlgorithmId, fn NewCipherFunc)

RegisterCipher allows a go block cipher implementation to be registered for the specified algorithm, so binaries don't need to link against every implementation.

func WriteCommandPacket added in v1.4.0

func WriteCommandPacket(w io.Writer, command CommandCode, handles HandleList, authArea []AuthCommand, parameters []byte) error

WriteCommandPacket serializes a complete TPM command packet from the provided arguments to the supplied writer. The parameters argument must already be serialized to the TPM wire format.

This will return an error if the supplied arguments cannot be represented correctly by the TPM wire format.

func WriteResponsePacket added in v1.7.0

func WriteResponsePacket(w io.Writer, rc ResponseCode, handle *Handle, parameters []byte, authArea []AuthResponse) error

WriteResponsePacket serializes a complete TPM response packet from the provided arguments to the supplied writer. The parameters argument must already be serialized to the TPM wire format. If handle is nil, then no response handle is serialized.

This will return an error if the supplied arguments cannot be represented correctly by the TPM wire format.

This will return an error if the supplied arguments are inconsistent, eg, an error response code with a non-zero parameters length or non-zero authArea length.

Types

type AlgorithmAttributes

type AlgorithmAttributes uint32

AlgorithmAttributes corresponds to the TPMA_ALGORITHM type and represents the attributes for an algorithm.

const (
	AttrAsymmetric AlgorithmAttributes = 1 << 0
	AttrSymmetric  AlgorithmAttributes = 1 << 1
	AttrHash       AlgorithmAttributes = 1 << 2
	AttrObject     AlgorithmAttributes = 1 << 3
	AttrSigning    AlgorithmAttributes = 1 << 8
	AttrEncrypting AlgorithmAttributes = 1 << 9
	AttrMethod     AlgorithmAttributes = 1 << 10
)

type AlgorithmId

type AlgorithmId uint16

AlgorithmId corresponds to the TPM_ALG_ID type.

const (
	AlgorithmError          AlgorithmId = 0x0000 // TPM_ALG_ERROR
	AlgorithmRSA            AlgorithmId = 0x0001 // TPM_ALG_RSA
	AlgorithmTDES           AlgorithmId = 0x0003 // TPM_ALG_TDES
	AlgorithmSHA1           AlgorithmId = 0x0004 // TPM_ALG_SHA1
	AlgorithmHMAC           AlgorithmId = 0x0005 // TPM_ALG_HMAC
	AlgorithmAES            AlgorithmId = 0x0006 // TPM_ALG_AES
	AlgorithmMGF1           AlgorithmId = 0x0007 // TPM_ALG_MGF1
	AlgorithmKeyedHash      AlgorithmId = 0x0008 // TPM_ALG_KEYEDHASH
	AlgorithmXOR            AlgorithmId = 0x000a // TPM_ALG_XOR
	AlgorithmSHA256         AlgorithmId = 0x000b // TPM_ALG_SHA256
	AlgorithmSHA384         AlgorithmId = 0x000c // TPM_ALG_SHA384
	AlgorithmSHA512         AlgorithmId = 0x000d // TPM_ALG_SHA512
	AlgorithmSHA256_192     AlgorithmId = 0x000e // TPM_ALG_SHA256_192
	AlgorithmNull           AlgorithmId = 0x0010 // TPM_ALG_NULL
	AlgorithmSM3_256        AlgorithmId = 0x0012 // TPM_ALG_SM3_256
	AlgorithmSM4            AlgorithmId = 0x0013 // TPM_ALG_SM4
	AlgorithmRSASSA         AlgorithmId = 0x0014 // TPM_ALG_RSASSA
	AlgorithmRSAES          AlgorithmId = 0x0015 // TPM_ALG_RSAES
	AlgorithmRSAPSS         AlgorithmId = 0x0016 // TPM_ALG_RSAPSS
	AlgorithmOAEP           AlgorithmId = 0x0017 // TPM_ALG_OAEP
	AlgorithmECDSA          AlgorithmId = 0x0018 // TPM_ALG_ECDSA
	AlgorithmECDH           AlgorithmId = 0x0019 // TPM_ALG_ECDH
	AlgorithmECDAA          AlgorithmId = 0x001a // TPM_ALG_ECDAA
	AlgorithmSM2            AlgorithmId = 0x001b // TPM_ALG_SM2
	AlgorithmECSchnorr      AlgorithmId = 0x001c // TPM_ALG_ECSCHNORR
	AlgorithmECMQV          AlgorithmId = 0x001d // TPM_ALG_ECMQV
	AlgorithmKDF1_SP800_56A AlgorithmId = 0x0020 // TPM_ALG_KDF1_SP800_56A
	AlgorithmKDF2           AlgorithmId = 0x0021 // TPM_ALG_KDF2
	AlgorithmKDF1_SP800_108 AlgorithmId = 0x0022 // TPM_ALG_KDF1_SP800_108
	AlgorithmECC            AlgorithmId = 0x0023 // TPM_ALG_ECC
	AlgorithmSymCipher      AlgorithmId = 0x0025 // TPM_ALG_SYMCIPHER
	AlgorithmCamellia       AlgorithmId = 0x0026 // TPM_ALG_CAMELLIA
	AlgorithmSHA3_256       AlgorithmId = 0x0027 // TPM_ALG_SHA3_256
	AlgorithmSHA3_384       AlgorithmId = 0x0028 // TPM_ALG_SHA3_384
	AlgorithmSHA3_512       AlgorithmId = 0x0029 // TPM_ALG_SHA3_512
	AlgorithmSHAKE128       AlgorithmId = 0x002a // TPM_ALG_SHAKE128
	AlgorithmSHAKE256       AlgorithmId = 0x002b // TPM_ALG_SHAKE256
	AlgorithmSHAKE256_192   AlgorithmId = 0x002c // TPM_ALG_SHAKE256_192
	AlgorithmSHAKE256_256   AlgorithmId = 0x002d // TPM_ALG_SHAKE256_256
	AlgorithmSHAKE256_512   AlgorithmId = 0x002e // TPM_ALG_SHAKE256_512
	AlgorithmCMAC           AlgorithmId = 0x003f // TPM_ALG_CMAC
	AlgorithmCTR            AlgorithmId = 0x0040 // TPM_ALG_CTR
	AlgorithmOFB            AlgorithmId = 0x0041 // TPM_ALG_OFB
	AlgorithmCBC            AlgorithmId = 0x0042 // TPM_ALG_CBC
	AlgorithmCFB            AlgorithmId = 0x0043 // TPM_ALG_CFB
	AlgorithmECB            AlgorithmId = 0x0044 // TPM_ALG_ECB
	AlgorithmCCM            AlgorithmId = 0x0050 // TPM_ALG_CCM
	AlgorithmGCM            AlgorithmId = 0x0051 // TPM_ALG_GCM
	AlgorithmKW             AlgorithmId = 0x0052 // TPM_ALG_KW
	AlgorithmKWP            AlgorithmId = 0x0053 // TPM_ALG_KWP
	AlgorithmEAX            AlgorithmId = 0x0054 // TPM_ALG_EAX
	AlgorithmEDDSA          AlgorithmId = 0x0060 // TPM_ALG_EDDSA
	AlgorithmEDDSA_PH       AlgorithmId = 0x0061 // TPM_ALG_EDDSA_PH
	AlgorithmLMS            AlgorithmId = 0x0070 // TPM_ALG_LMS
	AlgorithmXMSS           AlgorithmId = 0x0071 // TPM_ALG_XMSS
	AlgorithmKeyedXOF       AlgorithmId = 0x0080 // TPM_ALG_KEYEDXOF
	AlgorithmKMACXOF128     AlgorithmId = 0x0081 // TPM_ALG_KMACXOF128
	AlgorithmKMACXOF256     AlgorithmId = 0x0082 // TPM_ALG_KMACXOF256
	AlgorithmKMAC128        AlgorithmId = 0x0090 // TPM_ALG_KMAC128
	AlgorithmKMAC256        AlgorithmId = 0x0091 // TPM_ALG_KMAC256

	AlgorithmFirst AlgorithmId = AlgorithmRSA
)

func (AlgorithmId) Format

func (a AlgorithmId) Format(s fmt.State, f rune)

func (AlgorithmId) String

func (a AlgorithmId) String() string

type AlgorithmList

type AlgorithmList []AlgorithmId

AlgorithmList is a slice of AlgorithmId values, and corresponds to the TPML_ALG type.

type AlgorithmProperty

type AlgorithmProperty struct {
	Alg        AlgorithmId         // Algorithm identifier
	Properties AlgorithmAttributes // Attributes of the algorithm
}

AlgorithmProperty corresponds to the TPMS_ALG_PROPERTY type. It is used to report the properties of an algorithm.

type AlgorithmPropertyList

type AlgorithmPropertyList []AlgorithmProperty

AlgorithmPropertyList is a slice of AlgorithmProperty values, and corresponds to the TPML_ALG_PROPERTY type.

type ArithmeticOp

type ArithmeticOp uint16

ArithmeticOp corresponds to the TPM_EO type.

const (
	OpEq         ArithmeticOp = 0x0000 // TPM_EO_EQ
	OpNeq        ArithmeticOp = 0x0001 // TPM_EO_NEQ
	OpSignedGT   ArithmeticOp = 0x0002 // TPM_EO_SIGNED_GT
	OpUnsignedGT ArithmeticOp = 0x0003 // TPM_EO_UNSIGNED_GT
	OpSignedLT   ArithmeticOp = 0x0004 // TPM_EO_SIGNED_LT
	OpUnsignedLT ArithmeticOp = 0x0005 // TPM_EO_UNSIGNED_LT
	OpSignedGE   ArithmeticOp = 0x0006 // TPM_EO_SIGNED_GE
	OpUnsignedGE ArithmeticOp = 0x0007 // TPM_EO_UNSIGNED_GE
	OpSignedLE   ArithmeticOp = 0x0008 // TPM_EO_SIGNED_LE
	OpUnsignedLE ArithmeticOp = 0x0009 // TPM_EO_UNSIGNED_LE
	OpBitset     ArithmeticOp = 0x000a // TPM_EO_BITSET
	OpBitclear   ArithmeticOp = 0x000b // TPM_EO_BITCLEAR
)

func (ArithmeticOp) Format added in v1.5.0

func (o ArithmeticOp) Format(s fmt.State, f rune)

func (ArithmeticOp) String added in v1.5.0

func (o ArithmeticOp) String() string

type AsymParams

type AsymParams struct {
	Symmetric SymDefObject // Symmetric algorithm for a restricted decrypt key.
	// For a key with the AttrSign attribute: a signing scheme.
	// For a key with the AttrDecrypt attribute: a key exchange protocol.
	// For a key with both AttrSign and AttrDecrypt attributes: AlgorithmNull.
	Scheme AsymScheme
}

AsymParams corresponds to the TPMS_ASYM_PARMS type, and defines the common public parameters for an asymmetric key.

type AsymScheme

type AsymScheme struct {
	Scheme  AsymSchemeId // Scheme selector
	Details *AsymSchemeU // Scheme specific parameters
}

AsymScheme corresponds to the TPMT_ASYM_SCHEME type.

func (*AsymScheme) AnyDetails added in v1.1.0

func (s *AsymScheme) AnyDetails() *SchemeHash

AnyDetails returns the details of the asymmetric scheme. If the scheme is AsymSchemeNull, or doesn't have a digest, then nil is returned. If the scheme is not otherwise valid, it will panic.

type AsymSchemeId

type AsymSchemeId AlgorithmId

AsymSchemeId corresponds to the TPMI_ALG_ASYM_SCHEME type

const (
	AsymSchemeNull      AsymSchemeId = AsymSchemeId(AlgorithmNull)      // TPM_ALG_NULL
	AsymSchemeRSASSA    AsymSchemeId = AsymSchemeId(AlgorithmRSASSA)    // TPM_ALG_RSASSA
	AsymSchemeRSAES     AsymSchemeId = AsymSchemeId(AlgorithmRSAES)     // TPM_ALG_RSAES
	AsymSchemeRSAPSS    AsymSchemeId = AsymSchemeId(AlgorithmRSAPSS)    // TPM_ALG_RSAPSS
	AsymSchemeOAEP      AsymSchemeId = AsymSchemeId(AlgorithmOAEP)      // TPM_ALG_OAEP
	AsymSchemeECDSA     AsymSchemeId = AsymSchemeId(AlgorithmECDSA)     // TPM_ALG_ECDSA
	AsymSchemeECDH      AsymSchemeId = AsymSchemeId(AlgorithmECDH)      // TPM_ALG_ECDH
	AsymSchemeECDAA     AsymSchemeId = AsymSchemeId(AlgorithmECDAA)     // TPM_ALG_ECDAA
	AsymSchemeSM2       AsymSchemeId = AsymSchemeId(AlgorithmSM2)       // TPM_ALG_SM2
	AsymSchemeECSchnorr AsymSchemeId = AsymSchemeId(AlgorithmECSchnorr) // TPM_ALG_ECSCHNORR
	AsymSchemeECMQV     AsymSchemeId = AsymSchemeId(AlgorithmECMQV)     // TPM_ALG_ECMQV
	AsymSchemeEDDSA     AsymSchemeId = AsymSchemeId(AlgorithmEDDSA)     // TPM_ALG_EDDSA
	AsymSchemeEDDSA_PH  AsymSchemeId = AsymSchemeId(AlgorithmEDDSA_PH)  // TPM_ALG_EDDSA_PH
	AsymSchemeLMS       AsymSchemeId = AsymSchemeId(AlgorithmLMS)       // TPM_ALG_LMS
	AsymSchemeXMSS      AsymSchemeId = AsymSchemeId(AlgorithmXMSS)      // TPM_ALG_XMSS
)

func (AsymSchemeId) Format

func (a AsymSchemeId) Format(s fmt.State, f rune)

func (AsymSchemeId) HasDigest

func (s AsymSchemeId) HasDigest() bool

HasDigest determines if the asymmetric scheme is associated with a digest algorithm.

func (AsymSchemeId) IsValid

func (s AsymSchemeId) IsValid() bool

IsValid determines if the scheme is a valid asymmetric scheme.

type AsymSchemeU

type AsymSchemeU struct {
	RSASSA    *SigSchemeRSASSA
	RSAES     *EncSchemeRSAES
	RSAPSS    *SigSchemeRSAPSS
	OAEP      *EncSchemeOAEP
	ECDSA     *SigSchemeECDSA
	ECDH      *KeySchemeECDH
	ECDAA     *SigSchemeECDAA
	SM2       *SigSchemeSM2
	ECSchnorr *SigSchemeECSchnorr
	ECMQV     *KeySchemeECMQV
	EDDSA     *SigSchemeEDDSA
	EDDSA_PH  *SigSchemeEDDSA_PH
}

AsymSchemeU is a union type that corresponds to the TPMU_ASYM_SCHEME type. The selector type is AsymSchemeId. The mapping of selector values to fields is as follows:

  • AsymSchemeRSASSA: RSASSA
  • AsymSchemeRSAES: RSAES
  • AsymSchemeRSAPSS: RSAPSS
  • AsymSchemeOAEP: OAEP
  • AsymSchemeECDSA: ECDSA
  • AsymSchemeECDH: ECDH
  • AsymSchemeECDAA: ECDAA
  • AsymSchemeSM2: SM2
  • AsymSchemeECSchnorr: ECSchnorr
  • AsymSchemeECMQV: ECMQV
  • AsymSchemeEDDSA: EDDSA
  • AsymSchemeEDDSA_PH: EDDSA_PH
  • AsymSchemeNull: none

func (AsymSchemeU) Any deprecated

func (s AsymSchemeU) Any(scheme AsymSchemeId) *SchemeHash

Any returns the asymmetric scheme associated with scheme as a *SchemeHash. It panics if the specified scheme does not have an associated digest algorithm (AsymSchemeId.HasDigest returns false), or if the appropriate field isn't set.

Deprecated: Use AsymScheme.AnyDetails, RSAScheme.AnyDetails or ECCScheme.AnyDetails instead.

func (*AsymSchemeU) Select

func (s *AsymSchemeU) Select(selector reflect.Value) interface{}

Select implements mu.Union.

type Attest

type Attest struct {
	Magic           TPMGenerated // Always TPMGeneratedValue
	Type            StructTag    // Type of the attestation structure
	QualifiedSigner Name         // Qualified name of the signing key
	ExtraData       Data         // External information provided by the caller
	ClockInfo       ClockInfo    // Clock information
	FirmwareVersion uint64       // TPM vendor specific value indicating the version of the firmware
	Attested        *AttestU     `tpm2:"selector:Type"` // Type specific attestation data
}

Attest corresponds to the TPMS_ATTEST type, and is returned by the attestation commands. The signature of the attestation is over this structure.

type AttestU

type AttestU struct {
	Certify      *CertifyInfo
	Creation     *CreationInfo
	Quote        *QuoteInfo
	CommandAudit *CommandAuditInfo
	SessionAudit *SessionAuditInfo
	Time         *TimeAttestInfo
	NV           *NVCertifyInfo
}

AttestU is a union type that corresponds to the TPMU_ATTEST type. The selector type is StructTag. Mapping of selector values to fields is as follows:

  • TagAttestNV: NV
  • TagAttestCommandAudit: CommandAudit
  • TagAttestSessionAudit: SessionAudit
  • TagAttestCertify: Certify
  • TagAttestQuote: Quote
  • TagAttestTime: Time
  • TagAttestCreation: Creation

func (*AttestU) Select

func (a *AttestU) Select(selector reflect.Value) interface{}

Select implements mu.Union.

type Auth

type Auth = Digest

Auth corresponds to the TPM2B_AUTH type.

type AuthCommand

type AuthCommand struct {
	SessionHandle     Handle
	Nonce             Nonce
	SessionAttributes SessionAttributes
	HMAC              Auth
}

AuthCommand corresppnds to the TPMS_AUTH_COMMAND type, and represents an authorization for a command.

type AuthResponse

type AuthResponse struct {
	Nonce             Nonce
	SessionAttributes SessionAttributes
	HMAC              Auth
}

AuthResponse corresponds to the TPMS_AUTH_RESPONSE type, and represents an authorization response for a command.

type CapabilitiesU

type CapabilitiesU struct {
	Algorithms    AlgorithmPropertyList
	Handles       HandleList
	Command       CommandAttributesList
	PPCommands    CommandCodeList
	AuditCommands CommandCodeList
	AssignedPCR   PCRSelectionList
	TPMProperties TaggedTPMPropertyList
	PCRProperties TaggedPCRPropertyList
	ECCCurves     ECCCurveList
	AuthPolicies  TaggedPolicyList
}

Capabilities is a union type that corresponds to the TPMU_CAPABILITIES type. The selector type is Capability. Mapping of selector values to fields is as follows:

  • CapabilityAlgs: Algorithms
  • CapabilityHandles: Handles
  • CapabilityCommands: Command
  • CapabilityPPCommands: PPCommands
  • CapabilityAuditCommands: AuditCommands
  • CapabilityPCRs: AssignedPCR
  • CapabilityTPMProperties: TPMProperties
  • CapabilityPCRProperties: PCRProperties
  • CapabilityECCCurves: ECCCurves
  • CapabilityAuthPolicies: AuthPolicies

func (*CapabilitiesU) Select

func (c *CapabilitiesU) Select(selector reflect.Value) interface{}

Select implements mu.Union.

type Capability

type Capability uint32

Capability corresponds to the TPM_CAP type.

const (
	CapabilityAlgs          Capability = 0 // TPM_CAP_ALGS
	CapabilityHandles       Capability = 1 // TPM_CAP_HANDLES
	CapabilityCommands      Capability = 2 // TPM_CAP_COMMANDS
	CapabilityPPCommands    Capability = 3 // TPM_CAP_PP_COMMANDS
	CapabilityAuditCommands Capability = 4 // TPM_CAP_AUDIT_COMMANDS
	CapabilityPCRs          Capability = 5 // TPM_CAP_PCRS
	CapabilityTPMProperties Capability = 6 // TPM_CAP_TPM_PROPERTIES
	CapabilityPCRProperties Capability = 7 // TPM_CAP_PCR_PROPERTIES
	CapabilityECCCurves     Capability = 8 // TPM_CAP_ECC_CURVES
	CapabilityAuthPolicies  Capability = 9 // TPM_CAP_AUTH_POLICIES
)

func (Capability) Format

func (c Capability) Format(s fmt.State, f rune)

func (Capability) String

func (c Capability) String() string

type CapabilityData

type CapabilityData struct {
	Capability Capability     // Capability
	Data       *CapabilitiesU // Capability data
}

CapabilityData corresponds to the TPMS_CAPABILITY_DATA type, and is returned by TPMContext.GetCapability.

type CertifyInfo

type CertifyInfo struct {
	Name          Name // Name of the certified object
	QualifiedName Name // Qualified name of the certified object
}

CertifyInfo corresponds to the TPMS_CERTIFY_INFO type, and is returned by TPMContext.Certify.

type ClockInfo

type ClockInfo struct {
	Clock      uint64 // Time value in milliseconds that increments whilst the TPM is powered
	ResetCount uint32 // Number of TPM resets since the TPM was last cleared

	// RestartCount is the number of TPM restarts or resumes since the last TPM reset or the last time the TPM was cleared.
	RestartCount uint32

	// Safe indicates the the value reported by Clock is guaranteed to be unique for the current owner.
	Safe bool
}

ClockInfo corresponds to the TPMS_CLOCK_INFO type.

type CommandAttributes

type CommandAttributes uint32

CommandAttributes corresponds to the TPMA_CC type and represents the attributes of a command. It also encodes the command code to which these attributes belong, and the number of command handles for the command.

const (
	AttrNV        CommandAttributes = 1 << 22
	AttrExtensive CommandAttributes = 1 << 23
	AttrFlushed   CommandAttributes = 1 << 24
	AttrRHandle   CommandAttributes = 1 << 28
	AttrV         CommandAttributes = 1 << 29
)

func (CommandAttributes) CommandCode

func (a CommandAttributes) CommandCode() CommandCode

CommandCode returns the command code that a set of attributes belongs to.

func (CommandAttributes) NumberOfCommandHandles

func (a CommandAttributes) NumberOfCommandHandles() int

NumberOfCommandHandles returns the number of command handles for the command that a set of attributes belong to.

type CommandAttributesList

type CommandAttributesList []CommandAttributes

CommandAttributesList is a slice of CommandAttribute values, and corresponds to the TPML_CCA type.

type CommandAuditInfo

type CommandAuditInfo struct {
	AuditCounter  uint64      // Monotonic audit counter
	DigestAlg     AlgorithmId // Hash algorithm used for the command audit
	AuditDigest   Digest      // Current value of the audit digest
	CommandDigest Digest      // Digest of command codes being audited, using DigestAlg
}

CommandAuditInfo corresponds to the TPMS_COMMAND_AUDIT_INFO type, and is returned by TPMContext.GetCommandAuditDigest.

type CommandCode

type CommandCode uint32

CommandCode corresponds to the TPM_CC type.

const (
	CommandFirst CommandCode = 0x0000011A

	CommandNVUndefineSpaceSpecial     CommandCode = 0x0000011F // TPM_CC_NV_UndefineSpaceSpecial
	CommandEvictControl               CommandCode = 0x00000120 // TPM_CC_EvictControl
	CommandHierarchyControl           CommandCode = 0x00000121 // TPM_CC_HierarchyControl
	CommandNVUndefineSpace            CommandCode = 0x00000122 // TPM_CC_NV_UndefineSpace
	CommandClear                      CommandCode = 0x00000126 // TPM_CC_Clear
	CommandClearControl               CommandCode = 0x00000127 // TPM_CC_ClearControl
	CommandClockSet                   CommandCode = 0x00000128 // TPM_CC_ClockSet
	CommandHierarchyChangeAuth        CommandCode = 0x00000129 // TPM_CC_HierarchyChangeAuth
	CommandNVDefineSpace              CommandCode = 0x0000012A // TPM_CC_NV_DefineSpace
	CommandPCRAllocate                CommandCode = 0x0000012B // TPM_CC_PCR_Allocate
	CommandSetPrimaryPolicy           CommandCode = 0x0000012E // TPM_CC_SetPrimaryPolicy
	CommandClockRateAdjust            CommandCode = 0x00000130 // TPM_CC_ClockRateAdjust
	CommandCreatePrimary              CommandCode = 0x00000131 // TPM_CC_CreatePrimary
	CommandNVGlobalWriteLock          CommandCode = 0x00000132 // TPM_CC_NV_GlobalWriteLock
	CommandGetCommandAuditDigest      CommandCode = 0x00000133 // TPM_CC_GetCommandAuditDigest
	CommandNVIncrement                CommandCode = 0x00000134 // TPM_CC_NV_Increment
	CommandNVSetBits                  CommandCode = 0x00000135 // TPM_CC_NV_SetBits
	CommandNVExtend                   CommandCode = 0x00000136 // TPM_CC_NV_Extend
	CommandNVWrite                    CommandCode = 0x00000137 // TPM_CC_NV_Write
	CommandNVWriteLock                CommandCode = 0x00000138 // TPM_CC_NV_WriteLock
	CommandDictionaryAttackLockReset  CommandCode = 0x00000139 // TPM_CC_DictionaryAttackLockReset
	CommandDictionaryAttackParameters CommandCode = 0x0000013A // TPM_CC_DictionaryAttackParameters
	CommandNVChangeAuth               CommandCode = 0x0000013B // TPM_CC_NV_ChangeAuth
	CommandPCREvent                   CommandCode = 0x0000013C // TPM_CC_PCR_Event
	CommandPCRReset                   CommandCode = 0x0000013D // TPM_CC_PCR_Reset
	CommandSequenceComplete           CommandCode = 0x0000013E // TPM_CC_SequenceComplete
	CommandSetCommandCodeAuditStatus  CommandCode = 0x00000140 // TPM_CC_SetCommandCodeAuditStatus
	CommandIncrementalSelfTest        CommandCode = 0x00000142 // TPM_CC_IncrementalSelfTest
	CommandSelfTest                   CommandCode = 0x00000143 // TPM_CC_SelfTest
	CommandStartup                    CommandCode = 0x00000144 // TPM_CC_Startup
	CommandShutdown                   CommandCode = 0x00000145 // TPM_CC_Shutdown
	CommandStirRandom                 CommandCode = 0x00000146 // TPM_CC_StirRandom
	CommandActivateCredential         CommandCode = 0x00000147 // TPM_CC_ActivateCredential
	CommandCertify                    CommandCode = 0x00000148 // TPM_CC_Certify
	CommandPolicyNV                   CommandCode = 0x00000149 // TPM_CC_PolicyNV
	CommandCertifyCreation            CommandCode = 0x0000014A // TPM_CC_CertifyCreation
	CommandDuplicate                  CommandCode = 0x0000014B // TPM_CC_Duplicate
	CommandGetTime                    CommandCode = 0x0000014C // TPM_CC_GetTime
	CommandGetSessionAuditDigest      CommandCode = 0x0000014D // TPM_CC_GetSessionAuditDigest
	CommandNVRead                     CommandCode = 0x0000014E // TPM_CC_NV_Read
	CommandNVReadLock                 CommandCode = 0x0000014F // TPM_CC_NV_ReadLock
	CommandObjectChangeAuth           CommandCode = 0x00000150 // TPM_CC_ObjectChangeAuth
	CommandPolicySecret               CommandCode = 0x00000151 // TPM_CC_PolicySecret
	CommandCreate                     CommandCode = 0x00000153 // TPM_CC_Create
	CommandECDHZGen                   CommandCode = 0x00000154 // TPM_CC_ECDH_ZGen
	CommandHMAC                       CommandCode = 0x00000155 // TPM_CC_HMAC
	CommandImport                     CommandCode = 0x00000156 // TPM_CC_Import
	CommandLoad                       CommandCode = 0x00000157 // TPM_CC_Load
	CommandQuote                      CommandCode = 0x00000158 // TPM_CC_Quote
	CommandRSADecrypt                 CommandCode = 0x00000159 // TPM_CC_RSA_Decrypt
	CommandHMACStart                  CommandCode = 0x0000015B // TPM_CC_HMAC_Start
	CommandSequenceUpdate             CommandCode = 0x0000015C // TPM_CC_SequenceUpdate
	CommandSign                       CommandCode = 0x0000015D // TPM_CC_Sign
	CommandUnseal                     CommandCode = 0x0000015E // TPM_CC_Unseal
	CommandPolicySigned               CommandCode = 0x00000160 // TPM_CC_PolicySigned
	CommandContextLoad                CommandCode = 0x00000161 // TPM_CC_ContextLoad
	CommandContextSave                CommandCode = 0x00000162 // TPM_CC_ContextSave
	CommandECDHKeyGen                 CommandCode = 0x00000163 // TPM_CC_ECDH_KeyGen
	CommandFlushContext               CommandCode = 0x00000165 // TPM_CC_FlushContext
	CommandLoadExternal               CommandCode = 0x00000167 // TPM_CC_LoadExternal
	CommandMakeCredential             CommandCode = 0x00000168 // TPM_CC_MakeCredential
	CommandNVReadPublic               CommandCode = 0x00000169 // TPM_CC_NV_ReadPublic
	CommandPolicyAuthorize            CommandCode = 0x0000016A // TPM_CC_PolicyAuthorize
	CommandPolicyAuthValue            CommandCode = 0x0000016B // TPM_CC_PolicyAuthValue
	CommandPolicyCommandCode          CommandCode = 0x0000016C // TPM_CC_PolicyCommandCode
	CommandPolicyCounterTimer         CommandCode = 0x0000016D // TPM_CC_PolicyCounterTimer
	CommandPolicyCpHash               CommandCode = 0x0000016E // TPM_CC_PolicyCpHash
	CommandPolicyLocality             CommandCode = 0x0000016F // TPM_CC_PolicyLocality
	CommandPolicyNameHash             CommandCode = 0x00000170 // TPM_CC_PolicyNameHash
	CommandPolicyOR                   CommandCode = 0x00000171 // TPM_CC_PolicyOR
	CommandPolicyTicket               CommandCode = 0x00000172 // TPM_CC_PolicyTicket
	CommandReadPublic                 CommandCode = 0x00000173 // TPM_CC_ReadPublic
	CommandRSAEncrypt                 CommandCode = 0x00000174 // TPM_CC_RSA_Encrypt
	CommandStartAuthSession           CommandCode = 0x00000176 // TPM_CC_StartAuthSession
	CommandVerifySignature            CommandCode = 0x00000177 // TPM_CC_VerifySignature
	CommandECCParameters              CommandCode = 0x00000178 // TPM_CC_ECC_Parameters
	CommandGetCapability              CommandCode = 0x0000017A // TPM_CC_GetCapability
	CommandGetRandom                  CommandCode = 0x0000017B // TPM_CC_GetRandom
	CommandGetTestResult              CommandCode = 0x0000017C // TPM_CC_GetTestResult
	CommandHash                       CommandCode = 0x0000017D // TPM_CC_Hash
	CommandPCRRead                    CommandCode = 0x0000017E // TPM_CC_PCR_Read
	CommandPolicyPCR                  CommandCode = 0x0000017F // TPM_CC_PolicyPCR
	CommandPolicyRestart              CommandCode = 0x00000180 // TPM_CC_PolicyRestart
	CommandReadClock                  CommandCode = 0x00000181 // TPM_CC_ReadClock
	CommandPCRExtend                  CommandCode = 0x00000182 // TPM_CC_PCR_Extend
	CommandNVCertify                  CommandCode = 0x00000184 // TPM_CC_NV_Certify
	CommandEventSequenceComplete      CommandCode = 0x00000185 // TPM_CC_EventSequenceComplete
	CommandHashSequenceStart          CommandCode = 0x00000186 // TPM_CC_HashSequenceStart
	CommandPolicyDuplicationSelect    CommandCode = 0x00000188 // TPM_CC_PolicyDuplicationSelect
	CommandPolicyGetDigest            CommandCode = 0x00000189 // TPM_CC_PolicyGetDigest
	CommandTestParms                  CommandCode = 0x0000018A // TPM_CC_TestParms
	CommandCommit                     CommandCode = 0x0000018B // TPM_CC_Commit
	CommandPolicyPassword             CommandCode = 0x0000018C // TPM_CC_PolicyPassword
	CommandPolicyNvWritten            CommandCode = 0x0000018F // TPM_CC_PolicyNvWritten
	CommandPolicyTemplate             CommandCode = 0x00000190 // TPM_CC_PolicyTemplate
	CommandCreateLoaded               CommandCode = 0x00000191 // TPM_CC_CreateLoaded
	CommandPolicyAuthorizeNV          CommandCode = 0x00000192 // TPM_CC_PolicyAuthorizeNV
)

func (CommandCode) Format

func (c CommandCode) Format(s fmt.State, f rune)

func (CommandCode) String

func (c CommandCode) String() string

type CommandCodeList

type CommandCodeList []CommandCode

CommandCodeList is a slice of CommandCode values, and corresponds to the TPML_CC type.

type CommandContext added in v0.2.0

type CommandContext struct {
	// contains filtered or unexported fields
}

CommandContext provides an API for building a command to execute via a TPMContext.

func (*CommandContext) AddExtraSessions added in v0.2.0

func (c *CommandContext) AddExtraSessions(sessions ...SessionContext) *CommandContext

AddExtraSessions adds the supplied additional session contexts to this command. These sessions are not used for authorization of any resources, but can be used for command or response parameter encryption, or command auditing.

func (*CommandContext) AddHandles added in v0.2.0

func (c *CommandContext) AddHandles(handles ...*CommandHandleContext) *CommandContext

AddHandles appends the supplied command handle contexts to this command.

func (*CommandContext) AddParams added in v0.2.0

func (c *CommandContext) AddParams(params ...interface{}) *CommandContext

AddParams appends the supplied command parameters to this command.

func (*CommandContext) Run added in v0.2.0

func (c *CommandContext) Run(responseHandle *Handle, responseParams ...interface{}) error

Run executes the command defined by this context using the TPMContext that created it. The caller supplies a pointer to the response handle if the command returns one, and a command dependent number of pointers to response parameters.

If a SessionContext used for this command has the AttrCommandEncrypt attribute set, then the first command parameter will be encrypted using the properties of that SessionContext.

If a SessionContext used for this command has the AttrResponseEncrypt attribute set, then the first response parameter will be decrypted using the properties of that SessionContext.

If the TPM returns a response indicating that the command should be retried, this function will retry up to a maximum number of times defined by the number supplied to TPMContext.SetMaxSubmissions.

This performs validation of the response auth area and updates internal SessionContext state. If a response HMAC is invalid, an error will be returned.

A *TransportError will be returned if the transmission interface returns an error.

One of *TPMWarning, *TPMError, *TPMParameterError, *TPMHandleError or *TPMSessionError will be returned if the TPM returns a response code other than ResponseSuccess.

func (*CommandContext) RunWithoutProcessingResponse added in v0.2.0

func (c *CommandContext) RunWithoutProcessingResponse(responseHandle *Handle) (*ResponseContext, error)

RunWithoutProcessingResponse executes the command defined by this context using the TPMContext that created it. The caller supplies a pointer to the response handle if the command returns one.

If a SessionContext used for this command has the AttrCommandEncrypt attribute set, then the first command parameter will be encrypted using the properties of that SessionContext.

If the TPM returns a response indicating that the command should be retried, this function will retry up to a maximum number of times defined by the number supplied to TPMContext.SetMaxSubmissions.

This performs no validation of the response auth area. Instead, a ResponseContext is returned and the caller is expected to call ResponseContext.Complete. This is useful for commands that change an authorization value, where the response HMAC is computed with a key based on the new value.

A *TransportError will be returned if the transmission interface returns an error.

One of *TPMWarning, *TPMError, *TPMParameterError, *TPMHandleError or *TPMSessionError will be returned if the TPM returns a response code other than ResponseSuccess.

type CommandHandleContext added in v0.2.0

type CommandHandleContext struct {
	// contains filtered or unexported fields
}

CommandHandleContext is used to supply a HandleContext to a CommandContext.

func UseHandleContext added in v0.2.0

func UseHandleContext(h HandleContext) *CommandHandleContext

UseHandleContext creates a CommandHandleContext for any HandleContext that does not require authorization. If the HandleContext is nil, then HandleNull is used.

func UseResourceContextWithAuth added in v0.2.0

func UseResourceContextWithAuth(r ResourceContext, s SessionContext) *CommandHandleContext

UseResourceContextWithAuth creates a CommandHandleContext for a ResourceContext that requires authorization in a command. The supplied SessionContext is the session used for authorization and determines the type of authorization used for the specified resource:

  • If SessionContext is nil, then passphrase authorization is used.
  • If SessionContext is a HMAC session, then HMAC authorization is used.
  • If SessionContext is a policy session, then policy authorization is used.

If the authorization value of the resource is required as part of the authorization (eg, for passphrase authorization, a HMAC session that is not bound to the specified resource, or a policy session that contains the TPM2_PolicyPassword or TPM2_PolicyAuthValue assertion), it is obtained from the supplied ResourceContext, and should be set by calling ResourceContext.SetAuthValue before the command is executed.

Resources that require authorization will require authorization with one of 3 roles, depending on the command: user, admin or duplication. The role determines the required authorization type, which is dependent on the type of the resource.

Where a command requires authorization with the user role for a resource, the following authorization types are permitted:

  • HandleTypePCR: passphrase or HMAC session if no auth policy is set, or a policy session if an auth policy is set.
  • HandleTypeNVIndex: passphrase, HMAC session or policy session depending on attributes.
  • HandleTypePermanent: passphrase or HMAC session. A policy session can also be used if an auth policy is set.
  • HandleTypeTransient / HandleTypePersistent: policy session. Passphrase or HMAC session can also be used if AttrWithUserAuth is set.

Where a command requires authorization with the admin role for a resource, the following authorization types are permitted:

Where a command requires authorization with the duplication role for a resource, a policy session is required.

Where a policy session is used for a resource that requires authorization with the admin or duplication role, the session must contain the TPM2_PolicyCommandCode assertion.

If the ResourceContext is nil, then HandleNull is used.

func (*CommandHandleContext) Handle added in v0.2.0

func (c *CommandHandleContext) Handle() HandleContext

Handle returns the HandleContext.

func (*CommandHandleContext) Session added in v0.2.0

func (c *CommandHandleContext) Session() SessionContext

Session returns the SessionContext if the handle requires authorization.

type CommandHeader

type CommandHeader struct {
	Tag         StructTag
	CommandSize uint32
	CommandCode CommandCode
}

CommandHeader is the header for a TPM command.

type CommandPacket deprecated

type CommandPacket []byte

CommandPacket corresponds to a complete command packet including header and payload.

Deprecated: use ReadCommandPacket.

func MarshalCommandPacket

func MarshalCommandPacket(command CommandCode, handles HandleList, authArea []AuthCommand, parameters []byte) (CommandPacket, error)

MarshalCommandPacket serializes a complete TPM packet from the provided arguments. The parameters argument must already be serialized to the TPM wire format.

This will return an error if the supplied parameters cannot be represented correctly by the TPM wire format.

func MustMarshalCommandPacket added in v0.2.0

func MustMarshalCommandPacket(commandCode CommandCode, handles HandleList, authArea []AuthCommand, parameters []byte) CommandPacket

MustMarshalCommandPacket serializes a complete TPM packet from the provided arguments. The parameters argument must already be serialized to the TPM wire format.

This will panic if the supplied parameters cannot be represented correctly by the TPM wire format.

func (CommandPacket) GetCommandCode deprecated

func (p CommandPacket) GetCommandCode() (CommandCode, error)

GetCommandCode returns the command code contained within this packet.

Deprecated: just supply a CommandHeader to mu.UnmarshalFromBytes or mu.UnmarshalFromReader.

func (CommandPacket) Unmarshal deprecated

func (p CommandPacket) Unmarshal(numHandles int) (handles HandleList, authArea []AuthCommand, parameters []byte, err error)

Unmarshal unmarshals this command packet, returning the handles, auth area and parameters. The parameters will still be in the TPM wire format. The number of command handles associated with the command must be supplied by the caller.

Deprecated: use ReadCommandPacket.

type Context

type Context struct {
	Sequence    uint64      // Sequence number of the context
	SavedHandle Handle      // Handle indicating if this is a session or object
	Hierarchy   Handle      // Hierarchy of the context
	Blob        ContextData // Encrypted context data and integrity HMAC
}

Context corresponds to the TPMS_CONTEXT type which represents a saved object or session context.

type ContextData

type ContextData []byte

ContextData corresponds to the TPM2B_CONTEXT_DATA type.

type CreationData

type CreationData struct {
	PCRSelect PCRSelectionList // PCRs included in PCRDigest

	// Digest of the selected PCRs using the name algorithm of the object associated with this data.
	PCRDigest           Digest
	Locality            Locality    // Locality at which the object was created
	ParentNameAlg       AlgorithmId // Name algorithm of the parent
	ParentName          Name        // Name of the parent
	ParentQualifiedName Name        // Qualified name of the parent
	OutsideInfo         Data        // External information provided by the caller
}

CreationData corresponds to the TPMS_CREATION_DATA type, which provides information about the creation environment of an object.

type CreationInfo

type CreationInfo struct {
	ObjectName   Name // Name of the object
	CreationHash Digest
}

CreationInfo corresponds to the TPMS_CREATION_INFO type, and is returned by TPMContext.CertifyCreation.

type Data

type Data []byte

Data corresponds to the TPM2B_DATA type. The largest size of this supported by the TPM can be determined by calling TPMContext.GetMaxData.

type Derive

type Derive struct {
	Label   Label
	Context Label
}

Derive corresponds to the TPMS_DERIVE type.

type Digest

type Digest []byte

Digest corresponds to the TPM2B_DIGEST type. The largest size of this supported by the TPM can be determined by calling TPMContext.GetMaxDigest.

type DigestList

type DigestList []Digest

DigestList is a slice of Digest values, and corresponds to the TPML_DIGEST type.

type ECCCurve

type ECCCurve uint16

ECCCurve corresponds to the TPM_ECC_CURVE type.

const (
	ECCCurveNIST_P192  ECCCurve = 0x0001 // TPM_ECC_NIST_P192
	ECCCurveNIST_P224  ECCCurve = 0x0002 // TPM_ECC_NIST_P224
	ECCCurveNIST_P256  ECCCurve = 0x0003 // TPM_ECC_NIST_P256
	ECCCurveNIST_P384  ECCCurve = 0x0004 // TPM_ECC_NIST_P384
	ECCCurveNIST_P521  ECCCurve = 0x0005 // TPM_ECC_NIST_P521
	ECCCurveBN_P256    ECCCurve = 0x0010 // TPM_ECC_BN_P256
	ECCCurveBN_P638    ECCCurve = 0x0011 // TPM_ECC_BN_P638
	ECCCurveSM2_P256   ECCCurve = 0x0020 // TPM_ECC_SM2_P256
	ECCCurveBP_P256_R1 ECCCurve = 0x0030 // TPM_ECC_BP_P256_R1
	ECCCurveBP_P384_R1 ECCCurve = 0x0031 // TPM_ECC_BP_P384_R1
	ECCCurveBP_P512_R1 ECCCurve = 0x0032 // TPM_ECC_BP_P512_R1
	ECCCurve25519      ECCCurve = 0x0040 // TPM_ECC_CURVE_25519
	ECCCurve448        ECCCurve = 0x0041 // TPM_ECC_CURVE_448

	ECCCurveFirst ECCCurve = ECCCurveNIST_P192
)

func (ECCCurve) GoCurve

func (c ECCCurve) GoCurve() elliptic.Curve

GoCurve returns the equivalent elliptic.Curve for this ECC curve.

type ECCCurveList

type ECCCurveList []ECCCurve

ECCCurveList is a slice of ECCCurve values, and corresponds to the TPML_ECC_CURVE type.

type ECCParameter

type ECCParameter []byte

ECCParameter corresponds to the TPM2B_ECC_PARAMETER type.

type ECCParams

type ECCParams struct {
	Symmetric SymDefObject // Symmetric algorithm for a restricted decrypt key.
	// For a key with the AttrSign attribute: a signing scheme.
	// For a key with the AttrDecrypt attribute: a key exchange protocol or AlgorithmNull.
	// For a storage key: AlgorithmNull.
	Scheme  ECCScheme
	CurveID ECCCurve  // ECC curve ID
	KDF     KDFScheme // Unused - always KDFAlgorithmNull
}

ECCParams corresponds to the TPMS_ECC_PARMS type, and defines the public parameters for an ECC key.

type ECCPoint

type ECCPoint struct {
	X ECCParameter // X coordinate
	Y ECCParameter // Y coordinate
}

ECCPoint corresponds to the TPMS_ECC_POINT type, and contains the coordinates that define an ECC point.

type ECCScheme

type ECCScheme struct {
	Scheme  ECCSchemeId  // Scheme selector
	Details *AsymSchemeU // Scheme specific parameters.
}

ECCScheme corresponds to the TPMT_ECC_SCHEME type.

func (*ECCScheme) AnyDetails added in v1.1.0

func (s *ECCScheme) AnyDetails() *SchemeHash

AnyDetails returns the details of the ECC scheme. If the scheme is ECCSchemeNull then nil is returned. If the scheme is not otherwise valid, it will panic.

type ECCSchemeId

type ECCSchemeId AsymSchemeId

ECCSchemeId corresponds to the TPMI_ALG_ECC_SCHEME type.

const (
	ECCSchemeNull      ECCSchemeId = ECCSchemeId(AlgorithmNull)      // TPM_ALG_NULL
	ECCSchemeECDSA     ECCSchemeId = ECCSchemeId(AlgorithmECDSA)     // TPM_ALG_ECDSA
	ECCSchemeECDH      ECCSchemeId = ECCSchemeId(AlgorithmECDH)      // TPM_ALG_ECDH
	ECCSchemeECDAA     ECCSchemeId = ECCSchemeId(AlgorithmECDAA)     // TPM_ALG_ECDAA
	ECCSchemeSM2       ECCSchemeId = ECCSchemeId(AlgorithmSM2)       // TPM_ALG_SM2
	ECCSchemeECSchnorr ECCSchemeId = ECCSchemeId(AlgorithmECSchnorr) // TPM_ALG_ECSCHNORR
	ECCSchemeECMQV     ECCSchemeId = ECCSchemeId(AlgorithmECMQV)     // TPM_ALG_ECMQV
)

func (ECCSchemeId) Format

func (a ECCSchemeId) Format(s fmt.State, f rune)

type Empty

type Empty struct{}

type EncSchemeOAEP

type EncSchemeOAEP = SchemeHash

type EncSchemeRSAES

type EncSchemeRSAES = Empty

type EncryptedSecret

type EncryptedSecret []byte

EncryptedSecret corresponds to the TPM2B_ENCRYPTED_SECRET type.

type ErrorCode

type ErrorCode uint8

ErrorCode represents a TPM error. This type represents TCG defined format 0 response codes without the severity bit set (response codes 0x100 to 0x17f), and format 1 response codes (where rc & 0x80 != 0).

Format 0 error numbers are 7 bits wide and are represented by codes 0x00 to 0x7f. Format 1 error numbers are 6 bits wide and are represented by codes 0x80 to 0xbf.

const (
	// ErrorInitialize corresponds to TPM_RC_INITIALIZE and is returned for any command executed
	// between a _TPM_Init event and a TPM2_Startup command.
	ErrorInitialize ErrorCode = 0x00

	// ErrorFailure corresponds to TPM_RC_FAILURE and is returned for any command if the TPM is in
	// failure mode.
	ErrorFailure ErrorCode = 0x01

	ErrorSequence  ErrorCode = 0x03 // TPM_RC_SEQUENCE
	ErrorDisabled  ErrorCode = 0x20 // TPM_RC_DISABLED
	ErrorExclusive ErrorCode = 0x21 // TPM_RC_EXCLUSIVE

	// ErrorAuthType corresponds to TPM_RC_AUTH_TYPE and is returned for a command where an
	// authorization is required and the authorization type is expected to be a policy session, but
	// another authorization type has been provided.
	ErrorAuthType ErrorCode = 0x24

	// ErrorAuthMissing corresponds to TPM_RC_AUTH_MISSING and is returned for a command that accepts
	// a ResourceContext argument that requires authorization, but no authorization session has been
	// provided in the command payload.
	ErrorAuthMissing ErrorCode = 0x25

	ErrorPolicy ErrorCode = 0x26 // TPM_RC_POLICY
	ErrorPCR    ErrorCode = 0x27 // TPM_RC_PCR

	// ErrorPCRChanged corresponds to TPM_RC_PCR_CHANGED and is returned for a command where a policy
	// session is used for authorization and the PCR contents have been updated since the last time
	// that they were checked in the session with a TPM2_PolicyPCR assertion.
	ErrorPCRChanged ErrorCode = 0x28

	// ErrorUpgrade corresponds to TPM_RC_UPGRADE and is returned for any command that isn't
	// TPM2_FieldUpgradeData if the TPM is in field upgrade mode.
	ErrorUpgrade ErrorCode = 0x2d

	ErrorTooManyContexts ErrorCode = 0x2e // TPM_RC_TOO_MANY_CONTEXTS

	// ErrorAuthUnavailable corresponds to TPM_RC_AUTH_UNAVAILABLE and is returned for a command where
	// the provided authorization requires the use of the authorization value for an entity, but the
	// authorization value cannot be used. For example, if the entity is an object and the command
	// requires the user auth role but the object does not have the AttrUserWithAuth attribute.
	ErrorAuthUnavailable ErrorCode = 0x2f

	// ErrorReboot corresponds to TPM_RC_REBOOT and is returned for any command if the TPM requires a
	// _TPM_Init event before it will execute any more commands.
	ErrorReboot ErrorCode = 0x30

	ErrorUnbalanced ErrorCode = 0x31 // TPM_RC_UNBALANCED

	// ErrorCommandSize corresponds to TPM_RC_COMMAND_SIZE and indicates that the value of the
	// commandSize field in the command header does not match the size of the command packet
	// transmitted to the TPM.
	ErrorCommandSize ErrorCode = 0x42

	// ErrorCommandCode corresponds to TPM_RC_COMMAND_CODE and is returned for any command that is not
	// implemented by the TPM.
	ErrorCommandCode ErrorCode = 0x43

	ErrorAuthsize ErrorCode = 0x44 // TPM_RC_AUTHSIZE

	// ErrorAuthContext corresponds to TPM_RC_AUTH_CONTEXT and is returned for any command that does
	// not accept any sessions if sessions have been provided in the command payload.
	ErrorAuthContext ErrorCode = 0x45

	ErrorNVRange         ErrorCode = 0x46 // TPM_RC_NV_RANGE
	ErrorNVSize          ErrorCode = 0x47 // TPM_RC_NV_SIZE
	ErrorNVLocked        ErrorCode = 0x48 // TPM_RC_NV_LOCKED
	ErrorNVAuthorization ErrorCode = 0x49 // TPM_RC_NV_AUTHORIZATION
	ErrorNVUninitialized ErrorCode = 0x4a // TPM_RC_NV_UNINITIALIZED
	ErrorNVSpace         ErrorCode = 0x4b // TPM_RC_NV_SPACE
	ErrorNVDefined       ErrorCode = 0x4c // TPM_RC_NV_DEFINED
	ErrorBadContext      ErrorCode = 0x50 // TPM_RC_BAD_CONTEXT
	ErrorCpHash          ErrorCode = 0x51 // TPM_RC_CPHASH
	ErrorParent          ErrorCode = 0x52 // TPM_RC_PARENT
	ErrorNeedsTest       ErrorCode = 0x53 // TPM_RC_NEEDS_TEST

	// ErrorNoResult corresponds to TPM_RC_NO_RESULT and is returned for any command if the TPM
	// cannot process a request due to an unspecified problem.
	ErrorNoResult ErrorCode = 0x54

	ErrorSensitive ErrorCode = 0x55 // TPM_RC_SENSITIVE

	ErrorAsymmetric ErrorCode = errorCode1Start + 0x01 // TPM_RC_ASYMMETRIC

	// ErrorAttributes corresponds to TPM_RC_ATTRIBUTES and is returned as a *TPMSessionError for a
	// command in the following circumstances:
	// * More than one SessionContext instance with the AttrCommandEncrypt attribute has been provided.
	// * More than one SessionContext instance with the AttrResponseEncrypt attribute has been provided.
	// * A SessionContext instance referencing a trial session has been provided for authorization.
	ErrorAttributes ErrorCode = errorCode1Start + 0x02

	// ErrorHash corresponds to TPM_RC_HASH and is returned as a *TPMParameterError error for any
	// command that accepts a HashAlgorithmId parameter if the parameter value is not a valid digest
	// algorithm.
	ErrorHash ErrorCode = errorCode1Start + 0x03

	// ErrorValue corresponds to TPM_RC_VALUE and is returned as a *TPMParameterError or
	// *TPMHandleError for any command where an argument value is incorrect or out of range for the
	// command.
	ErrorValue ErrorCode = errorCode1Start + 0x04 // TPM_RC_VALUE

	// ErrorHierarchy corresponds to TPM_RC_HIERARCHY and is returned as a *TPMHandleError error for
	// any command that accepts a ResourceContext or Handle argument if that argument corresponds to
	// a hierarchy on the TPM that has been disabled.
	ErrorHierarchy ErrorCode = errorCode1Start + 0x05

	ErrorKeySize ErrorCode = errorCode1Start + 0x07 // TPM_RC_KEY_SIZE
	ErrorMGF     ErrorCode = errorCode1Start + 0x08 // TPM_RC_MGF

	// ErrorMode corresponds to TPM_RC_MODE and is returned as a *TPMParameterError error for any
	// command that accepts a SymModeId parameter if the parameter value is not a valid symmetric
	// mode.
	ErrorMode ErrorCode = errorCode1Start + 0x09

	// ErrorType corresponds to TPM_RC_TYPE and is returned as a *TPMParameterError error for any
	// command that accepts a ObjectTypeId parameter if the parameter value is not a valid public
	// type.
	ErrorType ErrorCode = errorCode1Start + 0x0a

	ErrorHandle ErrorCode = errorCode1Start + 0x0b // TPM_RC_HANDLE

	// ErrorKDF corresponds to TPM_RC_KDF and is returned as a *TPMParameterError error for any
	// command that accepts a KDFAlgorithmId parameter if the parameter value is not a valid key
	// derivation function.
	ErrorKDF ErrorCode = errorCode1Start + 0x0c

	ErrorRange ErrorCode = errorCode1Start + 0x0d // TPM_RC_RANGE

	// ErrorAuthFail corresponds to TPM_RC_AUTH_FAIL and is returned as a *TPMSessionError error for
	// a command if an authorization check fails. The dictionary attack counter is incremented when
	// this error is returned.
	ErrorAuthFail ErrorCode = errorCode1Start + 0x0e

	// ErrorNonce corresponds to TPM_RC_NONCE and is returned as a *TPMSessionError error for any
	// command where a password authorization has been provided and the authorization session in the
	// command payload contains a non-zero sized nonce field.
	ErrorNonce ErrorCode = errorCode1Start + 0x0f

	// ErrorPP corresponds to TPM_RC_PP and is returned as a *TPMSessionError for a command in the
	// following circumstances:
	// * Authorization of the platform hierarchy is provided and the command requires an assertion of
	//   physical presence that hasn't been provided.
	// * Authorization is provided with a policy session that includes the TPM2_PolicyPhysicalPresence
	//   assertion, and an assertion of physical presence hasn't been provided.
	ErrorPP ErrorCode = errorCode1Start + 0x10

	// ErrorScheme corresponds to TPM_RC_SCHEME and is returned as a *TPMParameterError error for any
	// command that accepts a SigSchemeId or ECCSchemeId parameter if the parameter value is not valid.
	ErrorScheme ErrorCode = errorCode1Start + 0x12

	// ErrorSize corresponds to TPM_RC_SIZE and is returned for a command in the following circumstances:
	// * As a *TPMParameterError if the command accepts a parameter type corresponding to TPM2B or
	//   TPML prefixed types and the size or length field has an invalid value.
	// * As a *TPMError if the TPM's parameter unmarshalling doesn't consume all of the bytes in the
	//   input buffer.
	// * As a *TPMError if the size field of the command's authorization area is an invalid value.
	// * As a *TPMSessionError if the authorization area for a command payload contains more than 3
	//   sessions.
	ErrorSize ErrorCode = errorCode1Start + 0x15

	// ErrorSymmetric corresponds to TPM_RC_SYMMETRIC and is returned for a command in the following
	// circumstances:
	// * As a *TPMParameterError if the command accepts a SymAlgorithmId parameter if the parameter
	//   value is not a valid symmetric algorithm.
	// * As a *TPMSessionError if a SessionContext instance is provided with the AttrCommandEncrypt
	//   attribute set but the session has no symmetric algorithm.
	// * As a *TPMSessionError if a SessionContext instance is provided with the AttrResponseEncrypt
	//   attribute set but the session has no symmetric algorithm.
	ErrorSymmetric ErrorCode = errorCode1Start + 0x16

	// ErrorTag corresponds to TPM_RC_TAG and is returned as a *TPMParameterError error for a command
	// that accepts a StructTag parameter if the parameter value is not the correct value.
	ErrorTag ErrorCode = errorCode1Start + 0x17

	// ErrorSelector corresponds to TPM_RC_SELECTOR and is returned as a *TPMParameterError error for
	// a command that accepts a parameter type corresponding to a TPMU prefixed type if the value of
	// the selector field in the surrounding TPMT prefixed type is incorrect.
	ErrorSelector ErrorCode = errorCode1Start + 0x18

	// ErrorInsufficient corresponds to TPM_RC_INSUFFICIENT and is returned as a *TPMParameterError
	// for a command if there is insufficient data in the TPM's input buffer to complete unmarshalling
	// of the command parameters.
	ErrorInsufficient ErrorCode = errorCode1Start + 0x1a

	ErrorSignature ErrorCode = errorCode1Start + 0x1b // TPM_RC_SIGNATURE
	ErrorKey       ErrorCode = errorCode1Start + 0x1c // TPM_RC_KEY

	// ErrorPolicyFail corresponds to TPM_RC_POLICY_FAIL and is returned as a *TPMSessionError error
	// for a command in the following circumstances:
	// * A policy session is used for authorization and the policy session digest does not match the
	//   authorization policy digest for the entity being authorized.
	// * A policy session is used for authorization and the digest algorithm of the session does not
	//   match the name algorithm of the entity being authorized.
	// * A policy session is used for authorization but the authorization is for the admin or DUP role
	//   and the policy session does not include a TPM2_PolicyCommandCode assertion.
	// * A policy session is used for authorization and the policy session includes a
	//   TPM2_PolicyNvWritten assertion but the entity being authorized is not a NV index.
	// * A policy session is used for authorization, the policy session includes the
	//   TPM2_PolicyNvWritten assertion, but the NV index being authorized does not have the
	//   AttrNVWritten attribute set.
	ErrorPolicyFail ErrorCode = errorCode1Start + 0x1d

	ErrorIntegrity ErrorCode = errorCode1Start + 0x1f // TPM_RC_INTEGRITY
	ErrorTicket    ErrorCode = errorCode1Start + 0x20 // TPM_RC_TICKET

	// ErroReservedBits corresponds to TPM_RC_RESERVED_BITS and is returned as a *TPMParameterError
	// error for a command that accepts a parameter type corresponding to a TPMA prefixed type if the
	// parameter value has reserved bits set.
	ErrorReservedBits ErrorCode = errorCode1Start + 0x21

	// ErrorBadAuth corresponds to TPM_RC_BAD_AUTH and is returned as a *TPMSessionError error for a
	// command if an authorization check fails and the authorized entity is exempt from dictionary
	// attack protections.
	ErrorBadAuth ErrorCode = errorCode1Start + 0x22

	// ErrorExpired corresponds to TPM_RC_EXPIRED and is returned as a *TPMSessionError error for a
	// command if a policy session is used for authorization, and the session has expired.
	ErrorExpired ErrorCode = errorCode1Start + 0x23

	// ErrorPolicyCC corresponds to TPM_RC_POLICY_CC and is returned as a *TPMSessionError error for
	// a command if a policy session is used for authorization, the session includes a
	// TPM2_PolicyCommandCode assertion, but the command code doesn't match the command for which the
	// authorization is being used for.
	ErrorPolicyCC ErrorCode = errorCode1Start + 0x24

	ErrorBinding ErrorCode = errorCode1Start + 0x25 // TPM_RC_BINDING

	// ErrorCurve corresponds to TPM_RC_CURVE and is returned as a *TPMParameterError for a command
	// that accepts a ECCCurve parameter if the parameter value is incorrect.
	ErrorCurve ErrorCode = errorCode1Start + 0x26

	ErrorECCPoint ErrorCode = errorCode1Start + 0x27 // TPM_RC_ECC_POINT

	ErrorFWLimited ErrorCode = errorCode1Start + 0x28 // TPM_RC_FW_LIMITED

	ErrorSVNLimited ErrorCode = errorCode1Start + 0x29 // TPM_RC_SVN_LIMITED
)

func (ErrorCode) Format

func (e ErrorCode) Format(s fmt.State, f rune)

func (ErrorCode) String

func (e ErrorCode) String() string

type Event

type Event []byte

Event corresponds to the TPM2B_EVENT type. The largest size of this is indicated by EventMaxSize.

type Handle

type Handle uint32

Handle corresponds to the TPM_HANDLE type, and is a numeric identifier that references a resource on the TPM.

const (
	HandleOwner              Handle = 0x40000001 // TPM_RH_OWNER
	HandleNull               Handle = 0x40000007 // TPM_RH_NULL
	HandleUnassigned         Handle = 0x40000008 // TPM_RH_UNASSIGNED
	HandlePW                 Handle = 0x40000009 // TPM_RS_PW
	HandleLockout            Handle = 0x4000000a // TPM_RH_LOCKOUT
	HandleEndorsement        Handle = 0x4000000b // TPM_RH_ENDORSEMENT
	HandlePlatform           Handle = 0x4000000c // TPM_RH_PLATFORM
	HandlePlatformNV         Handle = 0x4000000d // TPM_RH_PLATFORM_NV
	HandleFWOwner            Handle = 0x40000140 // TPM_RH_FW_OWNER
	HandleFWEndorsement      Handle = 0x40000141 // TPM_RH_FW_ENDORSEMENT
	HandleFWPlatform         Handle = 0x40000142 // TPM_RH_FW_PLATFORM
	HandleFWNull             Handle = 0x40000143 // TPM_RH_FW_NULL
	HandleSVNOwnerBase       Handle = 0x40010000 // TPM_RH_SVN_OWNER_BASE
	HandleSVNEndorsementBase Handle = 0x40020000 // TPM_RH_SVN_ENDORSEMENT_BASE
	HandleSVNPlatformBase    Handle = 0x40030000 // TPM_RH_SVN_PLATFORM_BASE
	HandleSVNNullBase        Handle = 0x40040000 // TPM_RH_SVN_NULL_BASE
)

func (Handle) Format

func (h Handle) Format(s fmt.State, f rune)

func (Handle) String

func (h Handle) String() string

func (Handle) Type

func (h Handle) Type() HandleType

Type returns the type of the handle.

type HandleContext

type HandleContext interface {
	// Handle returns the handle of the corresponding entity on the TPM. If Dispose has been called
	// then this will return HandleUnassigned.
	Handle() Handle
	Name() Name                        // The name of the entity. This will be empty if there isn't one or Dispose has been called.
	SerializeToBytes() []byte          // Return a byte slice containing the serialized form of this HandleContext
	SerializeToWriter(io.Writer) error // Write the serialized form of this HandleContext to the supplied io.Writer
	Dispose()                          // Called when the corresponding resource has been flushed or evicted from the TPM
}

HandleContext corresponds to an entity that resides on the TPM. Implementations of HandleContext maintain some host-side state in order to be able to participate in sessions. They are invalidated when used in a command that results in the entity being flushed or evicted from the TPM. Once invalidated, they can no longer be used.

func CreateHandleContextFromBytes deprecated

func CreateHandleContextFromBytes(b []byte) (HandleContext, int, error)

CreateHandleContextFromBytes returns a new HandleContext created from the serialized data read from the supplied byte slice. This should contain data that was previously created by HandleContext.SerializeToBytes or HandleContext.SerializeToWriter.

If the supplied data corresponds to a session then a SessionContext will be returned, else a ResourceContext will be returned.

If a ResourceContext is returned and subsequent use of it requires knowledge of the authorization value of the corresponding TPM resource, this should be provided by calling ResourceContext.SetAuthValue.

Deprecated: Use NewHandleContextFromBytes.

func CreateHandleContextFromReader deprecated

func CreateHandleContextFromReader(r io.Reader) (HandleContext, error)

CreateHandleContextFromReader returns a new HandleContext created from the serialized data read from the supplied io.Reader. This should contain data that was previously created by HandleContext.SerializeToBytes or HandleContext.SerializeToWriter.

If the supplied data corresponds to a session then a SessionContext will be returned, else a ResourceContext will be returned.

If a ResourceContext is returned and subsequent use of it requires knowledge of the authorization value of the corresponding TPM resource, this should be provided by calling ResourceContext.SetAuthValue.

Deprecated: Use NewHandleContextFromReader.

func CreatePartialHandleContext deprecated

func CreatePartialHandleContext(handle Handle) HandleContext

CreatePartialHandleContext creates a new HandleContext for the specified handle. The returned HandleContext cannot be type asserted to ResourceContext or SessionContext and can only be used in commands that don't use sessions, such as TPMContext.FlushContext, TPMContext.ReadPublic or TPMContext.NVReadPublic.

This function will panic if handle doesn't correspond to a session, transient or persistent object, or NV index.

Deprecated: Use NewHandleContext.

func NewHandleContext added in v1.7.0

func NewHandleContext(handle Handle) HandleContext

NewHandleContext creates a new HandleContext for the specified handle. The returned HandleContext cannot be type asserted to ResourceContext or SessionContext and can only be used in commands that don't use sessions, such as TPMContext.FlushContext, TPMContext.ReadPublic or TPMContext.NVReadPublic.

This function will panic if handle doesn't correspond to a session, transient or persistent object, or NV index.

func NewHandleContextFromBytes added in v1.1.0

func NewHandleContextFromBytes(b []byte) (HandleContext, int, error)

NewHandleContextFromBytes returns a new HandleContext created from the serialized data read from the supplied byte slice. This should contain data that was previously created by HandleContext.SerializeToBytes or HandleContext.SerializeToWriter.

If the supplied data corresponds to a session then a SessionContext will be returned, else a ResourceContext will be returned.

If a ResourceContext is returned and subsequent use of it requires knowledge of the authorization value of the corresponding TPM resource, this should be provided by calling ResourceContext.SetAuthValue.

func NewHandleContextFromReader added in v1.1.0

func NewHandleContextFromReader(r io.Reader) (HandleContext, error)

NewHandleContextFromReader returns a new HandleContext created from the serialized data read from the supplied io.Reader. This should contain data that was previously created by HandleContext.SerializeToBytes or HandleContext.SerializeToWriter.

If the supplied data corresponds to a session then a SessionContext will be returned, else a ResourceContext will be returned.

If a ResourceContext is returned and subsequent use of it requires knowledge of the authorization value of the corresponding TPM resource, this should be provided by calling ResourceContext.SetAuthValue.

func NewLimitedHandleContext deprecated added in v1.1.0

func NewLimitedHandleContext(handle Handle) HandleContext

NewLimitedHandleContext creates a new HandleContext for the specified handle. The returned HandleContext cannot be type asserted to ResourceContext or SessionContext and can only be used in commands that don't use sessions, such as TPMContext.FlushContext, TPMContext.ReadPublic or TPMContext.NVReadPublic.

This function will panic if handle doesn't correspond to a session, transient or persistent object, or NV index.

Deprecated: use NewHandleContext.

type HandleList

type HandleList []Handle

HandleList is a slice of Handle values, and corresponds to the TPML_HANDLE type.

type HandleType

type HandleType uint8

HandleType corresponds to the TPM_HT type, and is used to identify the type of a Handle.

const (
	HandleTypePCR           HandleType = 0x00 // TPM_HT_PCR
	HandleTypeNVIndex       HandleType = 0x01 // TPM_HT_NV_INDEX
	HandleTypeHMACSession   HandleType = 0x02 // TPM_HT_HMAC_SESSION
	HandleTypeLoadedSession HandleType = 0x02 // TPM_HT_LOADED_SESSION
	HandleTypePolicySession HandleType = 0x03 // TPM_HT_POLICY_SESSION
	HandleTypeSavedSession  HandleType = 0x03 // TPM_HT_SAVED_SESSION
	HandleTypePermanent     HandleType = 0x40 // TPM_HT_PERMANENT
	HandleTypeTransient     HandleType = 0x80 // TPM_HT_TRANSIENT
	HandleTypePersistent    HandleType = 0x81 // TPM_HT_PERSISTENT
)

func (HandleType) BaseHandle

func (h HandleType) BaseHandle() Handle

BaseHandle returns the first handle for the handle type.

type HashAlgorithmId

type HashAlgorithmId AlgorithmId

HashAlgorithmId corresponds to the TPMI_ALG_HASH type

const (
	HashAlgorithmNull         HashAlgorithmId = HashAlgorithmId(AlgorithmNull)         // TPM_ALG_NULL
	HashAlgorithmSHA1         HashAlgorithmId = HashAlgorithmId(AlgorithmSHA1)         // TPM_ALG_SHA1
	HashAlgorithmSHA256       HashAlgorithmId = HashAlgorithmId(AlgorithmSHA256)       // TPM_ALG_SHA256
	HashAlgorithmSHA384       HashAlgorithmId = HashAlgorithmId(AlgorithmSHA384)       // TPM_ALG_SHA384
	HashAlgorithmSHA512       HashAlgorithmId = HashAlgorithmId(AlgorithmSHA512)       // TPM_ALG_SHA512
	HashAlgorithmSHA256_192   HashAlgorithmId = HashAlgorithmId(AlgorithmSHA256_192)   // TPM_ALG_SHA256_192
	HashAlgorithmSM3_256      HashAlgorithmId = HashAlgorithmId(AlgorithmSM3_256)      // TPM_ALG_SM3_256
	HashAlgorithmSHA3_256     HashAlgorithmId = HashAlgorithmId(AlgorithmSHA3_256)     // TPM_ALG_SHA3_256
	HashAlgorithmSHA3_384     HashAlgorithmId = HashAlgorithmId(AlgorithmSHA3_384)     // TPM_ALG_SHA3_384
	HashAlgorithmSHA3_512     HashAlgorithmId = HashAlgorithmId(AlgorithmSHA3_512)     // TPM_ALG_SHA3_512
	HashAlgorithmSHAKE256_192 HashAlgorithmId = HashAlgorithmId(AlgorithmSHAKE256_192) // TPM_ALG_SHAKE256_192
	HashAlgorithmSHAKE256_256 HashAlgorithmId = HashAlgorithmId(AlgorithmSHAKE256_256) // TPM_ALG_SHAKE256_256
	HashAlgorithmSHAKE256_512 HashAlgorithmId = HashAlgorithmId(AlgorithmSHAKE256_512) // TPM_ALG_SHAKE256_512
)

func (HashAlgorithmId) Available

func (a HashAlgorithmId) Available() bool

Available determines if the TPM digest algorithm has an equivalent go crypto.Hash that is linked into the current binary.

func (HashAlgorithmId) Format

func (a HashAlgorithmId) Format(s fmt.State, f rune)

func (HashAlgorithmId) GetHash

func (a HashAlgorithmId) GetHash() crypto.Hash

GetHash returns the equivalent crypto.Hash value for this algorithm if one exists, and 0 if one does not exist.

func (HashAlgorithmId) HashFunc added in v1.1.0

func (a HashAlgorithmId) HashFunc() crypto.Hash

HashFunc implements crypto.SignerOpts.HashFunc.

This will return 0 if the algorithm does not have a corresponding crypto.Hash.

func (HashAlgorithmId) IsValid

func (a HashAlgorithmId) IsValid() bool

IsValid determines if the digest algorithm is valid. This should be checked by code that deserializes an algorithm before calling Size if it does not want to panic.

Note that this does not guarantee that the HashAlgorithmId.GetHash will return a valid corresponding crypto.Hash.

func (HashAlgorithmId) NewHash

func (a HashAlgorithmId) NewHash() hash.Hash

NewHash constructs a new hash.Hash implementation for this algorithm. It will panic if HashAlgorithmId.Available returns false.

func (HashAlgorithmId) Size

func (a HashAlgorithmId) Size() int

Size returns the size of the algorithm. It will panic if HashAlgorithmId.IsValid returns false.

type IDObject added in v1.1.0

type IDObject []byte

IDObject corresponds to the TPM2B_ID_OBJECT type.

type IDObjectRaw deprecated

type IDObjectRaw = IDObject

IDObjectRaw corresponds to the TPM2B_ID_OBJECT type.

Deprecated: use IDObject

type InvalidAuthResponseError added in v0.2.0

type InvalidAuthResponseError struct {
	Index int // Index of the session responsible for this error, starting from 1
	// contains filtered or unexported fields
}

InvalidAuthResponseError is returned from any TPMContext method that executes a TPM command if one of the response auth HMACs is invalid. If this error occurs, session contexts associated with the command that caused this error should be considered invalid.

func (*InvalidAuthResponseError) Error added in v0.2.0

func (e *InvalidAuthResponseError) Error() string

type InvalidResponseCodeError

type InvalidResponseCodeError ResponseCode

InvalidResponseCode is returned from DecodeResponseCode and any TPMContext method that executes a command on the TPM if the TPM response code is invalid.

func (InvalidResponseCodeError) Error

func (e InvalidResponseCodeError) Error() string

type InvalidResponseError

type InvalidResponseError struct {
	Command CommandCode
	// contains filtered or unexported fields
}

InvalidResponseError is returned from any TPMContext method that executes a TPM command if the TPM's response is invalid. Some examples of invalid responses that would result in this error are:

  • The response packet was too large.
  • The response packet could not be unmarshalled.
  • The size field in the response header doesn't match the actual size.
  • The response code and response tag were inconsistent.
  • An error occurred whilst unmarshalling the response auth area or parameters.
  • The response auth area or parameter area have unused bytes after unmarshalling.
  • There were an unexpected number of response auths.
  • A response auth was invalid.

Any session contexts associated with the command that caused this error should be considered invalid.

It is possible that the TPM command completed successfully.

If any function that executes a command which allocates objects on the TPM returns this error, it is possible that these objects were allocated and now exist on the TPM.

If any function that executes a command which makes persistent changes to the TPM returns this error, it is possible that the persistent changes were completed.

func (*InvalidResponseError) Error

func (e *InvalidResponseError) Error() string

func (*InvalidResponseError) Unwrap added in v0.2.0

func (e *InvalidResponseError) Unwrap() error

type KDFAlgorithmId

type KDFAlgorithmId AlgorithmId

KDFAlgorithmId corresppnds to the TPMI_ALG_KDF type

const (
	KDFAlgorithmMGF1           KDFAlgorithmId = KDFAlgorithmId(AlgorithmMGF1)           // TPM_ALG_MGF1
	KDFAlgorithmNull           KDFAlgorithmId = KDFAlgorithmId(AlgorithmNull)           // TPM_ALG_NULL
	KDFAlgorithmKDF1_SP800_56A KDFAlgorithmId = KDFAlgorithmId(AlgorithmKDF1_SP800_56A) // TPM_ALG_KDF1_SP800_56A
	KDFAlgorithmKDF2           KDFAlgorithmId = KDFAlgorithmId(AlgorithmKDF2)           // TPM_ALG_KDF2
	KDFAlgorithmKDF1_SP800_108 KDFAlgorithmId = KDFAlgorithmId(AlgorithmKDF1_SP800_108) // TPM_ALG_KDF1_SP800_108
)

func (KDFAlgorithmId) Format

func (a KDFAlgorithmId) Format(s fmt.State, f rune)

type KDFScheme

type KDFScheme struct {
	Scheme  KDFAlgorithmId // Scheme selector
	Details *KDFSchemeU    // Scheme specific parameters.
}

KDFScheme corresponds to the TPMT_KDF_SCHEME type.

type KDFSchemeU

type KDFSchemeU struct {
	MGF1           *SchemeMGF1
	KDF1_SP800_56A *SchemeKDF1_SP800_56A
	KDF2           *SchemeKDF2
	KDF1_SP800_108 *SchemeKDF1_SP800_108
}

KDFSchemeU is a union type that corresponds to the TPMU_KDF_SCHEME type. The selector type is KDFAlgorithmId. The mapping of selector value to field is as follows:

  • KDFAlgorithmMGF1: MGF1
  • KDFAlgorithmKDF1_SP800_56A: KDF1_SP800_56A
  • KDFAlgorithmKDF2: KDF2
  • KDFAlgorithmKDF1_SP800_108: KDF1_SP800_108
  • KDFAlgorithmNull: none

func (*KDFSchemeU) Select

func (s *KDFSchemeU) Select(selector reflect.Value) interface{}

Select implements mu.Union.

type KeySchemeECDH

type KeySchemeECDH = SchemeHash

type KeySchemeECMQV

type KeySchemeECMQV = SchemeHash

type KeyedHashParams

type KeyedHashParams struct {
	Scheme KeyedHashScheme // Signing method for a keyed hash signing object
}

KeyedHashParams corresponds to the TPMS_KEYEDHASH_PARMS type, and defines the public parameters for a keyedhash object.

type KeyedHashScheme

type KeyedHashScheme struct {
	Scheme  KeyedHashSchemeId // Scheme selector
	Details *SchemeKeyedHashU // Scheme specific parameters
}

KeyedHashScheme corresponds to the TPMT_KEYEDHASH_SCHEME type.

type KeyedHashSchemeId

type KeyedHashSchemeId AlgorithmId

KeyedHashSchemeId corresponds to the TPMI_ALG_KEYEDHASH_SCHEME type

const (
	KeyedHashSchemeHMAC KeyedHashSchemeId = KeyedHashSchemeId(AlgorithmHMAC) // TPM_ALG_HMAC
	KeyedHashSchemeXOR  KeyedHashSchemeId = KeyedHashSchemeId(AlgorithmXOR)  // TPM_ALG_XOR
	KeyedHashSchemeNull KeyedHashSchemeId = KeyedHashSchemeId(AlgorithmNull) // TPM_ALG_NULL
)

func (KeyedHashSchemeId) Format

func (a KeyedHashSchemeId) Format(s fmt.State, f rune)

type Label

type Label []byte

Label corresponds to the TPM2B_LABEL type.

type Locality

type Locality uint8

Locality corresponds to the TPMA_LOCALITY type.

const (
	LocalityZero  Locality = 1 << 0 // TPM_LOC_ZERO
	LocalityOne   Locality = 1 << 1 // TPM_LOC_ONE
	LocalityTwo   Locality = 1 << 2 // TPM_LOC_TWO
	LocalityThree Locality = 1 << 3 // TPM_LOC_THREE
	LocalityFour  Locality = 1 << 4 // TPM_LOC_FOUR
)

func (Locality) IsExtended added in v1.7.0

func (l Locality) IsExtended() bool

IsExtended indicates whether this value represents an extended locality, which is a locality greater than or equal to 32. Note that the Locality type cannot represent localities between 5 and 31.

func (Locality) IsMultiple added in v1.7.0

func (l Locality) IsMultiple() bool

IsMultiple indicates whether this value represents multiple localities. This is only possible for localities 0 to 4.

func (Locality) IsValid added in v1.7.0

func (l Locality) IsValid() bool

IsValid returns whether this value represents one or more valid localities. The zero value does not represent any valid localities.

func (Locality) Value added in v1.7.0

func (l Locality) Value() uint8

Value returns the locality represented by this value as an integer. It will panic if it doesn't represent any valid locality ([IsValid] returns false), or if it represents multiple localities ([IsMultiple] returns true).

func (Locality) Values added in v1.7.0

func (l Locality) Values() []uint8

Values returns the localities represented by this value as a slice of integers.

type MaxBuffer

type MaxBuffer []byte

MaxBuffer corresponds to the TPM2B_MAX_BUFFER type. The largest size of this supported by the TPM can be determined by calling TPMContext.GetInputBuffer.

type MaxNVBuffer

type MaxNVBuffer []byte

MaxNVBuffer corresponds to the TPM2B_MAX_NV_BUFFER type. The largest size of this supported by the TPM can be determined by calling TPMContext.GetNVBufferMax.

type MemoryAttributes

type MemoryAttributes uint32

MemoryAttributes corresponds to the TPMA_MEMORY type and is used to report details about memory management. It is returned when querying the value of PropertyMemory.

const (
	AttrSharedRAM         MemoryAttributes = 1 << 0 // sharedRAM
	AttrSharedNV          MemoryAttributes = 1 << 1 // sharedNV
	AttrObjectCopiedToRAM MemoryAttributes = 1 << 2 // objectCopiedToRam
)

type ModeAttributes

type ModeAttributes uint32

ModeAttributes correspnds to TPMA_MODES and is returned when querying the value of PropertyModes.

const (
	ModeFIPS140_2 ModeAttributes = 1 << 0 // FIPS_140_2
)

type NVAttributes

type NVAttributes uint32

NVAttributes corresponds to the TPMA_NV type, and represents the attributes of a NV index. When exchanged with the TPM, some bits are reserved to encode the type of the NV index (NVType).

const (
	AttrNVPPWrite        NVAttributes = 1 << 0  // TPMA_NV_PPWRITE
	AttrNVOwnerWrite     NVAttributes = 1 << 1  // TPMA_NV_OWNERWRITE
	AttrNVAuthWrite      NVAttributes = 1 << 2  // TPMA_NV_AUTHWRITE
	AttrNVPolicyWrite    NVAttributes = 1 << 3  // TPMA_NV_POLICY_WRITE
	AttrNVPolicyDelete   NVAttributes = 1 << 10 // TPMA_NV_POLICY_DELETE
	AttrNVWriteLocked    NVAttributes = 1 << 11 // TPMA_NV_WRITELOCKED
	AttrNVWriteAll       NVAttributes = 1 << 12 // TPMA_NV_WRITEALL
	AttrNVWriteDefine    NVAttributes = 1 << 13 // TPMA_NV_WRITEDEFINE
	AttrNVWriteStClear   NVAttributes = 1 << 14 // TPMA_NV_WRITE_STCLEAR
	AttrNVGlobalLock     NVAttributes = 1 << 15 // TPMA_NV_GLOBALLOCK
	AttrNVPPRead         NVAttributes = 1 << 16 // TPMA_NV_PPREAD
	AttrNVOwnerRead      NVAttributes = 1 << 17 // TPMA_NV_OWNERREAD
	AttrNVAuthRead       NVAttributes = 1 << 18 // TPMA_NV_AUTHREAD
	AttrNVPolicyRead     NVAttributes = 1 << 19 // TPMA_NV_POLICYREAD
	AttrNVNoDA           NVAttributes = 1 << 25 // TPMA_NV_NO_DA
	AttrNVOrderly        NVAttributes = 1 << 26 // TPMA_NV_ORDERLY
	AttrNVClearStClear   NVAttributes = 1 << 27 // TPMA_NV_CLEAR_STCLEAR
	AttrNVReadLocked     NVAttributes = 1 << 28 // TPMA_NV_READLOCKED
	AttrNVWritten        NVAttributes = 1 << 29 // TPMA_NV_WRITTEN
	AttrNVPlatformCreate NVAttributes = 1 << 30 // TPMA_NV_PLATFORMCREATE
	AttrNVReadStClear    NVAttributes = 1 << 31 // TPMA_NV_READ_STCLEAR
)

func (NVAttributes) AttrsOnly

func (a NVAttributes) AttrsOnly() NVAttributes

AttrsOnly returns the NVAttributes without the encoded NVType.

func (NVAttributes) Type

func (a NVAttributes) Type() NVType

Type returns the NVType encoded in a NVAttributes value.

type NVCertifyInfo

type NVCertifyInfo struct {
	IndexName  Name        // Name of the NV index
	Offset     uint16      // Offset parameter of TPMContext.NVCertify
	NVContents MaxNVBuffer // Contents of the NV index
}

NVCertifyInfo corresponds to the TPMS_NV_CERTIFY_INFO type, and is returned by TPMContext.NVCertify.

type NVIndexContext added in v1.4.0

type NVIndexContext interface {
	ResourceContext

	// Type returns the type of the index
	Type() NVType

	// SetAttr is called when an attribute is set so that the context
	// can update its name.
	SetAttr(a NVAttributes)
}

NVIndexContext is a ResourceContext that corresponds to a NV index.

type NVPinCounterParams

type NVPinCounterParams struct {
	Count uint32
	Limit uint32
}

NVPinCounterParams corresponds to the TPMS_NV_PIN_COUNTER_PARAMETERS type.

type NVPublic

type NVPublic struct {
	Index      Handle          // Handle of the NV index
	NameAlg    HashAlgorithmId // NameAlg is the digest algorithm used to compute the name of the index
	Attrs      NVAttributes    // Attributes of this index
	AuthPolicy Digest          // Authorization policy for this index
	Size       uint16          // Size of this index
}

NVPublic corresponds to the TPMS_NV_PUBLIC type, which describes a NV index.

func (*NVPublic) ComputeName added in v1.0.0

func (p *NVPublic) ComputeName() (Name, error)

Name computes the name of this NV index

func (*NVPublic) Handle deprecated added in v1.1.0

func (p *NVPublic) Handle() Handle

Deprecated: there is currently no use for this.

func (*NVPublic) Name

func (p *NVPublic) Name() Name

Name implements github.com/canonical/go-tpm2/objectutil.Named and github.com/canonical/go-tpm2/policyutil.Named.

This computes the name from the public area. If the name cannot be computed then an invalid name is returned (Name.Type will return NameTypeInvalid).

type NVType

type NVType uint32

NVType corresponds to the TPM_NT type.

const (
	NVTypeOrdinary NVType = 0 // TPM_NT_ORDINARY
	NVTypeCounter  NVType = 1 // TPM_NT_COUNTER
	NVTypeBits     NVType = 2 // TPM_NT_BITS
	NVTypeExtend   NVType = 4 // TPM_NT_EXTEND
	NVTypePinFail  NVType = 8 // TPM_NT_PIN_FAIL
	NVTypePinPass  NVType = 9 // TPM_NT_PIN_PASS
)

func (NVType) WithAttrs

func (t NVType) WithAttrs(attrs NVAttributes) NVAttributes

WithAttrs returns NVAttributes for this type with the specified attributes set.

type Name

type Name []byte

Name corresponds to the TPM2B_NAME type.

func MakeHandleName added in v1.1.0

func MakeHandleName(handle Handle) Name

MakeHandleName creates a Name from the specified handle. This will panic if the specified handle doesn't correspond to a PCR, session or permanent resource.

func (Name) Algorithm

func (n Name) Algorithm() HashAlgorithmId

Algorithm returns the digest algorithm of this name. If Type does not return NameTypeDigest, it will return HashAlgorithmNull.

func (Name) Digest

func (n Name) Digest() Digest

Digest returns the name as a digest without the algorithm identifier. If Type does not return NameTypeDigest, it will panic.

func (Name) Handle

func (n Name) Handle() Handle

Handle returns the handle of the resource that this name corresponds to. If Type does not return NameTypeHandle, it will panic.

func (Name) IsValid added in v0.9.9

func (n Name) IsValid() bool

IsValid determines if this name is valid.

func (Name) Name added in v0.9.9

func (n Name) Name() Name

Name implements github.com/canonical/go-tpm2/objectutil.Named.

func (Name) Type

func (n Name) Type() NameType

Type determines the type of this name.

type NameType

type NameType int

NameType describes the type of a name.

const (
	// NameTypeInvalid means that a Name is invalid.
	NameTypeInvalid NameType = iota

	// NameTypeHandle means that a Name is a handle.
	NameTypeHandle

	// NameTypeDigest means that a Name is a digest.
	NameTypeDigest

	// NameTypeNone means that a Name is empty.
	NameTypeNone
)

type NewCipherFunc

type NewCipherFunc func([]byte) (cipher.Block, error)

type Nonce

type Nonce = Digest

Nonce corresponds to the TPM2B_NONCE type.

type ObjectAttributes

type ObjectAttributes uint32

ObjectAttributes corresponds to the TPMA_OBJECT type, and represents the attributes for an object.

const (
	AttrFixedTPM             ObjectAttributes = 1 << 1  // fixedTPM
	AttrStClear              ObjectAttributes = 1 << 2  // stClear
	AttrFixedParent          ObjectAttributes = 1 << 4  // fixedParent
	AttrSensitiveDataOrigin  ObjectAttributes = 1 << 5  // sensitiveDataOrigin
	AttrUserWithAuth         ObjectAttributes = 1 << 6  // userWithAuth
	AttrAdminWithPolicy      ObjectAttributes = 1 << 7  // adminWithPolicy
	AttrNoDA                 ObjectAttributes = 1 << 10 // noDA
	AttrEncryptedDuplication ObjectAttributes = 1 << 11 // encryptedDuplication
	AttrRestricted           ObjectAttributes = 1 << 16 // restricted
	AttrDecrypt              ObjectAttributes = 1 << 17 // decrypt
	AttrSign                 ObjectAttributes = 1 << 18 // sign
)

type ObjectContext added in v1.4.0

type ObjectContext interface {
	ResourceContext

	// Public is the public area associated with the object. This will return nil
	// if HandleContext.Dispose was called.
	Public() *Public
}

ObjectContext is a ResourceContext that corresponds to an object on the TPM.

type ObjectTypeId

type ObjectTypeId AlgorithmId

ObjectTypeId corresponds to the TPMI_ALG_PUBLIC type.

const (
	ObjectTypeRSA       ObjectTypeId = ObjectTypeId(AlgorithmRSA)       // TPM_ALG_RSA
	ObjectTypeKeyedHash ObjectTypeId = ObjectTypeId(AlgorithmKeyedHash) // TPM_ALG_KEYEDHASH
	ObjectTypeECC       ObjectTypeId = ObjectTypeId(AlgorithmECC)       // TPM_ALG_ECC
	ObjectTypeSymCipher ObjectTypeId = ObjectTypeId(AlgorithmSymCipher) // TPM_ALG_SYMCIPHER
)

func (ObjectTypeId) Format

func (a ObjectTypeId) Format(s fmt.State, f rune)

func (ObjectTypeId) IsAsymmetric

func (t ObjectTypeId) IsAsymmetric() bool

IsAsymmetric determines if the type corresponds to an asymmetric object.

type Operand

type Operand = Digest

Operand corresponds to the TPM2B_OPERAND type.

type PCRSelect

type PCRSelect []int

PCRSelect is a slice of PCR indexes. It makes it easier to work with the TPMS_PCR_SELECT type, which is a bitmap of PCR indices.

This type can't be marshalled directly because there is no mechanism to specify a minimum size.

It should either be converted to and from *PCRSelectBitmap for marshalling or used as part of the PCRSelection type (which makes it possible to specify the minimum size of the bitmap/

func (PCRSelect) Marshal

func (d PCRSelect) Marshal(w io.Writer) error

Marshal implements mu.CustomMarshaller.Marshal.

Note that this type cannot be marshalled directly and will result in a panic if this is attempted.

func (PCRSelect) ToBitmap added in v0.2.0

func (d PCRSelect) ToBitmap(minsize uint8) (out *PCRSelectBitmap, err error)

ToBitmap converts this PCRSelect into its bitmap form, with the specified minimum size. If minsize is zero, a value of 3 will be used which aligns with PC client TPM devices.

func (*PCRSelect) Unmarshal

func (d *PCRSelect) Unmarshal(r io.Reader) error

Unmarshal implements mu.CustomMarshaller.Unmarshal.

type PCRSelectBitmap added in v0.2.0

type PCRSelectBitmap struct {
	Bytes mu.Sized1Bytes
}

PCRSelectBitmap correspnds to the TPMS_PCR_SELECT type, and is a bitmap that defines a selection of PCRs. Note that it is easier to work with the PCRSelect type instead, which is a slice of PCR indexes.

func (*PCRSelectBitmap) ToPCRs added in v0.2.0

func (b *PCRSelectBitmap) ToPCRs() (out PCRSelect)

ToPCRs converts this PCRSelectBitmap to a slice of PCR indexes.

type PCRSelection

type PCRSelection struct {
	Hash   HashAlgorithmId // Hash is the digest algorithm associated with the selection
	Select PCRSelect       // The selected PCRs

	// SizeOfSelect sets the minimum number of bytes in the serialized Select field
	// during marshalling, and is set to the actual number of bytes in the Select
	// field during unmarshalling.
	//
	// TPMs define a minimum size for a PCR selection, based on the number of PCRs
	// defined in its associated platform specification. Note that methods of
	// TPMContext that accept a PCRSelection will set this automatically.
	//
	// If set to zero during marshalling, a value of 3 will be assumed, which
	// aligns with PC client TPM devices.
	SizeOfSelect uint8
}

PCRSelection corresponds to the TPMS_PCR_SELECTION type.

func (PCRSelection) Marshal added in v0.2.0

func (s PCRSelection) Marshal(w io.Writer) error

Marshal implements mu.CustomMarshaller.Marshal.

func (PCRSelection) String added in v1.5.0

func (s PCRSelection) String() string

func (*PCRSelection) Unmarshal added in v0.2.0

func (s *PCRSelection) Unmarshal(r io.Reader) error

Unmarshal implements mu.CustomMarshaller.Unmarshal.

type PCRSelectionList

type PCRSelectionList []PCRSelection

PCRSelectionList is a slice of PCRSelection values, and corresponds to the TPML_PCR_SELECTION type.

func (PCRSelectionList) IsEmpty

func (l PCRSelectionList) IsEmpty() bool

IsEmpty returns true if the list of PCR selections selects no PCRs.

func (PCRSelectionList) Merge

Merge will merge the PCR selections specified by l and r together and return a new set of PCR selections which contains a combination of both. For each PCR found in r that isn't found in l, it will be added to the first occurence of the corresponding PCR bank found in l if that exists, or otherwise a selection for that PCR bank will be appended to the result.

This will return an error if either selection list cannot be marshalled to the TPM wire format.

func (PCRSelectionList) MustMerge added in v0.9.9

func (l PCRSelectionList) MustMerge(r PCRSelectionList) (out PCRSelectionList)

MustMerge will merge the PCR selections specified by l and r together and return a new set of PCR selections which contains a combination of both. For each PCR found in r that isn't found in l, it will be added to the first occurence of the corresponding PCR bank found in l if that exists, or otherwise a selection for that PCR bank will be appended to the result.

This will panic if either selection list cannot be marshalled to the TPM wire format. Use mu.IsValid to check if the values can actually be serialized correctly.

func (PCRSelectionList) MustRemove added in v0.9.9

func (l PCRSelectionList) MustRemove(r PCRSelectionList) (out PCRSelectionList)

MustRemove will remove the PCR selections in r from the PCR selections in l, and return a new set of selections.

This will panic if either selection list cannot be marshalled to the TPM wire format. Use mu.IsValid to check if the values can actually be serialized correctly.

func (PCRSelectionList) MustSort added in v0.9.9

func (l PCRSelectionList) MustSort() (out PCRSelectionList)

MustSort will sort the list of PCR selections in order of ascending algorithm ID. A new list of selections is returned.

This will panic if the selection list cannot be marshalled to the TPM wire format. Use mu.IsValid to check if it can actually be serialized correctly.

func (PCRSelectionList) Remove

Remove will remove the PCR selections in r from the PCR selections in l, and return a new set of selections.

This will return an error if either selection list cannot be marshalled to the TPM wire format.

func (PCRSelectionList) Sort

func (l PCRSelectionList) Sort() (out PCRSelectionList, err error)

Sort will sort the list of PCR selections in order of ascending algorithm ID. A new list of selections is returned.

This will return an error if the selection list cannot be marshalled to the TPM wire format.

func (PCRSelectionList) String added in v1.5.0

func (l PCRSelectionList) String() string

func (PCRSelectionList) WithMinSelectSize added in v0.2.0

func (l PCRSelectionList) WithMinSelectSize(sz uint8) (out PCRSelectionList)

WithMinSelectSize creates a copy of this list of selections with the minimum size of each selection in bytes set to the specified value. If this isn't used to change the default of zero, then 3 is assumed during marshalling which aligns with PC client TPM devices.

Methods of TPMContext that accept a PCRSelectionList call this function already.

type PCRValues

type PCRValues map[HashAlgorithmId]map[int]Digest

PCRValues contains a collection of PCR values, keyed by HashAlgorithmId and PCR index. It can be marshalled to and from the TPM wire format.

func (PCRValues) AddValues added in v0.2.0

func (v PCRValues) AddValues(pcrs PCRSelectionList, digests DigestList) (n int, err error)

AddValues the PCR values from the supplied list of PCR selections and list of values.

func (PCRValues) Marshal added in v0.3.0

func (v PCRValues) Marshal(w io.Writer) error

Marshal implements mu.CustomMarshaller.Marshal.

func (PCRValues) SelectionList

func (v PCRValues) SelectionList() (PCRSelectionList, error)

SelectionList computes a list of PCR selections corresponding to this set of PCR values. This will always return a valid selection or an error.

func (PCRValues) SetValue

func (v PCRValues) SetValue(alg HashAlgorithmId, pcr int, digest Digest) error

SetValue sets the PCR value for the specified PCR and PCR bank.

func (PCRValues) ToListAndSelection

func (v PCRValues) ToListAndSelection() (pcrs PCRSelectionList, digests DigestList, err error)

ToListAndSelection converts this set of PCR values to a list of PCR selections and list of PCR values in a form that can be serialized, although if you want to do that then you can pass PCRValues directly to mu.MarshalToBytes or mu.MarshalToWriter.

func (*PCRValues) Unmarshal added in v0.3.0

func (v *PCRValues) Unmarshal(r io.Reader) error

Unmarshal implements mu.CustomMarshaller.Unmarshal.

type PermanentAttributes

type PermanentAttributes uint32

PermanentAttributes corresponds to the TPMA_PERMANENT type and is returned when querying the value of PropertyPermanent.

const (
	AttrOwnerAuthSet       PermanentAttributes = 1 << 0  // ownerAuthSet
	AttrEndorsementAuthSet PermanentAttributes = 1 << 1  // endorsementAuthSet
	AttrLockoutAuthSet     PermanentAttributes = 1 << 2  // lockoutAuthSet
	AttrDisableClear       PermanentAttributes = 1 << 8  // disableClear
	AttrInLockout          PermanentAttributes = 1 << 9  // inLockout
	AttrTPMGeneratedEPS    PermanentAttributes = 1 << 10 // tpmGeneratedEPS
)

type Private

type Private []byte

Private corresponds to the TPM2B_PRIVATE type.

type PrivateKeyRSA

type PrivateKeyRSA []byte

PrivateKeyRSA corresponds to the TPM2B_PRIVATE_KEY_RSA type.

type PrivateVendorSpecific

type PrivateVendorSpecific []byte

PrivateVendorSpecific corresponds to the TPM2B_PRIVATE_VENDOR_SPECIFIC type.

type Property

type Property uint32

Property corresponds to the TPM_PT type.

const (
	// These constants represent properties that only change when the firmware in the TPM changes.
	PropertyFamilyIndicator   Property = 0x100 // TPM_PT_FAMILY_INDICATOR
	PropertyLevel             Property = 0x101 // TPM_PT_LEVEL
	PropertyRevision          Property = 0x102 // TPM_PT_REVISION
	PropertyDayOfYear         Property = 0x103 // TPM_PT_DAY_OF_YEAR
	PropertyYear              Property = 0x104 // TPM_PT_YEAR
	PropertyManufacturer      Property = 0x105 // TPM_PT_MANUFACTURER
	PropertyVendorString1     Property = 0x106 // TPM_PT_VENDOR_STRING_1
	PropertyVendorString2     Property = 0x107 // TPM_PT_VENDOR_STRING_2
	PropertyVendorString3     Property = 0x108 // TPM_PT_VENDOR_STRING_3
	PropertyVendorString4     Property = 0x109 // TPM_PT_VENDOR_STRING_4
	PropertyVendorTPMType     Property = 0x10a // TPM_PT_VENDOR_TPM_TYPE
	PropertyFirmwareVersion1  Property = 0x10b // TPM_PT_FIRMWARE_VERSION_1
	PropertyFirmwareVersion2  Property = 0x10c // TPM_PT_FIRMWARE_VERSION_2
	PropertyInputBuffer       Property = 0x10d // TPM_PT_INPUT_BUFFER
	PropertyHRTransientMin    Property = 0x10e // TPM_PT_HR_TRANSIENT_MIN
	PropertyHRPersistentMin   Property = 0x10f // TPM_PT_HR_PERSISTENT_MIN
	PropertyHRLoadedMin       Property = 0x110 // TPM_PT_HR_LOADED_MIN
	PropertyActiveSessionsMax Property = 0x111 // TPM_PT_ACTIVE_SESSIONS_MAX
	PropertyPCRCount          Property = 0x112 // TPM_PT_PCR_COUNT
	PropertyPCRSelectMin      Property = 0x113 // TPM_PT_PCR_SELECT_MIN
	PropertyContextGapMax     Property = 0x114 // TPM_PT_CONTEXT_GAP_MAX
	PropertyNVCountersMax     Property = 0x116 // TPM_PT_NV_COUNTERS_MAX
	PropertyNVIndexMax        Property = 0x117 // TPM_PT_NV_INDEX_MAX
	PropertyMemory            Property = 0x118 // TPM_PT_MEMORY
	PropertyClockUpdate       Property = 0x119 // TPM_PT_CLOCK_UPDATE
	PropertyContextHash       Property = 0x11a // TPM_PT_CONTEXT_HASH
	PropertyContextSym        Property = 0x11b // TPM_PT_CONTEXT_SYM
	PropertyContextSymSize    Property = 0x11c // TPM_PT_CONTEXT_SYM_SIZE
	PropertyOrderlyCount      Property = 0x11d // TPM_PT_ORDERLY_COUNT
	PropertyMaxCommandSize    Property = 0x11e // TPM_PT_MAX_COMMAND_SIZE
	PropertyMaxResponseSize   Property = 0x11f // TPM_PT_MAX_RESPONSE_SIZE
	PropertyMaxDigest         Property = 0x120 // TPM_PT_MAX_DIGEST
	PropertyMaxObjectContext  Property = 0x121 // TPM_PT_MAX_OBJECT_CONTEXT
	PropertyMaxSessionContext Property = 0x122 // TPM_PT_MAX_SESSION_CONTEXT
	PropertyPSFamilyIndicator Property = 0x123 // TPM_PT_PS_FAMILY_INDICATOR
	PropertyPSLevel           Property = 0x124 // TPM_PT_PS_LEVEL
	PropertyPSRevision        Property = 0x125 // TPM_PT_PS_REVISION
	PropertyPSDayOfYear       Property = 0x126 // TPM_PT_PS_DAY_OF_YEAR
	PropertyPSYear            Property = 0x127 // TPM_PT_PS_YEAR
	PropertySplitMax          Property = 0x128 // TPM_PT_SPLIT_MAX
	PropertyTotalCommands     Property = 0x129 // TPM_PT_TOTAL_COMMANDS
	PropertyLibraryCommands   Property = 0x12a // TPM_PT_LIBRARY_COMMANDS
	PropertyVendorCommands    Property = 0x12b // TPM_PT_VENDOR_COMMANDS
	PropertyNVBufferMax       Property = 0x12c // TPM_PT_NV_BUFFER_MAX
	PropertyModes             Property = 0x12d // TPM_PT_MODES
	PropertyMaxCapBuffer      Property = 0x12e // TPM_PT_MAX_CAP_BUFFER
	PropertyFirmwareSVN       Property = 0x12f // TPM_PT_FIRMWARE_SVN
	PropertyFirmwareMaxSVN    Property = 0x130 // TPM_PT_FIRMWARE_MAX_SVN

	PropertyFixed Property = PropertyFamilyIndicator
)
const (
	// These constants represent properties that change for reasons other than a firmware upgrade. Some of
	// them may not persist across power cycles.
	PropertyPermanent         Property = 0x200 // TPM_PT_PERMANENT
	PropertyStartupClear      Property = 0x201 // TPM_PT_STARTUP_CLEAR
	PropertyHRNVIndex         Property = 0x202 // TPM_PT_HR_NV_INDEX
	PropertyHRLoaded          Property = 0x203 // TPM_PT_HR_LOADED
	PropertyHRLoadedAvail     Property = 0x204 // TPM_PT_HR_LOADED_AVAIL
	PropertyHRActive          Property = 0x205 // TPM_PT_HR_ACTIVE
	PropertyHRActiveAvail     Property = 0x206 // TPM_PT_HR_ACTIVE_AVAIL
	PropertyHRTransientAvail  Property = 0x207 // TPM_PT_HR_TRANSIENT_AVAIL
	PropertyHRPersistent      Property = 0x208 // TPM_PT_HR_PERSISTENT
	PropertyHRPersistentAvail Property = 0x209 // TPM_PT_HR_PERSISTENT_AVAIL
	PropertyNVCounters        Property = 0x20a // TPM_PT_NV_COUNTERS
	PropertyNVCountersAvail   Property = 0x20b // TPM_PT_NV_COUNTERS_AVAIL
	PropertyAlgorithmSet      Property = 0x20c // TPM_PT_ALGORITHM_SET
	PropertyLoadedCurves      Property = 0x20d // TPM_PT_LOADED_CURVES
	PropertyLockoutCounter    Property = 0x20e // TPM_PT_LOCKOUT_COUNTER
	PropertyMaxAuthFail       Property = 0x20f // TPM_PT_MAX_AUTH_FAIL
	PropertyLockoutInterval   Property = 0x210 // TPM_PT_LOCKOUT_INTERVAL
	PropertyLockoutRecovery   Property = 0x211 // TPM_PT_LOCKOUT_RECOVERY
	PropertyNVWriteRecovery   Property = 0x212 // TPM_PT_NV_WRITE_RECOVERY
	PropertyAuditCounter0     Property = 0x213 // TPM_PT_AUDIT_COUNTER_0
	PropertyAuditCounter1     Property = 0x214 // TPM_PT_AUDIT_COUNTER_1

	PropertyVar Property = PropertyPermanent
)

type PropertyPCR

type PropertyPCR uint32

PropertyPCR corresponds to the TPM_PT_PCR type.

const (
	PropertyPCRSave        PropertyPCR = 0x00 // TPM_PT_PCR_SAVE
	PropertyPCRExtendL0    PropertyPCR = 0x01 // TPM_PT_PCR_EXTEND_L0
	PropertyPCRResetL0     PropertyPCR = 0x02 // TPM_PT_PCR_RESET_L0
	PropertyPCRExtendL1    PropertyPCR = 0x03 // TPM_PT_PCR_EXTEND_L1
	PropertyPCRResetL1     PropertyPCR = 0x04 // TPM_PT_PCR_RESET_L1
	PropertyPCRExtendL2    PropertyPCR = 0x05 // TPM_PT_PCR_EXTEND_L2
	PropertyPCRResetL2     PropertyPCR = 0x06 // TPM_PT_PCR_RESET_L2
	PropertyPCRExtendL3    PropertyPCR = 0x07 // TPM_PT_PCR_EXTEND_L3
	PropertyPCRResetL3     PropertyPCR = 0x08 // TPM_PT_PCR_RESET_L3
	PropertyPCRExtendL4    PropertyPCR = 0x09 // TPM_PT_PCR_EXTEND_L4
	PropertyPCRResetL4     PropertyPCR = 0x0a // TPM_PT_PCR_RESET_L4
	PropertyPCRNoIncrement PropertyPCR = 0x11 // TPM_PT_PCR_NO_INCREMENT
	PropertyPCRDRTMReset   PropertyPCR = 0x12 // TPM_PT_PCR_DRTM_RESET
	PropertyPCRPolicy      PropertyPCR = 0x13 // TPM_PT_PCR_POLICY
	PropertyPCRAuth        PropertyPCR = 0x14 // TPM_PT_PCR_AUTH

	PropertyPCRFirst PropertyPCR = PropertyPCRSave
)

type Public

type Public struct {
	Type       ObjectTypeId     // Type of this object
	NameAlg    HashAlgorithmId  // NameAlg is the algorithm used to compute the name of this object
	Attrs      ObjectAttributes // Object attributes
	AuthPolicy Digest           // Authorization policy for this object
	Params     *PublicParamsU   // Type specific parameters
	Unique     *PublicIDU       // Type specific unique identifier
}

Public corresponds to the TPMT_PUBLIC type, and defines the public area for an object.

func (*Public) AsymDetail added in v1.1.0

func (p *Public) AsymDetail() *AsymParams

AsymDetail returns the asymmetric parameters associated with the object. It panics if it is not an asymmetric key (Public.IsAsymmetric returns false) or if the public area is invalid (mu.IsValid returns false). The public area will be valid if it was constructed by the github.com/canonical/go-tpm2/mu package.

func (*Public) ComputeName added in v1.0.0

func (p *Public) ComputeName() (Name, error)

ComputeName computes the name of this object

func (*Public) IsAsymmetric

func (p *Public) IsAsymmetric() bool

IsAsymmetric indicates that this public area is associated with an asymmetric key.

func (*Public) IsDerivationParent

func (p *Public) IsDerivationParent() bool

IsDerivationParent indicates that this public area is associated with an object that can be a derivation parent.

func (*Public) IsStorageParent

func (p *Public) IsStorageParent() bool

IsStorageParent indicates that this public area is associated with an object that can be a storage parent.

func (*Public) Name

func (p *Public) Name() Name

Name implements github.com/canonical/go-tpm2/objectutil.Named and github.com/canonical/go-tpm2/policyutil.Named.

This computes the name from the public area. If the name cannot be computed then an invalid name is returned (Name.Type will return NameTypeInvalid).

func (*Public) Public

func (p *Public) Public() crypto.PublicKey

Public returns a corresponding public key for the TPM public area. This will panic if the public area does not correspond to an asymmetric key.

func (*Public) ToTemplate

func (p *Public) ToTemplate() (Template, error)

type PublicDerived

type PublicDerived struct {
	Type       ObjectTypeId     // Type of this object
	NameAlg    HashAlgorithmId  // NameAlg is the algorithm used to compute the name of this object
	Attrs      ObjectAttributes // Object attributes
	AuthPolicy Digest           // Authorization policy for this object
	Params     *PublicParamsU   // Type specific parameters

	// Unique contains the derivation values. These take precedence over any values specified
	// in SensitiveCreate.Data when creating a derived object,
	Unique *Derive
}

PublicDerived is similar to Public but can be used as a template to create a derived object with TPMContext.CreateLoaded.

func (*PublicDerived) ComputeName added in v1.0.0

func (p *PublicDerived) ComputeName() (Name, error)

ComputeName computes the name of this object

func (*PublicDerived) Name

func (p *PublicDerived) Name() Name

Name implements github.com/canonical/go-tpm2/objectutil.Named and github.com/canonical/go-tpm2/policyutil.Named.

This computes the name from the public area. If the name cannot be computed then an invalid name is returned (Name.Type will return NameTypeInvalid).

func (*PublicDerived) ToTemplate

func (p *PublicDerived) ToTemplate() (Template, error)

type PublicIDU

type PublicIDU struct {
	KeyedHash Digest
	Sym       Digest
	RSA       PublicKeyRSA
	ECC       *ECCPoint
}

PublicIDU is a union type that corresponds to the TPMU_PUBLIC_ID type. The selector type is ObjectTypeId. The mapping of selector values to fields is as follows:

  • ObjectTypeRSA: RSA
  • ObjectTypeKeyedHash: KeyedHash
  • ObjectTypeECC: ECC
  • ObjectTypeSymCipher: Sym

func (*PublicIDU) Select

func (p *PublicIDU) Select(selector reflect.Value) interface{}

Select implements mu.Union.

type PublicKeyRSA

type PublicKeyRSA []byte

PublicKeyRSA corresponds to the TPM2B_PUBLIC_KEY_RSA type.

type PublicParams

type PublicParams struct {
	Type       ObjectTypeId   // Type specifier
	Parameters *PublicParamsU // Algorithm details
}

PublicParams corresponds to the TPMT_PUBLIC_PARMS type.

type PublicParamsU

type PublicParamsU struct {
	KeyedHashDetail *KeyedHashParams
	SymDetail       *SymCipherParams
	RSADetail       *RSAParams
	ECCDetail       *ECCParams
}

PublicParamsU is a union type that corresponds to the TPMU_PUBLIC_PARMS type. The selector type is ]ObjectTypeId]. The mapping of selector values to fields is as follows:

  • ObjectTypeRSA: RSADetail
  • ObjectTypeKeyedHash: KeyedHashDetail
  • ObjectTypeECC: ECCDetail
  • ObjectTypeSymCipher: SymDetail

func (PublicParamsU) AsymDetail deprecated

func (p PublicParamsU) AsymDetail(t ObjectTypeId) *AsymParams

AsymDetail returns the parameters associated with the specified object type as *AsymParams. It panics if the type is not ObjectTypeRSA or ObjectTypeECC, or the appropriate field isn't set.

Deprecated: Use Public.AsymDetail instead.

func (*PublicParamsU) Select

func (p *PublicParamsU) Select(selector reflect.Value) interface{}

Select implements mu.Union.

type PublicTemplate

type PublicTemplate interface {
	ToTemplate() (Template, error)
}

PublicTemplate exists to allow a type to be marshalled to the Template type.

type QuoteInfo

type QuoteInfo struct {
	PCRSelect PCRSelectionList // PCRs included in PCRDigest
	PCRDigest Digest           // Digest of the selected PCRs, using the hash algorithm of the signing key
}

QuoteInfo corresponds to the TPMS_QUOTE_INFO type, and is returned by TPMContext.Quote.

type RSAParams

type RSAParams struct {
	Symmetric SymDefObject // Symmetric algorithm for a restricted decrypt key.
	// For an unrestricted signing key: AlgorithmRSAPSS, AlgorithmRSASSA or AlgorithmNull.
	// For a restricted signing key: AlgorithmRSAPSS or AlgorithmRSASSA.
	// For an unrestricted decrypt key: AlgorithmRSAES, AlgorithmOAEP or AlgorithmNull.
	// For a restricted decrypt key: AlgorithmNull.
	Scheme   RSAScheme
	KeyBits  uint16 // Number of bits in the public modulus
	Exponent uint32 // Public exponent. When the value is zero, the exponent is 65537
}

RSAParams corresponds to the TPMS_RSA_PARMS type, and defines the public parameters for an RSA key.

type RSAScheme

type RSAScheme struct {
	Scheme  RSASchemeId  // Scheme selector
	Details *AsymSchemeU // Scheme specific parameters.
}

RSAScheme corresponds to the TPMT_RSA_SCHEME type.

func (*RSAScheme) AnyDetails added in v1.1.0

func (s *RSAScheme) AnyDetails() *SchemeHash

AnyDetails returns the details of the RSA scheme. If the scheme is RSASchemeNull, or doesn't have a digest, then nil is returned. If the scheme is not otherwise valid, it will panic.

type RSASchemeId

type RSASchemeId AsymSchemeId

RSASchemeId corresponds to the TPMI_ALG_RSA_SCHEME type.

const (
	RSASchemeNull   RSASchemeId = RSASchemeId(AlgorithmNull)   // TPM_ALG_NULL
	RSASchemeRSASSA RSASchemeId = RSASchemeId(AlgorithmRSASSA) // TPM_ALG_RSASSA
	RSASchemeRSAES  RSASchemeId = RSASchemeId(AlgorithmRSAES)  // TPM_ALG_RSAES
	RSASchemeRSAPSS RSASchemeId = RSASchemeId(AlgorithmRSAPSS) // TPM_ALG_RSAPSS
	RSASchemeOAEP   RSASchemeId = RSASchemeId(AlgorithmOAEP)   // TPM_ALG_OAEP
)

func (RSASchemeId) Format

func (a RSASchemeId) Format(s fmt.State, f rune)

type ResourceContext

type ResourceContext interface {
	HandleContext

	// AuthValue returns the authorization value previously set by SetAuthValue.
	AuthValue() []byte

	// SetAuthValue sets the authorization value that will be used in authorization roles where
	// knowledge of the authorization value is required. Functions that create resources on the TPM
	// and return a ResourceContext will set this automatically, else it will need to be set manually.
	SetAuthValue([]byte)
}

ResourceContext is a HandleContext that corresponds to a non-session entity on the TPM.

func CreateNVIndexResourceContextFromPublic deprecated

func CreateNVIndexResourceContextFromPublic(pub *NVPublic) (ResourceContext, error)

CreateNVIndexResourceContextFromPublic returns a new ResourceContext created from the provided public area. If subsequent use of the returned ResourceContext requires knowledge of the authorization value of the corresponding TPM resource, this should be provided by calling ResourceContext.SetAuthValue. The returned context can be type asserted to NVIndexContext.

This requires that the associated name algorithm is linked into the current binary.

Deprecated: Use NewNVIndexResourceContextFromPub.

func CreateObjectResourceContextFromPublic deprecated

func CreateObjectResourceContextFromPublic(handle Handle, pub *Public) (ResourceContext, error)

CreateObjectResourceContextFromPub returns a new ResourceContext created from the provided public area. If subsequent use of the returned ResourceContext requires knowledge of the authorization value of the corresponding TPM resource, this should be provided by calling ResourceContext.SetAuthValue. The returned context can be type asserted to ObjectContext.

This requires that the associated name algorithm is linked into the current binary.

Deprecated: Use NewObjectResourceContextFromPub.

func NewLimitedResourceContext deprecated added in v1.1.0

func NewLimitedResourceContext(handle Handle, name Name) ResourceContext

NewLimitedResourceContext creates a new ResourceContext with the specified handle and name. The returned ResourceContext has limited functionality - eg, it cannot bs used in functions that require knowledge of the public area associated with the resource (such as TPMContext.StartAuthSession, and some NV functions that modify the attributes of an index will not update its name. It cannot be type asserted to ObjectContext or NVIndexContext.

If subsequent use of the returned ResourceContext requires knowledge of the authorization value of the corresponding TPM resource, this should be provided by calling ResourceContext.SetAuthValue.

This function will panic if handle doesn't correspond to a transient or persistent object, or an NV index.

Deprecated: use NewResourceContext.

func NewNVIndexResourceContext added in v1.1.0

func NewNVIndexResourceContext(pub *NVPublic, name Name) ResourceContext

NewNVIndexResourceContext returns a new ResourceContext created from the provided public area and associated name. This is useful for creating a ResourceContext for an object that uses a name algorithm that is not available. If subsequent use of the returned ResourceContext requires knowledge of the authorization value of the corresponding TPM resource, this should be provided by calling ResourceContext.SetAuthValue. The returned context can be type asserted to NVIndexContext.

This does not check the consistency of the name and public area.

It will panic if the Index field of the supplied public area has a handle type other than HandleTypeNVIndex.

func NewNVIndexResourceContextFromPub added in v1.1.0

func NewNVIndexResourceContextFromPub(pub *NVPublic) (ResourceContext, error)

NewNVIndexResourceContextFromPub returns a new ResourceContext created from the provided public area. If subsequent use of the returned ResourceContext requires knowledge of the authorization value of the corresponding TPM resource, this should be provided by calling ResourceContext.SetAuthValue. The returned context can be type asserted to NVIndexContext.

This requires that the associated name algorithm is linked into the current binary.

func NewObjectResourceContext added in v1.1.0

func NewObjectResourceContext(handle Handle, pub *Public, name Name) ResourceContext

NewObjectResourceContext returns a new ResourceContext created from the provided public area and associated name. This is useful for creating a ResourceContext for an object that uses a name algorithm that is not available. If subsequent use of the returned ResourceContext requires knowledge of the authorization value of the corresponding TPM resource, this should be provided by calling ResourceContext.SetAuthValue. The returned context can be type asserted to ObjectContext.

This does not check the consistency of the name and public area.

This will panic if the handle type is not HandleTypeTransient or HandleTypePersistent.

func NewObjectResourceContextFromPub added in v1.1.0

func NewObjectResourceContextFromPub(handle Handle, pub *Public) (ResourceContext, error)

NewObjectResourceContextFromPub returns a new ResourceContext created from the provided public area. If subsequent use of the returned ResourceContext requires knowledge of the authorization value of the corresponding TPM resource, this should be provided by calling ResourceContext.SetAuthValue. The returned context can be type asserted to ObjectContext.

This requires that the associated name algorithm is linked into the current binary.

func NewResourceContext added in v1.7.0

func NewResourceContext(handle Handle, name Name) ResourceContext

NewResourceContext creates a new ResourceContext with the specified handle and name. The returned ResourceContext has limited functionality - eg, it cannot bs used in functions that require knowledge of the public area associated with the resource (such as TPMContext.StartAuthSession), and some NV functions that modify the attributes of an index will not update its name. It cannot be type asserted to ObjectContext or NVIndexContext.

If subsequent use of the returned ResourceContext requires knowledge of the authorization value of the corresponding TPM resource, this should be provided by calling ResourceContext.SetAuthValue.

This function will panic if handle doesn't correspond to a transient or persistent object, or an NV index.

type ResourceUnavailableError

type ResourceUnavailableError struct {
	Handle Handle
	// contains filtered or unexported fields
}

ResourceUnavailableError is returned from TPMContext.NewResourceContext if it is called with a handle that does not correspond to a resource that is available on the TPM. This could be because the resource doesn't exist on the TPM, or it lives within a hierarchy that is disabled.

func (*ResourceUnavailableError) Error

func (e *ResourceUnavailableError) Error() string

func (*ResourceUnavailableError) Is

func (e *ResourceUnavailableError) Is(target error) bool

func (*ResourceUnavailableError) Unwrap added in v1.7.7

func (e *ResourceUnavailableError) Unwrap() error

type ResponseCode

type ResponseCode uint32

ResponseCode corresponds to the TPM_RC type.

const (
	ResponseSuccess ResponseCode = 0
	ResponseBadTag  ResponseCode = 0x1e
)

func (ResponseCode) E

func (rc ResponseCode) E() uint8

E returns the E field of the response code, corresponding to the error number.

func (ResponseCode) F

func (rc ResponseCode) F() bool

F returns the F field of the response code, corresponding to the format. If it is set, this is a format-one response code. If it is not set, this is a format-zero response code.

func (ResponseCode) N

func (rc ResponseCode) N() uint8

N returns the N field of the response code and is only relevant for format-one response codes. If the P field is set then this indicates the parameter number from 0x1 to 0xf. If the P field is not set then the lower 3 bits indicate the handle or session number (0x1 to 0x7 for handles and 0x9 to 0xf for sessions).

This will panic if the F field is not set.

func (ResponseCode) P

func (rc ResponseCode) P() bool

P returns the P field of the response code and is only relevant for format-one response codes. If this is set then the code is associated with a command parameter. If it is not set then the code is associated with a command handle or session.

This will panic if the F field is not set.

func (ResponseCode) S

func (rc ResponseCode) S() bool

S returns the S field of the response code, corresponding to the severity and is only relevant for format-zero response codes. If this is set then the code indicates a warning. If it is not set then the code indicates an error.

This will panic if the F field is set.

func (ResponseCode) T

func (rc ResponseCode) T() bool

T returns the T field of the response code, corresponding to the TCG/Vendor indicator and is only relevant for format-zero response codes. If this is set then the code is defined by the TPM vendor. If it is not set then the code is defined by the TCG.

This will panic if the F field is set.

func (ResponseCode) V

func (rc ResponseCode) V() bool

V returns the V field of the response code, corresponding to the version and is only relevant for format-zero response codes. If this is set then it is a TPM2 code returned when the response tag is TPM_ST_NO_SESSIONS. If it is not set then it is a TPM1.2 code returned when the response tag is TPM_TAG_RSP_COMMAND.

This will panic if the F field is set.

type ResponseContext added in v0.2.0

type ResponseContext struct {
	// contains filtered or unexported fields
}

ResponseContext contains the context required to validate a response and obtain response parameters.

func (*ResponseContext) Complete added in v0.2.0

func (c *ResponseContext) Complete(responseParams ...interface{}) error

Complete performs validation of the response auth area and updates internal SessionContext state. If a response HMAC is invalid, an error will be returned. The caller supplies a command dependent number of pointers to the response parameters.

If a SessionContext supplied to the original CommandContext has the AttrResponseEncrypt attribute set, then the first response parameter will be decrypted using the properties of that SessionContext.

type ResponseHeader

type ResponseHeader struct {
	Tag          StructTag
	ResponseSize uint32
	ResponseCode ResponseCode
}

ResponseHeader is the header for the TPM's response to a command.

type ResponsePacket deprecated

type ResponsePacket []byte

ResponsePacket corresponds to a complete response packet including header and payload.

Deprecated: use ReadResponsePacket.

func (ResponsePacket) Unmarshal deprecated

func (p ResponsePacket) Unmarshal(handle *Handle) (rc ResponseCode, parameters []byte, authArea []AuthResponse, err error)

Unmarshal deserializes the response packet and returns the response code, handle, parameters and auth area. The parameters will still be in the TPM wire format. The caller supplies a pointer to which the response handle will be written. The pointer must be supplied if the command returns a handle, and must be nil if the command does not return a handle, else the response will be incorrectly unmarshalled.

Deprecated: use ReadResponsePacket.

type SchemeECDAA

type SchemeECDAA struct {
	HashAlg HashAlgorithmId // Hash algorithm used to digest the message
	Count   uint16
}

SchemeECDAA corresponds to the TPMS_SCHEME_ECDAA type.

type SchemeHMAC

type SchemeHMAC = SchemeHash

SchemeHMAC corresponds to the TPMS_SCHEME_HMAC type.

type SchemeHash

type SchemeHash struct {
	HashAlg HashAlgorithmId // Hash algorithm used to digest the message
}

SchemeHash corresponds to the TPMS_SCHEME_HASH type, and is used for schemes that only require a hash algorithm to complete their definition.

type SchemeKDF1_SP800_108

type SchemeKDF1_SP800_108 = SchemeHash

type SchemeKDF1_SP800_56A

type SchemeKDF1_SP800_56A = SchemeHash

type SchemeKDF2

type SchemeKDF2 = SchemeHash

type SchemeKeyedHashU

type SchemeKeyedHashU struct {
	HMAC *SchemeHMAC
	XOR  *SchemeXOR
}

SchemeKeyedHashU is a union type that corresponds to the TPMU_SCHEME_KEYED_HASH type. The selector type is KeyedHashSchemeId. The mapping of selector values to fields is as follows:

  • KeyedHashSchemeHMAC: HMAC
  • KeyedHashSchemeXOR: XOR
  • KeyedHashSchemeNull: none

func (*SchemeKeyedHashU) Select

func (d *SchemeKeyedHashU) Select(selector reflect.Value) interface{}

Select implements mu.Union.

type SchemeMGF1

type SchemeMGF1 = SchemeHash

type SchemeXOR

type SchemeXOR struct {
	HashAlg HashAlgorithmId // Hash algorithm used to digest the message
	KDF     KDFAlgorithmId  // Hash algorithm used for the KDF
}

SchemeXOR corresponds to the TPMS_SCHEME_XOR type, and is used to define the XOR encryption scheme.

type Sensitive

type Sensitive struct {
	Type      ObjectTypeId         // Same as the corresponding Type in the Public object
	AuthValue Auth                 // Authorization value
	SeedValue Digest               // For a parent object, the seed value for protecting descendant objects
	Sensitive *SensitiveCompositeU // Type specific private data
}

Sensitive corresponds to the TPMT_SENSITIVE type.

func (*Sensitive) AnySensitive added in v1.1.0

func (s *Sensitive) AnySensitive() PrivateVendorSpecific

type SensitiveCompositeU

type SensitiveCompositeU struct {
	RSA  PrivateKeyRSA
	ECC  ECCParameter
	Bits SensitiveData
	Sym  SymKey
}

SensitiveCompositeU is a union type that corresponds to the TPMU_SENSITIVE_COMPOSITE type. The selector type is ObjectTypeId. The mapping of selector values to fields is as follows:

  • ObjectTypeRSA: RSA
  • ObjectTypeECC: ECC
  • ObjectTypeKeyedHash: Bits
  • ObjectTypeSymCipher: Sym

func (SensitiveCompositeU) Any deprecated

Any returns the value associated with the specified object type as PrivateVendorSpecific.

Deprecated: Use Sensitive.AnySensitive instead.

func (*SensitiveCompositeU) Select

func (s *SensitiveCompositeU) Select(selector reflect.Value) interface{}

Select implements mu.Union.

type SensitiveCreate

type SensitiveCreate struct {
	UserAuth Auth          // Authorization value
	Data     SensitiveData // Secret data
}

SensitiveCreate corresponds to the TPMS_SENSITIVE_CREATE type and is used to define the values to be placed in the sensitive area of a created object.

type SensitiveData

type SensitiveData []byte

SensitiveData corresponds to the TPM2B_SENSITIVE_DATA type.

type SessionAttributes

type SessionAttributes uint8

SessionAttributes corresponds to the TPMA_SESSION type, and represents the attributes for a session.

const (
	// AttrContinueSession corresponds to continueSession and specifies that the session should not be flushed
	// from the TPM after it is used. If a session is used without this flag, it will be flushed from the TPM
	// after the command completes successfully. In this case, the HandleContext associated with the session
	// will be invalidated.
	AttrContinueSession SessionAttributes = 1 << iota

	// AttrAuditExclusive corresponds to auditExclusive and indicates that the command should only be executed
	// if the session is exclusive at the start of the command. A session becomes exclusive when it is used for
	// auditing for the first time, or if the AttrAuditReset attribute is provided. A session will remain
	// exclusive until the TPM executes any command where the exclusive session isn't used for auditing, if
	// that command allows for audit sessions to be provided.
	//
	// Setting this on SessionContext implies AttrAudit.
	AttrAuditExclusive

	// AttrAuditReset corresponds to auditReset and indicates that the audit digest of the session should be reset.
	// The session will subsequently become exclusive. A session will remain exclusive until the TPM executes any
	// command where the exclusive session isn't used for auditing, if that command allows for audit sessions to be
	// provided.
	//
	// Setting this on SessionContext implies AttrAudit.
	AttrAuditReset

	// AttrCommandEncrypt corresponds to decrypt and specifies that the session should be used for encryption of the
	// first command parameter before being sent from the host to the TPM. This can only be used for parameters that
	// have types corresponding to TPM2B prefixed TCG types, and requires a session that was configured with a valid
	// symmetric algorithm via the symmetric argument of TPMContext.StartAuthSession.
	AttrCommandEncrypt SessionAttributes = 1 << (iota + 2)

	// AttrResponseEncrypt corresponds to encrypt and specifies that the session should be used for encryption of the
	// first response parameter before being sent from the TPM to the host. This can only be used for parameters that
	// have types corresponding to TPM2B prefixed TCG types, and requires a session that was configured with a valid
	// symmetric algorithm via the symmetric argument of TPMContext.StartAuthSession. This package automatically
	// decrypts the received encrypted response parameter.
	AttrResponseEncrypt

	// AttrAudit corresponds to audit and indicates that the session should be used for auditing. If this is the first
	// time that the session is used for auditing, then this attribute will result in the session becoming exclusive.
	// A session will remain exclusive until the TPM executes any command where the exclusive session isn't used for
	// auditing, if that command allows for audit sessions to be provided.
	AttrAudit
)

type SessionAuditInfo

type SessionAuditInfo struct {
	// ExclusiveSession indicates the current exclusive status of the session. It is true if all of the commands recorded in
	// SessionDigest were executed without any intervening commands that did not use
	// the audit session.
	ExclusiveSession bool
	SessionDigest    Digest // Current value of the session audit digest
}

SessionAuditInfo corresponds to the TPMS_SESSION_AUDIT_INFO type, and is returned by TPMContext.GetSessionAuditDigest.

type SessionContext

type SessionContext interface {
	HandleContext

	// Params returns a copy of the session parameters. This will return a default
	// value (with HashAlg == HashAlgorithmNull) if the context was created via
	// NewLimitedHandleContext or HandleContext.Dispose was called.
	Params() SessionContextParams

	// State provides access to read and modify the session state. This will return
	// nil if the context was created via NewLimitedHandleContext or
	// HandleContext.Dispose was called.
	State() *SessionContextState

	// Deprecated: Use Params
	HashAlg() HashAlgorithmId

	// Deprecated: Use State
	NonceTPM() Nonce

	// Deprecated: Use State
	IsAudit() bool

	// Deprecated: Use State
	IsExclusive() bool

	Attrs() SessionAttributes                         // The attributes associated with this session
	SetAttrs(attrs SessionAttributes)                 // Set the attributes that will be used for this SessionContext
	WithAttrs(attrs SessionAttributes) SessionContext // Return a duplicate of this SessionContext with the specified attributes

	// IncludeAttrs returns a duplicate of this SessionContext and its attributes with the specified attributes included.
	IncludeAttrs(attrs SessionAttributes) SessionContext
	// ExcludeAttrs returns a duplicate of this SessionContext and its attributes with the specified attributes excluded.
	ExcludeAttrs(attrs SessionAttributes) SessionContext
}

SessionContext is a HandleContext that corresponds to a session on the TPM.

type SessionContextParams added in v1.4.0

type SessionContextParams struct {
	HashAlg     HashAlgorithmId // The session's digest algorithm
	IsBound     bool            // Whether the session is bound.
	BoundEntity Name            // The bound entity
	Symmetric   SymDef          // The session's symmetric algorithm
	SessionKey  []byte          // The session key
}

SessionContextParams corresponds to the parameters of a session.

type SessionContextState added in v1.4.0

type SessionContextState struct {
	NonceTPM       Nonce // The most recent TPM nonce value
	IsAudit        bool  // Whether the session is currently an audit session
	IsExclusive    bool  // Whether the session is currently an exclusive audit session
	NeedsPassword  bool  // Whether a policy session includes the TPM2_PolicyPassword assertion
	NeedsAuthValue bool  // Whether a policy session includes the TPM2_PolicyAuthValue assertion
}

SessionContextState corresponds to the state of a session.

type SessionType

type SessionType uint8

SessionType corresponds to the TPM_SE type.

const (
	SessionTypeHMAC   SessionType = 0x00 // TPM_SE_HMAC
	SessionTypePolicy SessionType = 0x01 // TPM_SE_POLICY
	SessionTypeTrial  SessionType = 0x03 // TPM_SE_TRIAL
)

type SigScheme

type SigScheme struct {
	Scheme  SigSchemeId // Scheme selector
	Details *SigSchemeU // Scheme specific parameters
}

SigScheme corresponds to the TPMT_SIG_SCHEME type.

func (*SigScheme) AnyDetails added in v1.1.0

func (s *SigScheme) AnyDetails() *SchemeHash

AnyDetails returns the details of the signature scheme. If the scheme is SigSchemeAlgNull, then nil is returned. If the scheme is not otherwise valid, it will panic.

type SigSchemeECDAA

type SigSchemeECDAA = SchemeECDAA

type SigSchemeECDSA

type SigSchemeECDSA = SchemeHash

type SigSchemeECSchnorr

type SigSchemeECSchnorr = SchemeHash

type SigSchemeEDDSA added in v1.7.7

type SigSchemeEDDSA = SchemeHash

type SigSchemeEDDSA_PH added in v1.7.7

type SigSchemeEDDSA_PH = SchemeHash

type SigSchemeId

type SigSchemeId AlgorithmId

SigSchemeId corresponds to the TPMI_ALG_SIG_SCHEME type

const (
	SigSchemeAlgHMAC      SigSchemeId = SigSchemeId(AlgorithmHMAC)      // TPM_ALG_HMAC
	SigSchemeAlgNull      SigSchemeId = SigSchemeId(AlgorithmNull)      // TPM_ALG_NULL
	SigSchemeAlgRSASSA    SigSchemeId = SigSchemeId(AlgorithmRSASSA)    // TPM_ALG_RSASSA
	SigSchemeAlgRSAPSS    SigSchemeId = SigSchemeId(AlgorithmRSAPSS)    // TPM_ALG_RSAPSS
	SigSchemeAlgECDSA     SigSchemeId = SigSchemeId(AlgorithmECDSA)     // TPM_ALG_ECDSA
	SigSchemeAlgECDAA     SigSchemeId = SigSchemeId(AlgorithmECDAA)     // TPM_ALG_ECDAA
	SigSchemeAlgSM2       SigSchemeId = SigSchemeId(AlgorithmSM2)       // TPM_ALG_SM2
	SigSchemeAlgECSchnorr SigSchemeId = SigSchemeId(AlgorithmECSchnorr) // TPM_ALG_ECSCHNORR
	SigSchemeAlgEDDSA     SigSchemeId = SigSchemeId(AlgorithmEDDSA)     // TPM_ALG_EDDSA
	SigSchemeAlgEDDSA_PH  SigSchemeId = SigSchemeId(AlgorithmEDDSA_PH)  // TPM_ALG_EDDSA
	SigSchemeAlgLMS       SigSchemeId = SigSchemeId(AlgorithmLMS)       // TPM_ALG_LMS
	SigSchemeAlgXMSS      SigSchemeId = SigSchemeId(AlgorithmXMSS)      // TPM_ALG_XMSS
)

func (SigSchemeId) Format

func (a SigSchemeId) Format(s fmt.State, f rune)

func (SigSchemeId) IsValid

func (s SigSchemeId) IsValid() bool

IsValid determines if the scheme is a valid signature scheme.

type SigSchemeRSAPSS

type SigSchemeRSAPSS = SchemeHash

type SigSchemeRSASSA

type SigSchemeRSASSA = SchemeHash

type SigSchemeSM2

type SigSchemeSM2 = SchemeHash

type SigSchemeU

type SigSchemeU struct {
	RSASSA    *SigSchemeRSASSA
	RSAPSS    *SigSchemeRSAPSS
	ECDSA     *SigSchemeECDSA
	ECDAA     *SigSchemeECDAA
	SM2       *SigSchemeSM2
	ECSchnorr *SigSchemeECSchnorr
	EDDSA     *SigSchemeEDDSA
	EDDSA_PH  *SigSchemeEDDSA_PH
	HMAC      *SchemeHMAC
}

SigSchemeU is a union type that corresponds to the TPMU_SIG_SCHEME type. The selector type is SigSchemeId. The mapping of selector value to fields is as follows:

  • SigSchemeAlgRSASSA: RSASSA
  • SigSchemeAlgRSAPSS: RSAPSS
  • SigSchemeAlgECDSA: ECDSA
  • SigSchemeAlgECDAA: ECDAA
  • SigSchemeAlgSM2: SM2
  • SigSchemeAlgECSchnorr: ECSchnorr
  • SigSchemeAlgEDDSA: EDDSA
  • SigSchemeAlgEDDSA_PH: EDDSA_PH
  • SigSchemeAlgHMAC: HMAC
  • SigSchemeAlgNull: none

func (SigSchemeU) Any deprecated

func (s SigSchemeU) Any(scheme SigSchemeId) *SchemeHash

Any returns the signature scheme associated with scheme as a *SchemeHash. It panics if the specified scheme is invalid (SigSchemeId.IsValid returns false), or the appropriate field isn't set.

Deprecated: Use SigScheme.AnyDetails instead.

func (*SigSchemeU) Select

func (s *SigSchemeU) Select(selector reflect.Value) interface{}

Select implements mu.Union.

type Signature

type Signature struct {
	SigAlg    SigSchemeId // Signature algorithm
	Signature *SignatureU // Actual signature
}

Signature corresponds to the TPMT_SIGNATURE type which represents a signature.

func (*Signature) HashAlg added in v1.1.0

func (s *Signature) HashAlg() HashAlgorithmId

HashAlg returns the digest algorithm used to create the signature. This will panic if the signature algorithm is not valid (SigSchemeId.IsValid returns false) or if the signature structure is otherwise invalid (mu.IsValid returns false). The signature structure will be valid if it was constructed by the github.com/canonical/go-tpm2/mu package.

type SignatureECC

type SignatureECC struct {
	Hash       HashAlgorithmId // Hash is the digest algorithm used in the signature process
	SignatureR ECCParameter
	SignatureS ECCParameter
}

SignatureECC corresponds to the TPMS_SIGNATURE_ECC type.

type SignatureECDAA

type SignatureECDAA = SignatureECC

type SignatureECDSA

type SignatureECDSA = SignatureECC

type SignatureECSchnorr

type SignatureECSchnorr = SignatureECC

type SignatureEDDSA added in v1.7.7

type SignatureEDDSA = SignatureECC

type SignatureEDDSA_PH added in v1.7.7

type SignatureEDDSA_PH = SignatureECC

type SignatureRSA

type SignatureRSA struct {
	Hash HashAlgorithmId // Hash algorithm used to digest the message
	Sig  PublicKeyRSA    // Signature, which is the same size as the public key
}

SignatureRSA corresponds to the TPMS_SIGNATURE_RSA type.

type SignatureRSAPSS

type SignatureRSAPSS = SignatureRSA

type SignatureRSASSA

type SignatureRSASSA = SignatureRSA

type SignatureSM2

type SignatureSM2 = SignatureECC

type SignatureU

type SignatureU struct {
	RSASSA    *SignatureRSASSA
	RSAPSS    *SignatureRSAPSS
	ECDSA     *SignatureECDSA
	ECDAA     *SignatureECDAA
	SM2       *SignatureSM2
	ECSchnorr *SignatureECSchnorr
	EDDSA     *SignatureEDDSA
	EDDSA_PH  *SignatureEDDSA_PH
	HMAC      *TaggedHash
}

SignatureU is a union type that corresponds to TPMU_SIGNATURE. The selector type is SigSchemeId. The mapping of selector values to fields is as follows:

  • SigSchemeAlgRSASSA: RSASSA
  • SigSchemeAlgRSAPSS: RSAPSS
  • SigSchemeAlgECDSA: ECDSA
  • SigSchemeAlgECDAA: ECDAA
  • SigSchemeAlgSM2: SM2
  • SigSchemeAlgECSchnorr: ECSchnorr
  • SigSchemeAlgEDDSA: EDDSA
  • SigSchemeAlgEDDSA_PH: EDDSA_PH
  • SigSchemeAlgHMAC: HMAC
  • SigSchemeAlgNull: none

func (SignatureU) Any deprecated

func (s SignatureU) Any(scheme SigSchemeId) *SchemeHash

Any returns the signature associated with scheme as a *SchemeHash. It panics if scheme is SigSchemeAlgNull or the appropriate field isn't set.

Deprecated: Use [Signature.Digest] instead.

func (*SignatureU) Select

func (s *SignatureU) Select(selector reflect.Value) interface{}

Select implements mu.Union.

type StartupClearAttributes

type StartupClearAttributes uint32

StatupClearAttributes corresponds to the TPMA_STARTUP_CLEAR type and is used to report details of properties that reset after a Startup(CLEAR). It is returned when querying the value of PropertyStartupClear.

const (
	AttrPhEnable   StartupClearAttributes = 1 << 0  // phEnable
	AttrShEnable   StartupClearAttributes = 1 << 1  // shEnable
	AttrEhEnable   StartupClearAttributes = 1 << 2  // ehEnable
	AttrPhEnableNV StartupClearAttributes = 1 << 3  // phEnableNV
	AttrOrderly    StartupClearAttributes = 1 << 31 // orderly
)

type StartupType

type StartupType uint16

StartupType corresponds to the TPM_SU type.

const (
	StartupClear StartupType = iota
	StartupState
)

type StructTag

type StructTag uint16

StructTag corresponds to the TPM_ST type.

const (
	TagRspCommand StructTag = 0x00c4 // TPM_ST_RSP_COMMAND

	TagNoSessions         StructTag = 0x8001 // TPM_ST_NO_SESSIONS
	TagSessions           StructTag = 0x8002 // TPM_ST_SESSIONS
	TagAttestNV           StructTag = 0x8014 // TPM_ST_ATTEST_NV
	TagAttestCommandAudit StructTag = 0x8015 // TPM_ST_ATTEST_COMMAND_AUDIT
	TagAttestSessionAudit StructTag = 0x8016 // TPM_ST_ATTEST_SESSION_AUDIT
	TagAttestCertify      StructTag = 0x8017 // TPM_ST_ATTEST_CERTIFY
	TagAttestQuote        StructTag = 0x8018 // TPM_ST_ATTEST_QUOTE
	TagAttestTime         StructTag = 0x8019 // TPM_ST_ATTEST_TIME
	TagAttestCreation     StructTag = 0x801a // TPM_ST_ATTEST_CREATION
	TagCreation           StructTag = 0x8021 // TPM_ST_CREATION
	TagVerified           StructTag = 0x8022 // TPM_ST_VERIFIED
	TagAuthSecret         StructTag = 0x8023 // TPM_ST_AUTH_SECRET
	TagHashcheck          StructTag = 0x8024 // TPM_ST_HASHCHECK
	TagAuthSigned         StructTag = 0x8025 // TPM_ST_AUTH_SIGNED
)

type SymAlgorithmId

type SymAlgorithmId AlgorithmId

SymAlgorithmId corresponds to the TPMI_ALG_SYM type

const (
	SymAlgorithmTDES     SymAlgorithmId = SymAlgorithmId(AlgorithmTDES)     // TPM_ALG_TDES
	SymAlgorithmAES      SymAlgorithmId = SymAlgorithmId(AlgorithmAES)      // TPM_ALG_AES
	SymAlgorithmXOR      SymAlgorithmId = SymAlgorithmId(AlgorithmXOR)      // TPM_ALG_XOR
	SymAlgorithmNull     SymAlgorithmId = SymAlgorithmId(AlgorithmNull)     // TPM_ALG_NULL
	SymAlgorithmSM4      SymAlgorithmId = SymAlgorithmId(AlgorithmSM4)      // TPM_ALG_SM4
	SymAlgorithmCamellia SymAlgorithmId = SymAlgorithmId(AlgorithmCamellia) // TPM_ALG_CAMELLIA
)

func (SymAlgorithmId) Available

func (a SymAlgorithmId) Available() bool

Available indicates whether the TPM symmetric cipher has a registered go implementation.

func (SymAlgorithmId) BlockSize

func (a SymAlgorithmId) BlockSize() int

BlockSize indicates the block size of the symmetric cipher. This will panic if SymAlgorithmId.IsValidBlockCipher returns false.

func (SymAlgorithmId) Format

func (a SymAlgorithmId) Format(s fmt.State, f rune)

func (SymAlgorithmId) IsValidBlockCipher

func (a SymAlgorithmId) IsValidBlockCipher() bool

IsValidBlockCipher determines if this algorithm is a valid block cipher. This should be checked by code that deserializes an algorithm before calling SymAlgorithmId.BlockSize if it does not want to panic.

func (SymAlgorithmId) NewCipher

func (a SymAlgorithmId) NewCipher(key []byte) (cipher.Block, error)

NewCipher constructs a new symmetric cipher with the supplied key, if there is a go implementation registered.

type SymCipherParams

type SymCipherParams struct {
	Sym SymDefObject
}

SymCipherParams corresponds to the TPMS_SYMCIPHER_PARMS type, and contains the parameters for a symmetric object.

type SymDef

type SymDef struct {
	Algorithm SymAlgorithmId // Symmetric algorithm
	KeyBits   *SymKeyBitsU   // Symmetric key size
	Mode      *SymModeU      // Symmetric mode
}

SymDef corresponds to the TPMT_SYM_DEF type, and is used to select the algorithm used for parameter encryption.

type SymDefObject

type SymDefObject struct {
	Algorithm SymObjectAlgorithmId // Symmetric algorithm
	KeyBits   *SymKeyBitsU         // Symmetric key size
	Mode      *SymModeU            // Symmetric mode
}

SymDefObject corresponds to the TPMT_SYM_DEF_OBJECT type, and is used to define an object's symmetric algorithm.

type SymKey

type SymKey []byte

SymKey corresponds to the TPM2B_SYM_KEY type.

type SymKeyBitsU

type SymKeyBitsU struct {
	Sym uint16
	XOR HashAlgorithmId
}

SymKeyBitsU is a union type that corresponds to the TPMU_SYM_KEY_BITS type and is used to specify symmetric encryption key sizes. The selector type is AlgorithmId. Mapping of selector values to fields is as follows:

  • AlgorithmAES: Sym
  • AlgorithmSM4: Sym
  • AlgorithmCamellia: Sym
  • AlgorithmXOR: XOR
  • AlgorithmNull: none

func (*SymKeyBitsU) Select

func (b *SymKeyBitsU) Select(selector reflect.Value) interface{}

Select implements mu.Union.

type SymModeId

type SymModeId AlgorithmId

SymModeId corresponds to the TPMI_ALG_SYM_MODE type

const (
	SymModeNull SymModeId = SymModeId(AlgorithmNull) // TPM_ALG_NULL
	SymModeCTR  SymModeId = SymModeId(AlgorithmCTR)  // TPM_ALG_CTR
	SymModeOFB  SymModeId = SymModeId(AlgorithmOFB)  // TPM_ALG_OFB
	SymModeCBC  SymModeId = SymModeId(AlgorithmCBC)  // TPM_ALG_CBC
	SymModeCFB  SymModeId = SymModeId(AlgorithmCFB)  // TPM_ALG_CFB
	SymModeECB  SymModeId = SymModeId(AlgorithmECB)  // TPM_ALG_ECB
)

func (SymModeId) Format

func (a SymModeId) Format(s fmt.State, f rune)

type SymModeU

type SymModeU struct {
	Sym SymModeId
}

SymModeU is a union type that corresponds to the TPMU_SYM_MODE type. The selector type is AlgorithmId. The mapping of selector values to fields is as follows:

  • AlgorithmAES: Sym
  • AlgorithmSM4: Sym
  • AlgorithmCamellia: Sym
  • AlgorithmXOR: none
  • AlgorithmNull: none

func (*SymModeU) Select

func (m *SymModeU) Select(selector reflect.Value) interface{}

Select implements mu.Union.

type SymObjectAlgorithmId

type SymObjectAlgorithmId AlgorithmId

SymObjectAlgorithmId corresponds to the TPMI_ALG_SYM_OBJECT type

const (
	SymObjectAlgorithmAES      SymObjectAlgorithmId = SymObjectAlgorithmId(AlgorithmAES)      // TPM_ALG_AES
	SymObjectAlgorithmNull     SymObjectAlgorithmId = SymObjectAlgorithmId(AlgorithmNull)     // TPM_ALG_NULL
	SymObjectAlgorithmSM4      SymObjectAlgorithmId = SymObjectAlgorithmId(AlgorithmSM4)      // TPM_ALG_SM4
	SymObjectAlgorithmCamellia SymObjectAlgorithmId = SymObjectAlgorithmId(AlgorithmCamellia) // TPM_ALG_CAMELLIA
)

func (SymObjectAlgorithmId) Available

func (a SymObjectAlgorithmId) Available() bool

Available indicates whether the TPM symmetric cipher has a registered go implementation.

func (SymObjectAlgorithmId) BlockSize

func (a SymObjectAlgorithmId) BlockSize() int

BlockSize indicates the block size of the symmetric cipher. This will panic if SymObjectAlgorithmId.IsValidBlockCipher returns false.

func (SymObjectAlgorithmId) Format

func (a SymObjectAlgorithmId) Format(s fmt.State, f rune)

func (SymObjectAlgorithmId) IsValidBlockCipher

func (a SymObjectAlgorithmId) IsValidBlockCipher() bool

IsValidBlockCipher determines if this algorithm is a valid block cipher. This should be checked by code that deserializes an algorithm before calling SymObjectAlgorithmId.BlockSize if it does not want to panic.

func (SymObjectAlgorithmId) NewCipher

func (a SymObjectAlgorithmId) NewCipher(key []byte) (cipher.Block, error)

NewCipher constructs a new symmetric cipher with the supplied key, if there is a go implementation registered.

type TCTI deprecated

type TCTI = Transport

TCTI represents a communication channel to a TPM implementation.

Deprecated: use Transport instead.

type TPMContext

type TPMContext struct {
	// contains filtered or unexported fields
}

TPMContext is the main entry point by which commands are executed on a TPM device using this package. It provides convenience functions for supported commands and communicates with the underlying device via a Transport implementation, which is obtained from a tpm2.TPMDevice implementation provided to OpenTPMDevice.

Convenience functions are wrappers around TPMContext.StartCommand, which may be used directly for custom commands or commands that aren't supported directly by this package.

Methods that execute commands on the TPM may return errors from the TPM where a command responds with a ResponseCode other than ResponseSuccess. These errors are in the form of *TPMError, *TPMWarning, *TPMHandleError, *TPMSessionError, *TPMParameterError and *TPMVendorError types.

Some commands make use of resources on the TPM, and use of these resources may require authorization with one of 3 roles depending on the command: user, admin or duplication. The role determines the required authorization type (passphrase, HMAC session, or policy session), which is dependent on the type of the resource.

Commands that make use of resources on the TPM accept command handle arguments. Convenience methods generally use ResourceContext to represent these.

Convenience methods that require authorization for a ResourceContext provide an associated SessionContext argument to represent a session. Setting this to nil specifies passphrase authorization. A HMAC or policy session can be used by supplying a SessionContext associated with a session of the corresponding type.

If the authorization value of a resource is required as part of the authorization (eg, for passphrase authorization, a HMAC session that is not bound to the specified resource, or a policy session that contains the TPM2_PolicyPassword or TPM2_PolicyAuthValue assertion), it is obtained from the ResourceContext supplied to the method and should be set by calling ResourceContext.SetAuthValue before the method is called.

Where a command requires authorization with the user role for a resource, the following authorization types are permitted:

  • HandleTypePCR: passphrase or HMAC session if no auth policy is set, or a policy session if an auth policy is set.
  • HandleTypeNVIndex: passphrase, HMAC session or policy session depending on attributes.
  • HandleTypePermanent: passphrase or HMAC session. A policy session can also be used if an auth policy is set.
  • HandleTypeTransient / HandleTypePersistent: policy session. Passphrase or HMAC session can also be used if [AttrWithUserAuth] is set.

Where a command requires authorization with the admin role for a resource, the following authorization types are permitted:

Where a command requires authorization with the duplication role for a resource, a policy session is required.

Where a policy session is used for a resource that requires authorization with the admin or duplication role, the session must contain the TPM2_PolicyCommandCode assertion.

Some convenience methods also accept a variable number of optional SessionContext arguments - these are for sessions that don't provide authorization for a corresponding TPM resource. These sessions may be used for the purposes of session based parameter encryption or command auditing.

TPMContext is not safe to use concurrently from multiple goroutines.

Example (CleartextPassphraseAuth)
// Change the authorization value for the storage hierarchy using
// a cleartext passphrase for authorization.

oldPassphrase := []byte("passphrase")
newPassphrase := []byte("esarhpssap")

device, err := linux.DefaultTPM2Device()
if err != nil {
	fmt.Fprintln(os.Stderr, err)
	return
}
tpm, err := tpm2.OpenTPMDevice(device)
if err != nil {
	fmt.Fprintln(os.Stderr, err)
	return
}
defer tpm.Close()

tpm.OwnerHandleContext().SetAuthValue(oldPassphrase)

// Change the new authorization value. Note that we don't pass
// in a session argument - TPMContext creates a password session
// automatically. Both the old and new passphrases are sent to the
// TPM in cleartext.
if err := tpm.HierarchyChangeAuth(tpm.OwnerHandleContext(), newPassphrase, nil); err != nil {
	fmt.Fprintln(os.Stderr, err)
	return
}
Output:

Example (HMACSessionAuth)
// Change the authorization value for the storage hierarchy using
// a HMAC session for authorization.

oldPassphrase := []byte("passphrase")
newPassphrase := []byte("esarhpssap")

device, err := linux.DefaultTPM2Device()
if err != nil {
	fmt.Fprintln(os.Stderr, err)
	return
}
tpm, err := tpm2.OpenTPMDevice(device)
if err != nil {
	fmt.Fprintln(os.Stderr, err)
	return
}
defer tpm.Close()

// Create an unbounded, unsalted HMAC session.
session, err := tpm.StartAuthSession(nil, nil, tpm2.SessionTypeHMAC, nil, tpm2.HashAlgorithmSHA256)
if err != nil {
	fmt.Fprintln(os.Stderr, err)
	return
}
defer tpm.FlushContext(session)

tpm.OwnerHandleContext().SetAuthValue(oldPassphrase)

// Change the authorization value. Note that we pass in the HMAC session
// context. The current passphrase is not sent to the TPM - it is used to
// derive the key used to create a command HMAC, which is then verified on
// the TPM. The new passphrase is sent to the TPM in cleartext.
if err := tpm.HierarchyChangeAuth(tpm.OwnerHandleContext(), newPassphrase, session); err != nil {
	fmt.Fprintln(os.Stderr, err)
	return
}
Output:

Example (PolicySessionAuth)
// Change the authorization value of an existing NV index at handle 0x0180000 using a
// policy session for authorization. The policy for the index asserts that the caller
// must know the existing authorization value.

handle := tpm2.Handle(0x01800000)
oldPassphrase := []byte("passphrase")
newPassphrase := []byte("esarhpssap")

device, err := linux.DefaultTPM2Device()
if err != nil {
	fmt.Fprintln(os.Stderr, err)
	return
}
tpm, err := tpm2.OpenTPMDevice(device)
if err != nil {
	fmt.Fprintln(os.Stderr, err)
	return
}
defer tpm.Close()

index, err := tpm.NewResourceContext(handle)
if err != nil {
	fmt.Fprintln(os.Stderr, err)
	return
}

session, err := tpm.StartAuthSession(nil, nil, tpm2.SessionTypePolicy, nil, tpm2.HashAlgorithmSHA256)
if err != nil {
	fmt.Fprintln(os.Stderr, err)
	return
}
defer tpm.FlushContext(session)

if err := tpm.PolicyCommandCode(session, tpm2.CommandNVChangeAuth); err != nil {
	fmt.Fprintln(os.Stderr, err)
	return
}
if err := tpm.PolicyAuthValue(session); err != nil {
	fmt.Fprintln(os.Stderr, err)
	return
}

index.SetAuthValue(oldPassphrase)

if err := tpm.NVChangeAuth(index, newPassphrase, session); err != nil {
	fmt.Fprintln(os.Stderr, err)
	return
}
Output:

func NewTPMContext deprecated

func NewTPMContext(transport Transport) *TPMContext

NewTPMContext creates a new instance of TPMContext, which communicates with the TPM using the transmission interface provided via the transport parameter. The transmission interface must not be nil - it is expected that the caller checks the error returned from the function that is/ used to create it.

Deprecated: Use OpenTPMDevice instead.

func OpenTPMDevice added in v1.1.0

func OpenTPMDevice(device TPMDevice) (*TPMContext, error)

OpenTPMDevice opens the supplied TPM device and returns a new instance of TPMContext which communicates with the device using the newly opened communication channel.

Example (Linux)
// Open the default Linux TPM2 character device.

device, err := linux.DefaultTPM2Device()
if err != nil {
	fmt.Fprintln(os.Stderr, err)
	return
}
tpm, err := tpm2.OpenTPMDevice(device)
if err != nil {
	fmt.Fprintln(os.Stderr, err)
	return
}
defer tpm.Close()

// Use TPMContext
// ...
Output:

Example (Simulator)
// Open the TPM simulator on the default port (2321).

tpm, err := tpm2.OpenTPMDevice(mssim.DefaultDevice)
if err != nil {
	fmt.Fprintln(os.Stderr, err)
	return
}
defer tpm.Close()

// Use TPMContext
// ...
Output:

func (*TPMContext) ActivateCredential

func (t *TPMContext) ActivateCredential(activateContext, keyContext ResourceContext, credentialBlob IDObject, secret EncryptedSecret, activateContextAuthSession, keyContextAuthSession SessionContext, sessions ...SessionContext) (certInfo Digest, err error)

ActivateCredential executes the TPM2_ActivateCredential command to associate a credential with the object associated with activateContext.

The activateContext parameter corresponds to an object to which credentialBlob is to be associated. It would typically be an attestation key, and the credential issuer would have validated that this object has the expected properties of an attestation key (it is a restricted, non-duplicable signing key) before issuing the credential. Authorization with the admin role is required for activateContext, with session based authorization provided via activateContextAuthSession.

The credentialBlob is an encrypted and integrity protected credential (see section 24 - "Credential Protection" of Part 1 of the Trusted Platform Module Library specification). The secret parameter is used by the private part of the key associated with keyContext in order to recover the seed used to protect the credential.

The keyContext parameter corresponds to an asymmetric restricted decrypt. It is typically an endorsement key, and the credential issuer would have verified that it is a valid endorsement key by verifying the associated endorsement certificate. Authorization with the user auth role is required for keyContext, with session based authorization provided via keyContextAuthSession.

If keyContext does not correspond to an asymmetric restricted decrypt key, a *TPMHandleError error with an error code of ErrorType is returned for handle index 2.

If recovering the seed from secret fails, a *TPMParameterError error with an error code of ErrorScheme, ErrorValue, ErrorSize or ErrorECCPoint may be returned for parameter index 2.

If the integrity value or IV for credentialBlob cannot be unmarshalled correctly or any other errors occur during unmarshalling of credentialBlob, a *TPMParameterError error with an error code of either ErrorSize or ErrorInsufficient will be returned for parameter index 1. If the integrity check of credentialBlob fails, a *TPMParameterError error with an error code of ErrorIntegrity will be returned for parameter index 1. If the size of the IV for credentialBlob doesn't match the block size for the encryption algorithm, a *TPMParameterError error with an error code of ErrorValue will be returned for parameter index 1.

On success, the decrypted credential is returned. This is typically used to decrypt a certificate associated with activateContext, or provide a response to a challenge provided by the credential issuer.

func (*TPMContext) Certify

func (t *TPMContext) Certify(objectContext, signContext ResourceContext, qualifyingData Data, inScheme *SigScheme, objectContextAuthSession, signContextAuthSession SessionContext, sessions ...SessionContext) (certifyInfo *Attest, signature *Signature, err error)

Certify executes the TPM2_Certify command, which is used to prove that an object with a specific name is loaded in to the TPM. By producing an attestation, the TPM certifies that the object with a given name is loaded in to the TPM and consistent with a valid sensitive area.

The objectContext parameter corresponds to the object for which to produce an attestation. The command requires authorization with the admin role for objectContext, with session based authorization provided via objectContextAuthSession.

If signContext is not nil, the returned attestation will be signed by the key associated with it. This command requires authorization with the user auth role for signContext, with session based authorization provided via signContextAuthSession.

If signContext is not nil and the object associated with signContext is not a signing key, a *TPMHandleError error with an error code of ErrorKey will be returned for handle index 2.

If signContext is not nil and if the scheme of the key associated with signContext is AsymSchemeNull, then inScheme must be provided to specify a valid signing scheme for the key. If it isn't, a *TPMParameterError error with an error code of ErrorScheme will be returned for parameter index 2.

If signContext is not nil and the scheme of the key associated with signContext is not AsymSchemeNull, then inScheme may be nil. If it is provided, then the specified scheme must match that of the signing key, else a *TPMParameterError error with an error code of ErrorScheme will be returned for parameter index 2.

If successful, it returns an attestation structure detailing the name of the object associated with objectContext. If signContext is not nil, the attestation structure will be signed by the associated key and returned too.

func (*TPMContext) CertifyCreation

func (t *TPMContext) CertifyCreation(signContext, objectContext ResourceContext, qualifyingData Data, creationHash Digest, inScheme *SigScheme, creationTicket *TkCreation, signContextAuthSession SessionContext, sessions ...SessionContext) (certifyInfo *Attest, signature *Signature, err error)

CertifyCreation executes the TPM2_CertifyCreation command, which is used to prove the association between the object represented by objectContext and its creation data represented by creationHash. It does this by computing a ticket from creationHash and the name of the object represented by objectContext and then verifying that it matches the provided creationTicket, which was provided by the TPM at object creation time.

If signContext is not nil, the returned attestation will be signed by the key associated with it. This command requires authorization with the user auth role for signContext, with session based authorization provided via signContextAuthSession.

If signContext is not nil and the object associated with signContext is not a signing key, a *TPMHandleError error with an error code of ErrorKey will be returned for handle index 1.

If signContext is not nil and if the scheme of the key associated with signContext is AsymSchemeNull, then inScheme must be provided to specify a valid signing scheme for the key. If it isn't, a *TPMParameterError error with an error code of ErrorScheme will be returned for parameter index 3.

If signContext is not nil and the scheme of the key associated with signContext is not AsymSchemeNull, then inScheme may be nil. If it is provided, then the specified scheme must match that of the signing key, else a *TPMParameterError error with an error code of ErrorScheme will be returned for parameter index 3.

If creationTicket corresponds to an invalid ticket, a *TPMParameterError error with an error code of ErrorTicket will be returned for parameter index 4.

If the digest generated for signing is greater than or has a larger size than the modulus of the key associated with signContext, a *TPMError with an error code of ErrorValue will be returned.

If successful, it returns an attestation structure. If signContext is not nil, the attestation structure will be signed by the associated key and returned too.

func (*TPMContext) Clear

func (t *TPMContext) Clear(authContext ResourceContext, authContextAuthSession SessionContext, sessions ...SessionContext) error

Clear executes the TPM2_Clear command to remove all context associated with the current owner. The command requires knowledge of the authorization value for either the platform or lockout hierarchy. The hierarchy is specified by passing a ResourceContext corresponding to either HandlePlatform or HandleLockout to authContext. The command requires authorization with the user auth role for authContext, with session based authorization provided via authContextAuthSession.

On successful completion, all NV indices and objects associated with the current owner will have been evicted and subsequent use of ResourceContext instances associated with these resources will fail. The authorization values of the storage, endorsement and lockout hierarchies will have been cleared. It isn't necessary to update the corresponding ResourceContext instances for these by calling ResourceContext.SetAuthValue in order to use them in subsequent commands that require knowledge of the authorization value for those permanent resources.

If the TPM2_Clear command has been disabled, a *TPMError error will be returned with an error code of ErrorDisabled.

func (*TPMContext) ClearControl

func (t *TPMContext) ClearControl(authContext ResourceContext, disable bool, authContextAuthSession SessionContext, sessions ...SessionContext) error

ClearControl executes the TPM2_ClearControl command to enable or disable execution of the TPM2_Clear command (via the TPMContext.Clear function).

If disable is true, then this command will disable the execution of TPM2_Clear. In this case, the command requires knowledge of the authorization value for the platform or lockout hierarchy. The hierarchy is specified via the authContext parameter by passing a ResourceContext corresponding to either HandlePlatform or HandleLockout.

If disable is false, then this command will enable execution of TPM2_Clear. In this case, the command requires knowledge of the authorization value for the platform hierarchy, and authContext must be a ResourceContext corresponding to HandlePlatform. If authContext is a ResourceContext corresponding to HandleLockout, a *TPMError error with an error code of ErrorAuthFail will be returned.

The command requires the authorization with the user auth role for authContext, with session based authorization provided via authContextAuthSession.

func (*TPMContext) Close

func (t *TPMContext) Close() error

Close calls Close on the transmission interface.

func (*TPMContext) ContextLoad

func (t *TPMContext) ContextLoad(context *Context) (loadedContext HandleContext, err error)

ContextLoad executes the TPM2_ContextLoad command with the supplied Context, in order to restore a context previously saved from TPMContext.ContextSave.

Note that the context blob returned from TPMContext.ContextSave wraps the context blob returned from the TPM with some host-side state that can be used by this function to reconstruct a HandleContext. This function expects a context structure created by TPMContext.ContextSave as opposed to one created directly by the TPM2_ContextSave command on the TPM.

If the size field of the integrity HMAC in the unwrapped context blob is greater than the size of the largest digest algorithm, a *TPMError with an error code of ErrorSize is returned. If the unwrapped context blob is shorter than the indicated size of the integrity HMAC, a *TPMError error with an error code of ErrorInsufficient is returned.

If the size of the integrity HMAC in the unwrapped context blob does not match the size of the context integrity digest algorithm for the TPM, or the unwrapped context blob is too short, a *TPMParameterError error with an error code of ErrorSize is returned.

If the integrity HMAC check for the context including the unwrapped blob fails, a *TPMParameterError with an error code of ErrorIntegrity will be returned.

If the hierarchy that the context is part of is disabled, a *TPMParameterError error with an error code of ErrorHierarchy will be returned.

If the context corresponds to a session but the handle doesn't reference a saved session or the sequence number is invalid, a *TPMParameterError error with an error code of ErrorHandle will be returned.

If the context corresponds to a session and no more sessions can be created until the oldest session is context loaded, and context doesn't correspond to the oldest session, a *TPMWarning error with a warning code of WarningContextGap will be returned.

If there are no more slots available for objects or loaded sessions, a *TPMWarning error with a warning code of either WarningSessionMemory or WarningObjectMemory will be returned.

On successful completion, it returns a HandleContext which corresponds to the resource loaded in to the TPM. The returned context will be equivalent to the HandleContext originally passed to TPMContext.ContextSave.

func (*TPMContext) ContextSave

func (t *TPMContext) ContextSave(saveContext HandleContext) (context *Context, err error)

ContextSave executes the TPM2_ContextSave command on the handle referenced by saveContext, in order to save the context associated with that handle outside of the TPM. The TPM encrypts and integrity protects the context with a key derived from the hierarchy proof. If saveContext does not correspond to a transient object or a session, then it will return an error.

On successful completion, it returns a Context structure that can be passed to TPMContext.ContextLoad. Note that this function wraps the context blob returned from the TPM with some host-side state associated with the resource, so that it can be restored fully in TPMContext.ContextLoad. This means that the context structure cannot be passed directly to the TPM using the TPM2_ContextLoad command, but TPMContext.ContextLoad must be used instead. If saveContext corresponds to a session, the host-side state that is added to the returned context blob includes the session key.

If saveContext corresponds to a session, then TPM2_ContextSave also removes resources associated with the session from the TPM (it becomes a saved session rather than a loaded session). In this case, saveContext can only be used as an argument to TPMContext.FlushContext.

If saveContext corresponds to a session and no more contexts can be saved, a *TPMError error will be returned with an error code of ErrorTooManyContexts. If a context ID cannot be assigned for the session, a *TPMWarning error with a warning code of WarningContextGap will be returned.

func (*TPMContext) Create

func (t *TPMContext) Create(parentContext ResourceContext, inSensitive *SensitiveCreate, inPublic *Public, outsideInfo Data, creationPCR PCRSelectionList, parentContextAuthSession SessionContext, sessions ...SessionContext) (outPrivate Private, outPublic *Public, creationData *CreationData, creationHash Digest, creationTicket *TkCreation, err error)

Create executes the TPM2_Create command to create a new ordinary object as a child of the storage parent associated with parentContext.

The command requires authorization with the user auth role for parentContext, with session based authorization provided via parentContextAuthSession.

A template for the object is provided via the inPublic parameter. The Type field of inPublic defines the algorithm for the object. The NameAlg field defines the digest algorithm for computing the name of the object. The Attrs field defines the attributes of the object. The AuthPolicy field allows an authorization policy to be defined for the new object.

Data that will form part of the sensitive area of the object can be provided via inSensitive, which is optional.

If the Attrs field of inPublic does not have the AttrSensitiveDataOrigin attribute set, then the sensitive data in the created object is initialized with the data provided via the Data field of inSensitive.

If the Attrs field of inPublic has the AttrSensitiveDataOrigin attribute set and Type is ObjectTypeSymCipher, then the sensitive data in the created object is initialized with a TPM generated key. The size of this key is determined by the symmetric algorithm defined in the Params field of inPublic. If Type is ObjectTypeKeyedHash, then the sensitive data in the created object is initialized with a TPM generated value that is the same size as the name algorithm selected by the NameAlg field of inPublic.

If the Type field of inPublic is ObjectTypeRSA or ObjectTypeECC, then the sensitive data in the created object is initialized with a TPM generated private key. The size of this is determined by the asymmetric algorithm defined in the Params field of inPublic.

If the Type field of inPublic is ObjectTypeKeyedHash and the Attrs field has AttrSensitiveDataOrigin, AttrSign and AttrDecrypt all clear, then the created object is a sealed data object.

If the Attrs field of inPublic has the AttrRestricted and AttrDecrypt attributes set, and the Type field is not ObjectTypeKeyedHash, then the newly created object will be a storage parent.

If the Attrs field of inPublic has the AttrRestricted and AttrDecrypt attributes set, and the Type field is ObjectTypeKeyedHash, then the newly created object will be a derivation parent.

The authorization value for the created object is initialized to the value of the UserAuth field of inSensitive.

If the object associated with parentContext is not a valid storage parent object, a *TPMHandleError error with an error code of ErrorType will be returned for handle index 1.

If there are no available slots for new objects on the TPM, a *TPMWarning error with a warning code of WarningObjectMemory will be returned.

If the Attrs field of inPublic as the AttrSensitiveDataOrigin attribute set and the Data field of inSensitive has a non-zero size, or the AttrSensitiveDataOrigin attribute is clear and the Data field of inSensitive has a zero size, a *TPMParameterError error with an error code of ErrorAttributes will be returned for parameter index 1.

If the attributes in the Attrs field of inPublic are inconsistent or inappropriate for the usage, a *TPMParameterError error with an error code of ErrorAttributes will be returned for parameter index 2.

If the NameAlg field of inPublic is HashAlgorithmNull, then a *TPMParameterError error with an error code of ErrorHash will be returned for parameter index 2.

If an authorization policy is defined via the AuthPolicy field of inPublic then the length of the digest must match the name algorithm selected via the NameAlg field, else a *TPMParameterError error with an error code of ErrorSize is returned for parameter index 2.

If the scheme in the Params field of inPublic is inappropriate for the usage, a *TPMParameterError error with an error code of ErrorScheme will be returned for parameter index 2.

If the Type field of inPublic is ObjectTypeRSA, ObjectTypeECC or ObjectTypeKeyedHash and the digest algorithm specified by the scheme in the Params field of inPublic is inappropriate for the usage, a *TPMParameterError error with an error code of ErrorHash will be returned for parameter index 2.

If the Type field of inPublic is not ObjectTypeKeyedHash, a *TPMParameterError error with an error code of ErrorSymmetric will be returned for parameter index 2 if the symmetric algorithm specified in the Params field of inPublic is inappropriate for the usage.

If the Type field of inPublic is ObjectTypeECC and the KDF scheme specified in the Params field of inPublic is not KDFAlgorithmNull, a *TPMParameterError error with an error code of ErrorKDF will be returned for parameter index 2.

If the Type field of inPublic is not ObjectTypeKeyedHash and the AttrRestricted, AttrFixedParent and AttrDecrypt attributes of Attrs are set, a *TPMParameterError error with an error code of ErrorHash will be returned for parameter index 2 if the NameAlg field of inPublic does not select the same name algorithm as the parent object. A *TPMParameterError error with an error code of ErrorSymmetric will be returned for parameter index 2 if the symmetric algorithm specified in the Params field of inPublic does not match the symmetric algorithm of the parent object.

If the length of the UserAuth field of inSensitive is longer than the name algorithm selected by the NameAlg field of inPublic, a *TPMParameterError error with an error code of ErrorSize will be returned for parameter index 1.

If the Type field of inPublic is ObjectTypeRSA and the Params field specifies an unsupported exponent, a *TPMError with an error code of ErrorRange will be returned. If the specified key size is an unsupported value, a *TPMError with an error code of ErrorValue will be returned.

If the Type field of inPublic is ObjectTypeSymCipher and the key size is an unsupported value, a *TPMError with an error code of ErrorKeySize will be returned. If the AttrSensitiveDataOrigin attribute is not set and the length of the Data field of inSensitive does not match the key size specified in the Params field of inPublic, a *TPMError with an error code of ErrorKeySize will be returned.

If the Type field of inPublic is ObjectTypeKeyedHash and the AttrSensitiveDataOrigin attribute is not set, a *TPMError with an error code of ErrorSize will be returned if the length of the Data field of inSensitive is longer than permitted for the digest algorithm selected by the specified scheme.

This function will call TPMContext.InitProperties if it hasn't already been called.

On success, the private and public parts of the newly created object will be returned. The newly created object will not exist on the TPM. If the Type field of inPublic is ObjectTypeKeyedHash or ObjectTypeSymCipher, then the returned *Public object will have a Unique field that is the digest of the sensitive data and the value of the object's seed in the sensitive area, computed using the object's name algorithm. If the Type field of inPublic is ObjectTypeECC or ObjectTypeRSA, then the returned *Public object will have a Unique field containing details about the public part of the key, computed from the private part of the key.

The returned *CreationData will contain a digest computed from the values of PCRs selected by the creationPCR parameter at creation time in the PCRDigest field. It will also contain the provided outsideInfo in the OutsideInfo field. The returned *TkCreation ticket can be used to prove the association between the created object and the returned *CreationData via the TPMContext.CertifyCreation method.

Example (CreatePassphraseProtectedSealedObject)
// Use TPMContext.Create to seal some arbitrary data in a passphrase protected object.

passphrase := []byte("passphrase")
secret := []byte("secret data")

device, err := linux.DefaultTPM2Device()
if err != nil {
	fmt.Fprintln(os.Stderr, err)
	return
}
tpm, err := tpm2.OpenTPMDevice(device)
if err != nil {
	fmt.Fprintln(os.Stderr, err)
	return
}
defer tpm.Close()

// We need a storage parent, eg, the shared SRK. Assume it already exists.
srk, err := tpm.NewResourceContext(0x81000001)
if err != nil {
	fmt.Fprintln(os.Stderr, err)
	return
}

template := objectutil.NewSealedObjectTemplate()

sensitive := &tpm2.SensitiveCreate{
	UserAuth: passphrase,
	Data:     secret}

priv, pub, _, _, _, err := tpm.Create(srk, sensitive, template, nil, nil, nil)
if err != nil {
	fmt.Fprintln(os.Stderr, err)
	return
}

// priv and pub contain the private and public parts of the sealed object,
// and these can be serialized to persistent storage somewhere, or loaded in
// to the TPM with the TPMContext.Load function. The mu/ subpackage can be used
// to serialize them in the TPM wire format.
_ = priv
_ = pub
Output:

func (*TPMContext) CreateLoaded

func (t *TPMContext) CreateLoaded(parentContext ResourceContext, inSensitive *SensitiveCreate, inPublic PublicTemplate, parentContextAuthSession SessionContext, sessions ...SessionContext) (objectContext ResourceContext, outPrivate Private, outPublic *Public, err error)

CreateLoaded executes the TPM2_CreateLoaded command to create a new primary, ordinary or derived object. To create a new primary object, parentContext should correspond to a hierarchy. To create a new ordinary object, parentContext should correspond to a storage parent. To create a new derived object, parentContext should correspond to a derivation parent.

The command requires authorization with the user auth role for parentContext, with session based authorization provided via parentContextAuthSession.

A template for the object is provided via the inPublic parameter. Because of the way that this parameter is handled by the TPM spec, the parameter is an interface that serializes the actual template. The interface is implemented by both the Public and PublicDerived types.

The Type field of the template defines the algorithm for the object. The NameAlg field defines the digest algorithm for computing the name of the object. The Attrs field defines the attributes of the object. The AuthPolicy field allows an authorization policy to be defined for the new object.

Data that will form part of the sensitive area of the object can be provided via inSensitive, which is optional.

If parentContext does not correspond to a derivation parent and the Attrs field of of the template does not have the AttrSensitiveDataOrigin attribute set, then the sensitive data in the created object is initialized with the data provided via the Data field of inSensitive.

If the Attrs field of the template has the AttrSensitiveDataOrigin attribute set and Type is ObjectTypeSymCipher, then the sensitive data in the created object is initialized with a TPM generated key. The size of this key is determined by the symmetric algorithm defined in the Params field of the template. If Type is ObjectTypeKeyedHash, then the sensitive data in the created object is initialized with a TPM generated value that is the same size as the name algorithm selected by the NameAlg field of the template.

If the Type field of the template is ObjectTypeRSA then the sensitive data in the created object is initialized with a TPM generated private key. The size of this is determined by the asymmetric algorithm defined in the Params field of the template.

If the Type field of the template is ObjectTypeECC and parentContext does not correspond to a derivation parent, then the sensitive data in the created object is initialized with a TPM generated private key. The size of this is determined by the asymmetric algorithm defined in the Params field of the template.

If parentContext corresponds to a derivation parent, the sensitive data in the created object is initialized with a value derived from the parent object's private seed, and the derivation values specified in either the Unique field of the template or the Data field of inSensitive.

If the Type field of the template is ObjectTypeKeyedHash, the Attrs field has AttrSensitiveDataOrigin, AttrSign and AttrDecrypt all clear, then the created object is a sealed data object.

If the Attrs field of the template has the AttrRestricted and AttrDecrypt attributes set, and the Type field is not ObjectTypeKeyedHash, then the newly created object will be a storage parent.

If the Attrs field of the template has the AttrRestricted and AttrDecrypt attributes set, and the Type field is ObjectTypeKeyedHash, then the newly created object will be a derivation parent.

The authorization value for the created object is initialized to the value of the UserAuth field of inSensitive.

If parentContext corresponds to an object and it isn't a valid storage parent or derivation parent, *TPMHandleError error with an error code of ErrorType will be returned for handle index 1.

If there are no available slots for new objects on the TPM, a *TPMWarning error with a warning code of WarningObjectMemory will be returned.

If the attributes in the Attrs field of the template are inconsistent or inappropriate for the usage, a *TPMParameterError error with an error code of ErrorAttributes will be returned for parameter index 2.

If the NameAlg field of the template is HashAlgorithmNull, then a *TPMParameterError error with an error code of ErrorHash will be returned for parameter index 2.

If an authorization policy is defined via the AuthPolicy field of the template then the length of the digest must match the name algorithm selected via the NameAlg field, else a *TPMParameterError error with an error code of ErrorSize is returned for parameter index 2.

If the scheme in the Params field of the template is inappropriate for the usage, a *TPMParameterError errow with an error code of ErrorScheme will be returned for parameter index 2.

If the Type field of the template is ObjectTypeRSA, ObjectTypeECC or ObjectTypeKeyedHash and the digest algorithm specified by the scheme in the Params field of the template is inappropriate for the usage, a *TPMParameterError error with an error code of ErrorHash will be returned for parameter index 2.

If the Type field of the template is not ObjectTypeKeyedHash, a *TPMParameterError error with an error code of ErrorSymmetric will be returned for parameter index 2 if the symmetric algorithm specified in the Params field of the template is inappropriate for the usage.

If the Type field of the template is ObjectTypeECC and the KDF scheme specified in the Params field is not KDFAlgorithmNull, a *TPMParameterError error with an error code of ErrorKDF will be returned for parameter index 2.

If the Type field of the template is not ObjectTypeKeyedHash and the AttrRestricted, AttrFixedParent and AttrDecrypt attributes of Attrs are set, a *TPMParameterError error with an error code of ErrorHash will be returned for parameter index 2 if the NameAlg field of the template does not select the same name algorithm as the parent object. A *TPMParameterError error with an error code of ErrorSymmetric will be returned for parameter index 2 if the symmetric algorithm specified in the Params field of the template does not match the symmetric algorithm of the parent object.

If the length of the UserAuth field of inSensitive is longer than the name algorithm selected by the NameAlg field of the template, a *TPMParameterError error with an error code of ErrorSize will be returned for parameter index 1.

If the Type field of the template is ObjectTypeRSA and the Params field specifies an unsupported exponent, a *TPMError with an error code of ErrorRange will be returned. If the specified key size is an unsupported value, a *TPMError with an error code of ErrorValue will be returned.

If the Type field of the template is ObjectTypeSymCipher and the key size is an unsupported value, a *TPMError with an error code of ErrorKeySize will be returned. If the AttrSensitiveDataOrigin attribute is not set and the length of the Data field of inSensitive does not match the key size specified in the Params field of the template, a *TPMError with an error code of ErrorKeySize will be returned.

If the Type field of the template is ObjectTypeKeyedHash and the AttrSensitiveDataOrigin attribute is not set, a *TPMError with an error code of ErrorSize will be returned if the length of the Data field of inSensitive is longer than permitted for the digest algorithm selected by the specified scheme.

On success, a ResourceContext instance will be returned that corresponds to the newly created object on the TPM, along with the private and public parts. It will not be necessary to call ResourceContext.SetAuthValue on the returned ResourceContext - this function sets the correct authorization value so that it can be used in subsequent commands that require knowledge of the authorization value. The returned ResourceContext can be type asserted to ObjectContext. If the Type field of the template is ObjectTypeKeyedHash or ObjectTypeSymCipher, then the returned *Public object will have a Unique field that is the digest of the sensitive data and the value of the object's seed in the sensitive area, computed using the object's name algorithm. If the Type field of the template is ObjectTypeECC or ObjectTypeRSA, then the returned *Public object will have a Unique field containing details about the public part of the key, computed from the private part of the key.

func (*TPMContext) CreatePrimary

func (t *TPMContext) CreatePrimary(primaryObject ResourceContext, inSensitive *SensitiveCreate, inPublic *Public, outsideInfo Data, creationPCR PCRSelectionList, primaryObjectAuthSession SessionContext, sessions ...SessionContext) (objectContext ResourceContext, outPublic *Public, creationData *CreationData, creationHash Digest, creationTicket *TkCreation, err error)

CreatePrimary executes the TPM2_CreatePrimary command to create a new primary object in the hierarchy corresponding to primaryObject.

The primaryObject parameter should correspond to a hierarchy. The command requires authorization with the user auth role for primaryObject, with session based authorization provided via primaryObjectAuthSession.

A template for the object is provided via the inPublic parameter. The Type field of inPublic defines the algorithm for the object. The NameAlg field defines the digest algorithm for computing the name of the object. The Attrs field defines the attributes of the object. The AuthPolicy field allows an authorization policy to be defined for the new object.

Data that will form part of the sensitive area of the object can be provided via inSensitive, which is optional.

If the Attrs field of inPublic does not have the AttrSensitiveDataOrigin attribute set, then the sensitive data in the created object is initialized with the data provided via the Data field of inSensitive.

If the Attrs field of inPublic has the AttrSensitiveDataOrigin attribute set and Type is ObjectTypeSymCipher, then the sensitive data in the created object is initialized with a TPM generated key. The size of this key is determined by the symmetric algorithm defined in the Params field of inPublic. If Type is ObjectTypeKeyedHash, then the sensitive data in the created object is initialized with a TPM generated value that is the same size as the name algorithm selected by the NameAlg field of inPublic.

If the Type field of inPublic is ObjectTypeRSA or ObjectTypeECC, then the sensitive data in the created object is initialized with a TPM generated private key. The size of this is determined by the asymmetric algorithm defined in the Params field of inPublic.

If the Type field of inPublic is ObjectTypeKeyedHash and the Attrs field has AttrSensitiveDataOrigin, AttrSign and AttrDecrypt all clear, then the created object is a sealed data object.

If the Attrs field of inPublic has the AttrRestricted and AttrDecrypt attributes set, and the Type field is not ObjectTypeKeyedHash, then the newly created object will be a storage parent.

If the Attrs field of inPublic has the AttrRestricted and AttrDecrypt attributes set, and the Type field is ObjectTypeKeyedHash, then the newly created object will be a derivation parent.

The authorization value for the created object is initialized to the value of the UserAuth field of inSensitive.

If there are no available slots for new objects on the TPM, a *TPMWarning error with a warning code of WarningObjectMemory will be returned.

If the attributes in the Attrs field of inPublic are inconsistent or inappropriate for the usage, a *TPMParameterError error with an error code of ErrorAttributes will be returned for parameter index 2.

If the NameAlg field of inPublic is HashAlgorithmNull, then a *TPMParameterError error with an error code of ErrorHash will be returned for parameter index 2.

If an authorization policy is defined via the AuthPolicy field of inPublic then the length of the digest must match the name algorithm selected via the NameAlg field, else a *TPMParameterError error with an error code of ErrorSize is returned for parameter index 2.

If the scheme in the Params field of inPublic is inappropriate for the usage, a *TPMParameterError errow with an error code of ErrorScheme will be returned for parameter index 2.

If the Type field of inPublic is ObjectTypeRSA, ObjectTypeECC or ObjectTypeKeyedHash and the digest algorithm specified by the scheme in the Params field of inPublic is inappropriate for the usage, a *TPMParameterError error with an error code of ErrorHash will be returned for parameter index 2.

If the Type field of inPublic is not ObjectTypeKeyedHash, a *TPMParameterError error with an error code of ErrorSymmetric will be returned for parameter index 2 if the symmetric algorithm specified in the Params field of inPublic is inappropriate for the usage.

If the Type field of inPublic is ObjectTypeECC and the KDF scheme specified in the Params field of inPublic is not KDFAlgorithmNull, a *TPMParameterError error with an error code of ErrorKDF will be returned for parameter index 2.

If the length of the UserAuth field of inSensitive is longer than the name algorithm selected by the NameAlg field of inPublic, a *TPMParameterError error with an error code of ErrorSize will be returned for parameter index 1.

If the Type field of inPublic is ObjectTypeRSA and the Params field specifies an unsupported exponent, a *TPMError with an error code of ErrorRange will be returned. If the specified key size is an unsupported value, a *TPMError with an error code of ErrorValue will be returned.

If the Type field of inPublic is ObjectTypeSymCipher and the key size is an unsupported value, a *TPMError with an error code of ErrorKeySize will be returned. If the AttrSensitiveDataOrigin attribute is not set and the length of the Data field of inSensitive does not match the key size specified in the Params field of inPublic, a *TPMError with an error code of ErrorKeySize will be returned.

If the Type field of inPublic is ObjectTypeKeyedHash and the AttrSensitiveDataOrigin attribute is not set, a *TPMError with an error code of ErrorSize will be returned if the length of the Data field of inSensitive is longer than permitted for the digest algorithm selected by the specified scheme.

This function will call TPMContext.InitProperties if it hasn't already been called.

On success, a ResourceContext instance will be returned that corresponds to the newly created object on the TPM. It will not be necessary to call ResourceContext.SetAuthValue on it - this function sets the correct authorization value so that it can be used in subsequent commands that require knowledge of the authorization value. The returned ResourceContext can be type asserted to ObjectContext. If the Type field of inPublic is ObjectTypeKeyedHash or ObjectTypeSymCipher, then the returned *Public object will have a Unique field that is the digest of the sensitive data and the value of the object's seed in the sensitive area, computed using the object's name algorithm. If the Type field of inPublic is ObjectTypeECC or ObjectTypeRSA, then the returned *Public object will have a Unique field containing details about the public part of the key, computed from the private part of the key.

The returned *CreationData will contain a digest computed from the values of PCRs selected by the creationPCR parameter at creation time in the PCRDigest field. It will also contain the provided outsideInfo in the OutsideInfo field. The returned *TkCreation ticket can be used to prove the association between the created object and the returned *CreationData via the TPMContext.CertifyCreation method.

Example (CreatePrimaryStorageKeyInStorageHierarchy)
// Use TPMContext.CreatePrimary to create a primary storage key in the storage hierarchy.
device, err := linux.DefaultTPM2Device()
if err != nil {
	fmt.Fprintln(os.Stderr, err)
	return
}
tpm, err := tpm2.OpenTPMDevice(device)
if err != nil {
	fmt.Fprintln(os.Stderr, err)
	return
}
defer tpm.Close()

template := objectutil.NewRSAStorageKeyTemplate()

object, _, _, _, _, err := tpm.CreatePrimary(tpm.OwnerHandleContext(), nil, template, nil, nil, nil)
if err != nil {
	fmt.Fprintln(os.Stderr, err)
	return
}

// object is the handle to the new transient primary object
// ...
// ... do something with object
// ...

tpm.FlushContext(object)
Output:

func (*TPMContext) CreateResourceContextFromTPM deprecated

func (t *TPMContext) CreateResourceContextFromTPM(handle Handle, sessions ...SessionContext) (ResourceContext, error)

CreateResourceContextFromTPM creates and returns a new ResourceContext for the specified handle. It will execute a command to read the public area from the TPM in order to initialize state that is maintained on the host side. A *ResourceUnavailableError error will be returned if the specified handle references a resource that doesn't exist.

The public area and name returned from the TPM are checked for consistency as long as the corresponding name algorithm is linked into the current binary.

If any sessions are supplied, the public area is read from the TPM twice. The second time uses the supplied sessions.

This function will return an error if handle doesn't correspond to a NV index, transient object or persistent object.

If subsequent use of the returned ResourceContext requires knowledge of the authorization value of the corresponding TPM resource, this should be provided by calling ResourceContext.SetAuthValue.

If the specified handle is an object, the returned context can be type asserted to ObjectContext. If the specified handle is a NV index, the returned context can be type asserted to NVIndexContext.

Deprecated: Use TPMContext.NewResourceContext instead.

func (*TPMContext) DictionaryAttackLockReset

func (t *TPMContext) DictionaryAttackLockReset(lockContext ResourceContext, lockContextAuthSession SessionContext, sessions ...SessionContext) error

DictionaryAttackLockReset executes the TPM2_DictionaryAttackLockReset command to cancel the effect of a TPM lockout. The lockContext parameter must always be a ResourceContext corresponding to HandleLockout. The command requires authorization with the user auth role for lockContext, with session based authorization provided via lockContextAuthSession.

On successful completion, the lockout counter will be reset to zero.

func (*TPMContext) DictionaryAttackParameters

func (t *TPMContext) DictionaryAttackParameters(lockContext ResourceContext, newMaxTries, newRecoveryTime, lockoutRecovery uint32, lockContextAuthSession SessionContext, sessions ...SessionContext) error

DictionaryAttackParameters executes the TPM2_DictionaryAttackParameters command to change the dictionary attack lockout settings. The newMaxTries parameter sets the maximum value of the lockout counter before the TPM enters lockout mode. If it is set to zero, then the TPM will enter lockout mode and the use of dictionary attack protected entities will be disabled. The newRecoveryTime parameter specifies the amount of time in seconds it takes for the lockout counter to decrement by one. If it is set to zero, then dictionary attack protection is disabled. The lockoutRecovery parameter specifies the amount of time in seconds that the lockout hierarchy authorization cannot be used after an authorization failure. If it is set to zero, then the lockout hierarchy can be used again after a TPM reset, restart or resume. The newRecoveryTime and lockoutRecovery parameters are measured against powered on time rather than clock time.

The lockContext parameter must be a ResourceContext corresponding to HandleLockout. The command requires authorization with the user auth role for lockContext, with session based authorization provided via lockContextAuthSession.

func (*TPMContext) DoesHandleExist

func (t *TPMContext) DoesHandleExist(handle Handle, sessions ...SessionContext) bool

DoesHandleExist is a convenience function for TPMContext.GetCapability that determines if a resource with the specified handle exists on the TPM. This will indicate that the resource does not exist if the TPM returns an error. If handle corresponds to a session, this will only return true if the session is loaded.

func (*TPMContext) DoesSavedSessionExist added in v1.1.0

func (t *TPMContext) DoesSavedSessionExist(handle Handle, sessions ...SessionContext) bool

DoesSavedSessionExist is a convenience function for TPMContext.GetCapability that determines if the specified handle corresponds to a saved session. This will indicate that there is no saved session if the TPM returns an error.

func (*TPMContext) Duplicate

func (t *TPMContext) Duplicate(objectContext, newParentContext ResourceContext, encryptionKeyIn Data, symmetricAlg *SymDefObject, objectContextAuthSession SessionContext, sessions ...SessionContext) (encryptionKeyOut Data, duplicate Private, outSymSeed EncryptedSecret, err error)

Duplicate executes the TPM2_Duplicate command in order to duplicate the object associated with objectContext so that it may be used in a different hierarchy. The new parent is specified by the newParentContext argument, which may correspond to an object on the same or a different TPM, or may be nil for no parent.

This command requires authorization for objectContext with the duplication role, with the session provided via objectContextAuthSession.

If symmetricAlg is provided, it defines the symmetric algorithm used for the inner duplication wrapper (see section 23.3 - "Protected Storage Hierarchy - Duplication" of Part 1 of the Trusted Platform Module Library specification). If symmetricAlg is provided and symmetricAlg.Algorithm is not SymObjectAlgorithmNull, a symmetric key for the inner duplication wrapper may be provided via encryptionKeyIn.

If newParentContext is supplied, an outer duplication wrapper is applied (see section 23.3 - "Protected Storage Hierarchy - Duplication" of Part 1 of the Trusted Platform Module Library specification)

If the object associated with objectContext has the AttrFixedParent atttribute set, a *TPMHandleError error with an error code of ErrorAttributes will be returned for handle index 1.

If the object associated with objectContext has a name algorithm of HashAlgorithmNull, a *TPMHandleError error with an error code of ErrorType will be returned for handle index 1.

If newParentContext is provided and it does not correspond to a storage parent, a *TPMHandleError error with an error code of ErrorType will be returned for handle index 2.

If the object associated with objectContext has the AttrEncryptedDuplication attribute set and no symmetricAlg is provided or symmetricAlg.Algorithm is SymObjectAlgorithmNull, a *TPMParameterError error with an error code of ErrorSymmetric will be returned for parameter index 2.

If the object associated with objectContext has the AttrEncryptedDuplication attribute set and newParentContext is not provided, a *TPMHandleError error with an error code of ErrorHierarchy will be returned for handle index 2.

If the length of encryptionKeyIn is not consistent with symmetricAlg, a *TPMParameterError error with an error code of ErrorSize will be returned for parameter index 1.

If newParentContext corresponds to an ECC key and the public point of the key is not on the curve specified by the key, a *TPMError error with an error code of ErrorKey will be returned.

On success, the function returns a randomly generated symmetric key as Data for the inner duplication wrapper if symmetricAlg was provided, symmetricAlg.Algorithm was not SymObjectAlgorithmNull and encryptionKeyIn was not provided. It also returns the sensitive area associated with objectContext protected with an inner duplication wrapper (if specified by symmetricAlg) and an outer duplication wrapper (if newParentContext was provided). If newParentContext was provided, a secret structure that can be used by the private part of the new parent to recover the seed used to generate the outer wrapper is returned as an EncryptedSecret.

func (*TPMContext) EndorsementHandleContext

func (t *TPMContext) EndorsementHandleContext() ResourceContext

EndorsementHandleContext returns the ResourceContext corresponding to the endorsement hiearchy.

func (*TPMContext) EventSequenceComplete

func (t *TPMContext) EventSequenceComplete(pcrContext, sequenceContext ResourceContext, buffer MaxBuffer, pcrContextAuthSession, sequenceContextAuthSession SessionContext, sessions ...SessionContext) (results TaggedHashList, err error)

EventSequenceComplete executes the TPM2_EventSequenceComplete command to add the last part of the data to the event sequence associated with sequenceContext, and return the result. This command requires authorization with the user auth role for sequenceContext, with session based authorization provided via sequenceContextAuthSession.

If pcrContext is not nil, the result will be extended to the corresponding PCR in the same manner as TPMContext.PCRExtend. Authorization with the user auth role is required for pcrContext, with session based authorization provided via pcrContextAuthSession.

If sequenceContext does not correspond to an event sequence object, then a *TPMHandleError error with an error code of ErrorMode will be returned for handle index 2.

If pcrContext is not nil and the corresponding PCR can not be extended from the current locality, a *TPMError error with an error code of [ErrorLocality] will be returned.

On success, the sequence object associated with sequenceContext will be evicted, and sequenceContext will become invalid.

func (*TPMContext) EventSequenceExecute

func (t *TPMContext) EventSequenceExecute(pcrContext, sequenceContext ResourceContext, buffer []byte, pcrContextAuthSession, sequenceContextAuthSession SessionContext, sessions ...SessionContext) (results TaggedHashList, err error)

EventSequenceExecute executes an event sequence to completion and returns the result by adding the provided data to the sequence with a number of TPM2_SequenceUpdate commands appropriate for the size of buffer, and executing a final TPM2_EventSequenceComplete command. This command requires authorization with the user auth role for sequenceContext, with session based authorization provided via sequenceContextAuthSession.

If pcrContext is not nil, the result will be extended to the corresponding PCR in the same manner as TPMContext.PCRExtend. Authorization with the user auth role is required for pcrContext, with session based authorization provided via pcrContextAuthSession.

If sequenceContext does not correspond to an event sequence object, then a *TPMHandleError error with an error code of ErrorMode will be returned for handle index 1 if the command is CommandSequenceUpdate, or handle index 2 if the command is CommandEventSequenceComplete.

If pcrContext is not nil and the corresponding PCR can not be extended from the current locality, a *TPMError error with an error code of [ErrorLocality] will be returned.

On success, the sequence object associated with sequenceContext will be evicted, and sequenceContext will become invalid.

func (*TPMContext) EvictControl

func (t *TPMContext) EvictControl(auth, object ResourceContext, persistentHandle Handle, authAuthSession SessionContext, sessions ...SessionContext) (ResourceContext, error)

EvictControl executes the TPM2_EvictControl command on the handle referenced by object. To persist a transient object, object should correspond to the transient object and persistentHandle should specify the persistent handle to which the resource associated with object should be persisted. To evict a persistent object, object should correspond to the persistent object and persistentHandle should be the handle associated with that resource.

The auth parameter should be a ResourceContext that corresponds to a hierarchy - it should be HandlePlatform for objects within the platform hierarchy, or HandleOwner for objects within the storage or endorsement hierarchies. If auth is a ResourceContext corresponding to HandlePlatform but object corresponds to an object outside of the platform hierarchy, or auth is a ResourceContext corresponding to HandleOwner but object corresponds to an object inside of the platform hierarchy, a *TPMHandleError error with an error code of ErrorHierarchy will be returned for handle index 2. The auth handle requires authorization with the user auth role, with session based authorization provided via authAuthSession.

If object corresponds to a transient object that only has a public part loaded, or which has the AttrStClear attribute set, then a *TPMHandleError error with an error code of ErrorAttributes will ba returned for handle index 2.

If object corresponds to a persistent object and persistentHandle is not the handle for that object, a *TPMHandleError error with an error code of ErrorHandle will be returned for handle index 2.

If object corresponds to a transient object and persistentHandle is not in the correct range determined by the value of auth, a *TPMParameterError error with an error code of ErrorRange will be returned.

If there is insuffient space to persist a transient object, a *TPMError error with an error code of ErrorNVSpace will be returned. If a persistent object already exists at the specified handle, a *TPMError error with an error code of ErrorNVDefined will be returned.

On successful completion of persisting a transient object, it returns a ResourceContext that corresponds to the persistent object. If object can be type asserted to ObjectContext, then the returned ResourceContext can also be type asserted to ObjectContext. On successful completion of evicting a persistent object, it returns a nil ResourceContext, and object will be invalidated.

Example (EvictPersistentObject)
// Use TPMContext.EvictControl to remove the object at handle 0x81000001 from NV memory.
device, err := linux.DefaultTPM2Device()
if err != nil {
	fmt.Fprintln(os.Stderr, err)
	return
}
tpm, err := tpm2.OpenTPMDevice(device)
if err != nil {
	fmt.Fprintln(os.Stderr, err)
	return
}
defer tpm.Close()

persistent, err := tpm.NewResourceContext(0x81000001)
if err != nil {
	fmt.Fprintln(os.Stderr, err)
	return
}

if _, err := tpm.EvictControl(tpm.OwnerHandleContext(), persistent, persistent.Handle(), nil); err != nil {
	fmt.Fprintln(os.Stderr, err)
	return
}

// The resource associated with persistent is now unavailable.
Output:

Example (PersistTransientObject)
// Create a primary object and then use TPMContext.EvictControl to store it in NV memory
// at handle 0x81000001.
device, err := linux.DefaultTPM2Device()
if err != nil {
	fmt.Fprintln(os.Stderr, err)
	return
}
tpm, err := tpm2.OpenTPMDevice(device)
if err != nil {
	fmt.Fprintln(os.Stderr, err)
	return
}
defer tpm.Close()

template := objectutil.NewRSAStorageKeyTemplate()

transient, _, _, _, _, err := tpm.CreatePrimary(tpm.OwnerHandleContext(), nil, template, nil, nil, nil)
if err != nil {
	fmt.Fprintln(os.Stderr, err)
	return
}
defer tpm.FlushContext(transient)

persistent, err := tpm.EvictControl(tpm.OwnerHandleContext(), transient, 0x81000001, nil)
if err != nil {
	fmt.Fprintln(os.Stderr, err)
	return
}

// persistent is the handle to the new persistent object
_ = persistent
Output:

func (*TPMContext) FlushContext

func (t *TPMContext) FlushContext(flushContext HandleContext) error

FlushContext executes the TPM2_FlushContext command on the handle referenced by flushContext, in order to flush resources associated with it from the TPM. If flushContext does not correspond to a transient object or a session, then it will return with an error.

On successful completion, flushContext is invalidated. If flushContext corresponded to a session, then it will no longer be possible to restore that session with TPMContext.ContextLoad, even if it was previously saved with TPMContext.ContextSave.

func (*TPMContext) GetCapability

func (t *TPMContext) GetCapability(capability Capability, property, propertyCount uint32, sessions ...SessionContext) (capabilityData *CapabilityData, err error)

GetCapability executes the TPM2_GetCapability command, which returns various properties of the TPM and its current state. The capability parameter indicates the category of data to be returned. The property parameter indicates the first value of the selected category to be returned. The propertyCount parameter indicates the number of values to be returned.

If no property in the TPM corresponds to the value of property, then the next property is returned.

The underlying implementation of TPM2_GetCapability is not required to (or may not be able to) return all of the requested values in a single request. This function will re-execute the TPM2_GetCapability command until all of the requested properties have been returned. As a consequence, any SessionContext instances provided should have the AttrContinueSession attribute defined.

If capability is CapabilityHandles and property does not correspond to a valid handle type, a *TPMParameterError error with an error code of ErrorHandle is returned for parameter index 2.

On success, a capability structure is returned containing the requested number of properties, or the number of properties available, whichever is less.

func (*TPMContext) GetCapabilityAlg

func (t *TPMContext) GetCapabilityAlg(alg AlgorithmId, sessions ...SessionContext) (AlgorithmProperty, error)

GetCapabilityAlg is a convenience function for TPMContext.GetCapability that returns the properties of the specified algorithm if it is supported by the TPM. If it isn't supported, an error is returned.

func (*TPMContext) GetCapabilityAlgs

func (t *TPMContext) GetCapabilityAlgs(first AlgorithmId, propertyCount uint32, sessions ...SessionContext) (algs AlgorithmPropertyList, err error)

GetCapabilityAlgs is a convenience function for TPMContext.GetCapability, and returns properties of the algorithms supported by the TPM. The first parameter indicates the first algorithm for which to return properties. If this algorithm isn't supported, then the properties of the next supported algorithm are returned instead. The propertyCount parameter indicates the number of algorithms for which to return properties.

func (*TPMContext) GetCapabilityAuditCommands

func (t *TPMContext) GetCapabilityAuditCommands(first CommandCode, propertyCount uint32, sessions ...SessionContext) (auditCommands CommandCodeList, err error)

GetCapabilityAuditCommands is a convenience function for TPMContext.GetCapability, and returns a list of commands that are currently set for command audit. The first parameter indicates the command code at which the returned list should start. The propertyCount parameter indicates the maximum number of command codes to return.

func (*TPMContext) GetCapabilityAuthPolicies

func (t *TPMContext) GetCapabilityAuthPolicies(first Handle, propertyCount uint32, sessions ...SessionContext) (authPolicies TaggedPolicyList, err error)

GetCapabilityAuthPolicies is a convenience function for TPMContext.GetCapability, and returns auth policy digests associated with permanent handles. The first parameter indicates the first handle for which to return an auth policy. If the handle doesn't exist, then the auth policy for the next available handle is returned. The propertyCount parameter indicates the number of permanent handles for which to return an auth policy.

func (*TPMContext) GetCapabilityAuthPolicy added in v1.5.0

func (t *TPMContext) GetCapabilityAuthPolicy(handle Handle, sessions ...SessionContext) (TaggedHash, error)

GetCapabilityAuthPolicy is a convenience function for TPMContext.GetCapability, and returns the auth policy digest associated with the supplied permanent handle, if there is one. This will return a null hash if there is no auth policy digest.

func (*TPMContext) GetCapabilityCommand

func (t *TPMContext) GetCapabilityCommand(code CommandCode, sessions ...SessionContext) (CommandAttributes, error)

GetCapabilityCommand is a convenience function for TPMContext.GetCapability that returns the attributes of the specified command if it is supported by the TPM. If it isn't supported, an error is returned.

func (*TPMContext) GetCapabilityCommands

func (t *TPMContext) GetCapabilityCommands(first CommandCode, propertyCount uint32, sessions ...SessionContext) (commands CommandAttributesList, err error)

GetCapabilityCommands is a convenience function for TPMContext.GetCapability, and returns attributes of the commands supported by the TPM. The first parameter indicates the first command for which to return attributes. If this command isn't supported, then the attributes of the next supported command are returned instead. The propertyCount parameter indicates the number of commands for which to return attributes.

func (*TPMContext) GetCapabilityECCCurves

func (t *TPMContext) GetCapabilityECCCurves(sessions ...SessionContext) (eccCurves ECCCurveList, err error)

GetCapabilityECCCurves is a convenience function for TPMContext.GetCapability, and returns a list of ECC curves supported by the TPM.

func (*TPMContext) GetCapabilityHandles

func (t *TPMContext) GetCapabilityHandles(firstHandle Handle, propertyCount uint32, sessions ...SessionContext) (handles HandleList, err error)

GetCapabilityHandles is a convenience function for TPMContext.GetCapability, and returns a list of handles of resources on the TPM. The firstHandle parameter indicates the type of handles to be returned (represented by the most-significant byte), and also the handle at which the list should start. The propertyCount parameter indicates the maximum number of handles to return.

func (*TPMContext) GetCapabilityPCRProperties

func (t *TPMContext) GetCapabilityPCRProperties(first PropertyPCR, propertyCount uint32, sessions ...SessionContext) (pcrProperties TaggedPCRPropertyList, err error)

GetCapabilityPCRProperties is a convenience function for TPMContext.GetCapability, and returns the values of PCR properties. The first parameter indicates the first property for which to return a value. If the property does not exist, then the value of the next available property is returned. The propertyCount parameter indicates the number of properties for which to return values. Each returned property value is a list of PCR indexes associated with a property.

func (*TPMContext) GetCapabilityPCRs

func (t *TPMContext) GetCapabilityPCRs(sessions ...SessionContext) (pcrs PCRSelectionList, err error)

GetCapabilityPCRs is a convenience function for TPMContext.GetCapability, and returns the current allocation of PCRs on the TPM.

func (*TPMContext) GetCapabilityPPCommands

func (t *TPMContext) GetCapabilityPPCommands(first CommandCode, propertyCount uint32, sessions ...SessionContext) (ppCommands CommandCodeList, err error)

GetCapabilityPPCommands is a convenience function for TPMContext.GetCapability, and returns a list of commands that require physical presence for platform authorization. The first parameter indicates the command code at which the returned list should start. The propertyCount parameter indicates the maximum number of command codes to return.

func (*TPMContext) GetCapabilityRaw added in v0.2.0

func (t *TPMContext) GetCapabilityRaw(capability Capability, property, propertyCount uint32, sessions ...SessionContext) (moreData bool, capabilityData *CapabilityData, err error)

GetCapabilityRaw executes the TPM2_GetCapability command, which returns various properties of the TPM and its current state. The capability parameter indicates the category of data to be returned. The property parameter indicates the first value of the selected category to be returned. The propertyCount parameter indicates the number of values to be returned.

If no property in the TPM corresponds to the value of property, then the next property is returned.

The underlying implementation of TPM2_GetCapability is not required to (or may not be able to) return all of the requested values in a single request.

If capability is CapabilityHandles and property does not correspond to a valid handle type, a *TPMParameterError error with an error code of ErrorHandle is returned for parameter index 2.

On success, a capability structure is returned containing the requested number of properties, the number of properties available, or the number of properties that could be returned, whichever is less. If there are more properties in the selected category, moreData will be true whether the remaining properties were requested or not.

func (*TPMContext) GetCapabilityTPMProperties

func (t *TPMContext) GetCapabilityTPMProperties(first Property, propertyCount uint32, sessions ...SessionContext) (tpmProperties TaggedTPMPropertyList, err error)

GetCapabilityTPMProperties is a convenience function for TPMContext.GetCapability, and returns the values of properties of the TPM. The first parameter indicates the first property for which to return a value. If the property does not exist, then the value of the next available property is returned. The propertyCount parameter indicates the number of properties for which to return values.

func (*TPMContext) GetCapabilityTPMProperty

func (t *TPMContext) GetCapabilityTPMProperty(property Property, sessions ...SessionContext) (uint32, error)

GetCapabilityTPMProperty is a convenience function for TPMContext.GetCapability that returns the value of the specified property if it exists. If it doesn't exist, an error is returned.

func (*TPMContext) GetCommandAuditDigest

func (t *TPMContext) GetCommandAuditDigest(privacyContext, signContext ResourceContext, qualifyingData Data, inScheme *SigScheme, privacyContextAuthSession, signContextAuthSession SessionContext, sessions ...SessionContext) (auditInfo *Attest, signature *Signature, err error)

GetCommandAuditDigest executes the TPM2_GetCommandAuditDigest command to obtain the current command audit digest, the current audit digest algorithm and a digest of the list of commands being audited.

The privacyContext argument must be a ResourceContext corresponding to HandleEndorsement. This command requires authorization with the user auth role for privacyContext, with session based authorization provided via privacyContextAuthSession.

If signContext is not nil, the returned attestation will be signed by the key associated with it. This command requires authorization with the user auth role for signContext, with session based authorization provided via provided via signContextAuthSession.

If signContext is not nil and the object associated with signContext is not a signing key, a *TPMHandleError error with an error code of ErrorKey will be returned for handle index 2.

If signContext is not nil and if the scheme of the key associated with signContext is AsymSchemeNull, then inScheme must be provided to specify a valid signing scheme for the key. If it isn't, a *TPMParameterError error with an error code of ErrorScheme will be returned for parameter index 2.

If signContext is not nil and the scheme of the key associated with signContext is not AsymSchemeNull, then inScheme may be nil. If it is provided, then the specified scheme must match that of the signing key, else a *TPMParameterError error with an error code of ErrorScheme will be returned for parameter index 2.

On success, it returns an attestation structure detailing the current command audit digest, digest algorithm and a digest of the list of commands being audited. If signContext is not nil, the attestation structure will be signed by the associated key and returned too.

func (*TPMContext) GetInputBuffer deprecated

func (t *TPMContext) GetInputBuffer(sessions ...SessionContext) int

GetInputBuffer is a convenience function for TPMContext.GetCapability that returns the value of the PropertyInputBuffer property, which indicates the maximum size of arguments of the MaxBuffer type in bytes. The size is TPM implementation specific, but required to be at least 1024 bytes.

Deprecated: Use [GetMaxBufferSize] instead.

func (*TPMContext) GetManufacturer

func (t *TPMContext) GetManufacturer(sessions ...SessionContext) (manufacturer TPMManufacturer, err error)

GetManufacturer is a convenience function for TPMContext.GetCapability that returns the ID of the TPM manufacturer.

func (*TPMContext) GetMaxBufferSize added in v1.3.0

func (t *TPMContext) GetMaxBufferSize(sessions ...SessionContext) (uint16, error)

GetMaxBufferSize is a convenience function for TPMContext.GetCapability that returns the value of the PropertyInputBuffer property, which indicates the maximum size in bytes supported by the TPM for arguments of the MaxBuffer type.

func (*TPMContext) GetMaxData deprecated

func (t *TPMContext) GetMaxData(sessions ...SessionContext) (int, error)

GetMaxData is a convenience function for TPMContext.GetCapability that returns the maximum size of arguments of the Data type supported by the TPM in bytes.

Deprecated: Use [GetMaxDataSize].

func (*TPMContext) GetMaxDataSize added in v1.3.0

func (t *TPMContext) GetMaxDataSize(sessions ...SessionContext) (uint16, error)

GetMaxDataSize is a convenience function for TPMContext.GetCapability that returns the maximum size in bytes supported by the TPM for arguments of the Data type.

func (*TPMContext) GetMaxDigest deprecated

func (t *TPMContext) GetMaxDigest(sessions ...SessionContext) (int, error)

GetMaxDigest is a convenience function for TPMContext.GetCapability that returns the value of the PropertyMaxDigest property, which indicates the size of the largest digest algorithm supported by the TPM in bytes.

Deprecated: Use [GetMaxDigestSize].

func (*TPMContext) GetMaxDigestSize added in v1.3.0

func (t *TPMContext) GetMaxDigestSize(sessions ...SessionContext) (uint16, error)

GetMaxDigestSize is a convenience function for TPMContext.GetCapability that returns the value of the PropertyMaxDigest property, which indicates the size in bytes of the largest digest algorithm supported by the TPM.

func (*TPMContext) GetMinPCRSelectSize added in v0.2.0

func (t *TPMContext) GetMinPCRSelectSize(sessions ...SessionContext) (uint8, error)

GetMinPCRSelectSize is a convenience function for TPMContext.GetCapability that returns the value of the PropertyPCRSelectMin property, which indicates the minimum number of bytes in a PCR selection.

func (*TPMContext) GetNVBufferMax deprecated

func (t *TPMContext) GetNVBufferMax(sessions ...SessionContext) (int, error)

GetNVBufferMax is a convenience function for TPMContext.GetCapability that returns the value of the PropertyNVBufferMax property, which indicates the maximum buffer size supported by the TPM in bytes for TPMContext.NVReadRaw and TPMContext.NVWriteRaw.

Deprecated: Use [GetNVMaxBufferSize].

func (*TPMContext) GetNVIndexMax deprecated

func (t *TPMContext) GetNVIndexMax(sessions ...SessionContext) (int, error)

GetNVIndexMax is a convenience function for TPMContext.GetCapability that returns the value of the PropertyNVIndexMax property, which indicates the maximum size of a single NV index.

Deprecated: Use [GetNVMaxIndexSize].

func (*TPMContext) GetNVMaxBufferSize added in v1.3.0

func (t *TPMContext) GetNVMaxBufferSize(sessions ...SessionContext) (uint16, error)

GetNVMaxBufferSize is a convenience function for TPMContext.GetCapability that returns the value of the PropertyNVBufferMax property, which indicates the maximum buffer size in bytes supported by the TPM for arguments of the MaxNVBuffer type (used by TPMContext.NVReadRaw and TPMContext.NVWriteRaw).

func (*TPMContext) GetNVMaxIndexSize added in v1.3.0

func (t *TPMContext) GetNVMaxIndexSize(sessions ...SessionContext) (int, error)

GetNVMaxIndexSize is a convenience function for TPMContext.GetCapability that returns the value of the PropertyNVIndexMax property, which indicates the maximum size in bytes of a single NV index.

func (*TPMContext) GetPermanentContext

func (t *TPMContext) GetPermanentContext(handle Handle) ResourceContext

GetPermanentContext returns a ResourceContext for the specified permanent handle or PCR handle.

This function will panic if handle does not correspond to a permanent or PCR handle.

If subsequent use of the returned ResourceContext requires knowledge of the authorization value of the corresponding TPM resource, this should be provided by calling ResourceContext.SetAuthValue.

func (*TPMContext) GetRandom

func (t *TPMContext) GetRandom(bytesRequested uint16, sessions ...SessionContext) (randomBytes Digest, err error)

GetRandom executes the TPM2_GetRandom command to return the requested number of bytes from the TPM's random number generator.

func (*TPMContext) GetSessionAuditDigest

func (t *TPMContext) GetSessionAuditDigest(privacyAdminContext, signContext ResourceContext, sessionContext SessionContext, qualifyingData Data, inScheme *SigScheme, privacyAdminContextAuthSession, signContextAuthSession SessionContext, sessions ...SessionContext) (auditInfo *Attest, signature *Signature, err error)

GetSessionAuditDigest executes the TPM2_GetSessionAuditDigest to obtain the current digest of the audit session corresponding to sessionContext.

The privacyAdminContext argument must be a ResourceContext that corresponds to HandleEndorsement. This command requires authorization with the user auth role for privacyAdminContext, with session based authorization provided via privacyAdminContextAuthSession.

If signContext is not nil, the returned attestation will be signed by the key associated with it. This command requires authorization with the user auth role for signContext, with session based authorization provided via signContextAuthSession.

If signContext is not nil and the object associated with signContext is not a signing key, a *TPMHandleError error with an error code of ErrorKey will be returned for handle index 2.

If signContext is not nil and if the scheme of the key associated with signContext is AsymSchemeNull, then inScheme must be provided to specify a valid signing scheme for the key. If it isn't, a *TPMParameterError error with an error code of ErrorScheme will be returned for parameter index 2.

If signContext is not nil and the scheme of the key associated with signContext is not AsymSchemeNull, then inScheme may be nil. If it is provided, then the specified scheme must match that of the signing key, else a *TPMParameterError error with an error code of ErrorScheme will be returned for parameter index 2.

On success, it returns an attestation structure detailing the current audit digest for sessionContext. If signContext is not nil, the attestation structure will be signed by the associated key and returned too.

func (*TPMContext) GetTestResult

func (t *TPMContext) GetTestResult(sessions ...SessionContext) (outData MaxBuffer, testResult ResponseCode, err error)

func (*TPMContext) GetTime

func (t *TPMContext) GetTime(privacyAdminContext, signContext ResourceContext, qualifyingData Data, inScheme *SigScheme, privacyAdminContextAuthSession, signContextAuthSession SessionContext, sessions ...SessionContext) (timeInfo *Attest, signature *Signature, err error)

GetTime executes the TPM2_GetTime command in order to obtain the current values of time and clock.

The privacyAdminContext argument must be a ResourceContext that corresponds to HandleEndorsement. The command requires authorization with the user auth role for privacyAdminContext, with session based authorization provided via privacyAdminContextAuthSession.

If signContext is not nil, the returned attestation will be signed by the key associated with it. This command requires authorization with the user auth role for signContext, with session based authorization provided via signContextAuthSession.

If signContext is not nil and the object associated with signContext is not a signing key, a *TPMHandleError error with an error code of ErrorKey will be returned for handle index 2.

If signContext is not nil and if the scheme of the key associated with signContext is AsymSchemeNull, then inScheme must be provided to specify a valid signing scheme for the key. If it isn't, a *TPMParameterError error with an error code of ErrorScheme will be returned for parameter index 2.

If signContext is not nil and the scheme of the key associated with signContext is not AsymSchemeNull, then inScheme may be nil. If it is provided, then the specified scheme must match that of the signing key, else a *TPMParameterError error with an error code of ErrorScheme will be returned for parameter index 2.

On success, it returns an attestation structure detailing the current values of time and clock. If signContext is not nil, the attestation structure will be signed by the associated key and returned too.

func (*TPMContext) HMACStart

func (t *TPMContext) HMACStart(context ResourceContext, auth Auth, hashAlg HashAlgorithmId, contextAuthSession SessionContext, sessions ...SessionContext) (sequenceContext ResourceContext, err error)

HMACStart executes the TPM2_HMAC_Start command to begin a HMAC sequence. The context argument corresponds to a loaded HMAC key. This command requires authorization with the user auth role for context, with session based authorization provided via contextAuthSession. The command creates a new HMAC sequence object on the TPM. The auth argument defines the authorization value for the newly created sequence object, which is required for subsequent use of it.

If context does not correspond to an object with the type ObjectTypeKeyedHash, a *TPMHandleError error with an error code of ErrorType will be returned.

If context corresponds to an object with the AttrRestricted attribute set, a *TPMHandleError error with an error code of ErrorAttributes will be returned.

If context does not correspond to a signing key, a *TPMHandleError error with an error code of ErrorKey will be returned.

The hashAlg argument specifies the HMAC algorithm. If the default scheme of the key associated with context is KeyedHashSchemeNull, then hashAlg must not be HashAlgorithmNull. If the default scheme of the key associated with context is not KeyedHashSchemeNull, then hashAlg must either be HashAlgorithmNull or must match the key's default scheme, else a *TPMParameterError error with an error code of ErrorValue will be returned for parameter index 2.

On success, a ResourceContext corresponding to the newly created HMAC/ sequence object will be returned. It will not be necessary to call ResourceContext.SetAuthValue on it - this function sets the correct authorization value so that it can be used in subsequent commands that require knowledge of the authorization value.

func (*TPMContext) HashSequenceStart

func (t *TPMContext) HashSequenceStart(auth Auth, hashAlg HashAlgorithmId, sessions ...SessionContext) (sequenceContext ResourceContext, err error)

HashSequenceStart executes the TPM2_HashSequenceStart command to begin a hash or event sequence. The command creates a new sequence object on the TPM. The auth argument defines the authorization value for the newly created sequence object, which is required for subsequent use of it.

If hashAlg is HashAlgorithmNull, this function will return a ResourceContext corresponding to a newly created event sequence object. If hashAlg is not HashAlgorithmNull, this function will return a ResourceContext corresponding to a newly created hash sequence object. It will not be necessary to call ResourceContext.SetAuthValue on it - this function sets the correct authorization value so that it can be used in subsequent commands that require knowledge of the authorization value.

func (*TPMContext) HierarchyChangeAuth

func (t *TPMContext) HierarchyChangeAuth(authContext ResourceContext, newAuth Auth, authContextAuthSession SessionContext, sessions ...SessionContext) error

HierarchyChangeAuth executes the TPM2_HierarchyChangeAuth command to change the authorization value for the hierarchy associated with the authContext parameter. The command requires authorization with the user auth role for authContext, with session based authorization provided via authContextAuthSession.

If the value of newAuth is longer than the context integrity digest algorithm for the TPM, a *TPMParameterError error with an error code of ErrorSize will be returned.

On successful completion, the authorization value of the hierarchy associated with authContext will be set to the value of newAuth, and authContext will be updated to reflect this - it isn't necessary to update authContext with ResourceContext.SetAuthValue in order to use it in subsequent commands that require knowledge of the authorization value for the resource.

func (*TPMContext) HierarchyControl

func (t *TPMContext) HierarchyControl(authContext ResourceContext, enable Handle, state bool, authContextAuthSession SessionContext, sessions ...SessionContext) error

HierarchyControl executes the TPM2_HierarchyControl command in order to enable or disable the hierarchy associated with the enable argument. If state is true, the hierarchy associated with the enable argument will be enabled. If state is false, the hierarchy associated with the enable argument will be disabled. This command requires authorization with the user auth role for authContext, with session based authorization provided via authContextAuthSession.

If enable is HandlePlatform and state is false, then this will disable use of the platform hierarchy. In this case, authContext must correspond to HandlePlatform.

If enable is HandlePlatformNV and state is false, then this will disable the use of NV indices with the AttrNVPlatformCreate attribute set, indicating that they were created by the platform owner. In this case, authContext must correspond to HandlePlatform.

If enable is HandleOwner and state is false, then this will disable the use of the storage hierarchy and any NV indices with the AttrNVPlatformCreate attribute clear. In this case, authContext must correspond to HandleOwner or HandlePlatform.

If enable is HandleEndorsement and state is false, then this will disable the use of the endorsment hierarchy. In this case, authContext must correspond to HandleEndorsement or HandlePlatform.

When a hierarchy is disabled, persistent objects associated with it become unavailable, and transient objects associated with it are flushed from the TPM.

If state is true, then authContext must correspond to HandlePlatform. Note that the platform hierarchy can't be re-enabled by this command.

func (*TPMContext) Import

func (t *TPMContext) Import(parentContext ResourceContext, encryptionKey Data, objectPublic *Public, duplicate Private, inSymSeed EncryptedSecret, symmetricAlg *SymDefObject, parentContextAuthSession SessionContext, sessions ...SessionContext) (outPrivate Private, err error)

Import executes the TPM2_Import command in order to encrypt the sensitive area of the object associated with the objectPublic and duplicate arguments with the symmetric algorithm of the storage parent associated with parentContext, so that it can be loaded and used in the new hierarchy.

If the object to be imported has an outer duplication wrapper (see section 23.3 - "Protected Storage Hierarchy - Duplication" of Part 1 of the Trusted Platform Module Library specification), then inSymSeed must be supplied which contains a secret structure that can be recovered by the private part of the key associated with parentContext in order to remove the outer wrapper.

If the object to be imported has an inner duplication wrapper (see section 23.3 - "Protected Storage Hierarchy - Duplication" of Part 1 of the Trusted Platform Module Library specification), then symmetricAlg must be provided with the algorithm of the inner duplication wrapper, and encryptionKey must be provided with the symmetric key for the inner duplication wrapper.

This command requires authorization with the user auth role for parentContext, with session based authorization provided via parentContextAuthSession.

If objectPublic has the AttrFixedTPM or AttrFixedParent attributes set, a *TPMParameterError error with an error code of ErrorAttributes will be returned for parameter index 2.

If parentContext is not associated with a storage parent, a *TPMHandleError error with an error code of ErrorType will be returned.

If the length of encryptionKey is not consistent with symmetricAlg, a *TPMParameterError error with an error code of ErrorSize will be returned for parameter index 1.

If symmetricAlg is not provided or symmetricAlg.Algorithm is SymObjectAlgorithmNull and objectPublic has the AttrEncryptedDuplication attribute set, a *TPMParameterError error with an error code of ErrorAttributes will be returned for parameter index 1.

If the length of inSymSeed is not zero and the object associated with parentContext is not an asymmetric key, a *TPMHandleError error with an error code of ErrorType will be returned.

If parentContext is associated with a RSA key and the size of inSymSeed does not match the size of the key's public modulus, a *TPMParameterError error with an error code of ErrorSize will be returned for parameter index 4.

If parentContext is associated with a RSA key and the plaintext size of inSymSeed is larger than the name algorithm, a *TPMParameterError error with an error code of ErrorValue will be returned for parameter index 4.

If parentContext is associated with a ECC key and inSymSeed does not contain enough data to unmarshal a ECC point, a *TPMParameterError error with an error code of ErrorInsufficient will be returned for parameter index 4.

If parentContext is associated with a ECC key and the ECC point in inSymSeed is not on the curve specified by the parent key, a *TPMParameterError error with an error code of ErrorECCPoint will be returned for parameter index 4.

If parentContext is associated with a ECC key and multiplication of the ECC point in inSymSeed results in a point at infinity, a *TPMParameterError error with an error code of ErrorNoResult will be returned for parameter index 4.

If the name of the object associated with objectPublic cannot be computed, a *TPMParameterError error with an error code of ErrorHash will be returned for parameter index 2.

If the object has an outer duplication wrapper and the integrity value of duplicate cannot be unmarshalled correctly, a *TPMParameterError error with an error code of either ErrorSize or ErrorInsufficient will be returned for parameter index 3. If the integrity check fails, a *TPMParameterError error with an error code of ErrorIntegrity will be returned for parameter index 3.

If the object has an inner duplication wrapper and the integrity value of duplicate cannot be unmarshalled correctly after decrypting the inner wrapper, a *TPMParameterError error with an error code of either ErrorSize or ErrorInsufficient will be returned for parameter index 3. If the integrity check fails, a *[TPMParameterError error with an error code of ErrorIntegrity will be returned for parameter index 3.

If, after removing the duplication wrappers, the sensitive area does not unmarshal correctly, a *TPMParameterError error with an error code of either ErrorSize or ErrorInsufficient will be returned for parameter index 3.

On success, a new private area encrypted with the symmetric algorithm defined by the object associated with parentContext is returned.

func (*TPMContext) IncrementalSelfTest

func (t *TPMContext) IncrementalSelfTest(toTest AlgorithmList, sessions ...SessionContext) (AlgorithmList, error)

func (*TPMContext) InitProperties

func (t *TPMContext) InitProperties(sessions ...SessionContext) error

InitProperties executes one or more TPM2_GetCapability commands to initialize properties used internally by TPMContext. This is normally done automatically by functions that require these properties when they are used for the first time, but this function is provided so that the command can be audited, and so the exclusivity of an audit session can be preserved.

Any sessions supplied should have the AttrContinueSession attribute set.

func (*TPMContext) IsAlgorithmSupported

func (t *TPMContext) IsAlgorithmSupported(alg AlgorithmId, sessions ...SessionContext) bool

IsAlgorithmSupported is a convenience function for TPMContext.GetCapability that determines if the specified algorithm is supported by the TPM. Note that this will indicate that the algorithm is unsupported if the TPM returns an error.

func (*TPMContext) IsCommandSupported

func (t *TPMContext) IsCommandSupported(code CommandCode, sessions ...SessionContext) bool

IsCommandSupported is a convenience function for TPMContext.GetCapability that determines if the specified command is supported by the TPM. Note that this will indicate that the command is unsupported if the TPM returns an error.

func (*TPMContext) IsECCCurveSupported

func (t *TPMContext) IsECCCurveSupported(curve ECCCurve, sessions ...SessionContext) bool

IsECCCurveSupported is a convenience function for TPMContext.GetCapability that determines if the specified curve is supported. This will indicate that the specified curve is unsupported if the TPM returns an error.

func (*TPMContext) IsRSAKeySizeSupported

func (t *TPMContext) IsRSAKeySizeSupported(keyBits uint16, sessions ...SessionContext) bool

IsRSAKeySizeSupporters is a convenience function around TPMContext.TestParms that determines whether the specified RSA key size is supported.

func (*TPMContext) IsSymmetricAlgorithmSupported

func (t *TPMContext) IsSymmetricAlgorithmSupported(algorithm SymObjectAlgorithmId, keyBits uint16, sessions ...SessionContext) bool

IsSymmetricAlgorithmSupported is a convenience function around TPMContext.TestParms that determines whether the specified symmetric algorithm and key size combination is supported.

func (*TPMContext) IsTPM2

func (t *TPMContext) IsTPM2() (isTpm2 bool)

IsTPM2 determines whether this TPMContext is connected to a TPM2 device. It does this by attempting to execute a TPM2_GetCapability command, and verifying that the response packet has the expected tag.

On success, this will return true if TPMContext is connected to a TPM2 device, or false if it is connected to a TPM1.2 device. It will return false if communication with the device fails of if the response is badly formed.

func (*TPMContext) Load

func (t *TPMContext) Load(parentContext ResourceContext, inPrivate Private, inPublic *Public, parentContextAuthSession SessionContext, sessions ...SessionContext) (objectContext ResourceContext, err error)

Load executes the TPM2_Load command in order to load both the public and private parts of an object in to the TPM.

The parentContext parameter corresponds to the parent key. The command requires authorization with the user auth role for parentContext, with session based authorization provided via parentContextAuthSession.

The object to load is specified by providing the inPrivate and inPublic arguments.

If there are no available slots for new objects on the TPM, a *TPMWarning error with a warning code of WarningObjectMemory will be returned.

If inPrivate is empty, a *TPMParameterError error with an error code of ErrorSize will be returned for parameter index 1.

If parentContext does not correspond to a storage parent, a *TPMHandleError error with an error code of ErrorType will be returned.

If the name algorithm associated with inPublic is invalid, a *TPMParameterError error with an error code of ErrorHash will be returned for parameter index 2.

If the integrity value or IV for inPrivate cannot be unmarshalled correctly, a *TPMParameterError error with an error code of either ErrorSize or ErrorInsufficient will be returned for parameter index 1. If the integrity check of inPrivate fails, a *TPMParameterError error with an error code of ErrorIntegrity will be returned for parameter index 1. If the size of the IV for inPrivate doesn't match the block size for the encryption algorithm, a *TPMParameterError error with an error code of ErrorValue will be returned for parameter index 1.

TPM2_Load performs many of the same validations of the public attributes as TPM2_Create, and may return similar error codes as *TPMParameterError for parameter index 2.

If the object associated with parentContext has the AttrFixedTPM attribute clear, some additional validation of the decrypted sensitive data is performed as detailed below.

If the Type field of inPublic does not match the type specified in the sensitive data, a *TPMParameterError error with an error code of ErrorType is returned for parameter index 1. If the authorization value in the sensitive area is larger than the name algorithm, a *TPMParameterError error with an error code of ErrorSize is returned for parameter index 1.

If the Type field of inPublic is ObjectTypeRSA and the size of the modulus in the Unique field is inconsistent with the size specified in the Params field, a *TPMParameterError error with an error code of ErrorKey will be returned for parameter index 2. If the value of the exponent in the Params field is invalid, a *TPMParameterError error with an error code of ErrorValue will be returned for parameter index 2. If the size of private key in the sensitive area is not the correct size, a *TPMParameterError error with an error code of ErrorKeySize will be returned for parameter index 1.

If the Type field of inPublic is ObjectTypeECC and the private key in the sensitive area is invalid, a *TPMParameterError error with an error code of ErrorKeySize will be returned for parameter index 1. If the public point specified in the Unique field of inPublic does not belong to the private key, a *TPMError with an error code of ErrorBinding will be returned.

If the Type field of inPublic is ObjectTypeSymCipher and the size of the symmetric key in the sensitive area is inconsistent with the symmetric algorithm specified in the Params field of inPublic, a *TPMParameterError error with an error code of ErrorKeySize will be returned for parameter index 1.

If the Type field of inPublic is ObjectTypeKeyedHash and the size of the sensitive data is larger than permitted for the digest algorithm selected by the scheme defined in the Params field of inPublic, a *TPMParameterError error with an error code of ErrorKeySize will be returned for parameter index 1.

If the Type field of inPublic is ObjectTypeSymCipher or ObjectTypeKeyedHash and the size of seed value in the sensitive area does not match the name algorithm, a *TPMError error with an error code of ErrorKeySize will be returned. If the digest in the Unique field of inPublic is inconsistent with the value of the sensitive data and the seed value, a *TPMError with an error code of ErrorBinding will be returned.

If the loaded object is a storage parent and the size of the seed value in the sensitive area isn't sufficient for the selected name algorithm, a *TPMParameterError error with an error code of ErrorSize will be returned for parameter index 1.

On success, a ResourceContext corresponding to the newly loaded transient object will be returned. If subsequent use of the returned ResourceContext requires knowledge of the authorization value of the corresponding TPM resource, this should be provided by calling ResourceContext.SetAuthValue. The return ResourceContext can be type asserted to ObjectContext.

func (*TPMContext) LoadExternal

func (t *TPMContext) LoadExternal(inPrivate *Sensitive, inPublic *Public, hierarchy Handle, sessions ...SessionContext) (objectContext ResourceContext, err error)

LoadExternal executes the TPM2_LoadExternal command in order to load an object that is not a protected object in to the TPM. The object is specified by providing the inPrivate and inPublic arguments, although inPrivate is optional. If only the public part is to be loaded, the hierarchy parameter must specify a hierarchy to associate the loaded object with so that tickets can be created properly. If both the public and private parts are to be loaded, then hierarchy should be HandleNull.

If there are no available slots for new objects on the TPM, a *TPMWarning error with a warning code of WarningObjectMemory will be returned.

If the hierarchy specified by the hierarchy parameter is disabled, a *TPMParameterError error with an error code of ErrorHierarchy will be returned for parameter index 3.

If inPrivate is provided and hierarchy is not HandleNull, a *TPMParameterError error with an error code of ErrorHierarchy will be returned for parameter index 3.

If inPrivate is provided and the Attrs field of inPublic has either AttrFixedTPM, AttrFixedParent or AttrRestricted attribute set, a *TPMParameterError error with an error code of ErrorAttributes will be returned for parameter index 2.

TPM2_LoadExternal performs many of the same validations of the public attributes as TPM2_Create, and may return similar error codes as *TPMParameterError for parameter index 2.

If inPrivate is provided and the Type field of inPublic does not match the type specified in the sensitive data, a *TPMParameterError error with an error code of ErrorType is returned for parameter index 1. If the authorization value in the sensitive area is larger than the name algorithm, a *TPMParameterError error with an error code of ErrorSize is returned for parameter index 1.

If the Type field of inPublic is ObjectTypeRSA and the size of the modulus in the Unique field is inconsistent with the size specified in the Params field, a *TPMParameterError error with an error code of ErrorKey will be returned for parameter index 2. If the value of the exponent in the Params field is invalid, a *TPMParameterError error with an error code of ErrorValue will be returned for parameter index 2. If inPrivate is provided and the size of private key in the sensitive area is not the correct size, a *TPMParameterError error with an error code of ErrorKeySize will be returned for parameter index 1.

If the Type field of inPublic is ObjectTypeECC, inPrivate is provided and the private key in the sensitive area is invalid, a *TPMParameterError error with an error code of ErrorKeySize will be returned for parameter index 1. If the public point specified in the Unique field of inPublic does not belong to the private key, a *TPMError with an error code of ErrorBinding will be returned.

If the Type field of inPublic is ObjectTypeECC, inPrivate is not provided and the size of the public key in the Unique field of inPublic is inconsistent with the value of the Params field of inPublic, a *TPMParameterError error with an error code of ErrorKey is returned for parameter index 2. If the public point is not on the curve specified in the Params field of inPublic, a *TPMParameterError error with an error code of ErrorECCPoint will be returned for parameter index 2.

If the Type field of inPublic is ObjectTypeSymCipher, inPrivate is provided and the size of the symmetric key in the sensitive area is inconsistent with the symmetric algorithm specified in the Params field of inPublic, a *TPMParameterError error with an error code of ErrorKeySize will be returned for parameter index 1.

If the Type field of inPublic is ObjectTypeKeyedHash, inPrivate is provided and the size of the sensitive data is larger than permitted for the digest algorithm selected by the scheme defined in the Params field of inPublic, a *TPMParameterError error with an error code of ErrorKeySize will be returned for parameter index 1.

If the Type field of inPublic is ObjectTypeSymCipher or ObjectTypeKeyedHash and inPrivate has not been provided, a *TPMParameterError error with an error code of ErrorKey will be returned for parameter index 2 if the size of the digest in the Unique field of inPublic does not match the selected name algorithm.

If the Type field of inPublic is ObjectTypeSymCipher or ObjectTypeKeyedHash, inPrivate has been provided and the size of seed value in the sensitive area does not match the name algorithm, a *TPMError error with an error code of ErrorKeySize will be returned. If the digest in the Unique field of inPublic is inconsistent with the value of the sensitive data and the seed value, a *TPMError with an error code of ErrorBinding will be returned.

On success, a ResourceContext corresponding to the newly loaded transient object will be returned. If inPrivate has been provided, it will not be necessary to call ResourceContext.SetAuthValue on it - this function sets the correct authorization value so that it can be used in subsequent commands that require knowledge of the authorization value. The return ResourceContext can be type asserted to ObjectContext.

func (*TPMContext) LockoutHandleContext

func (t *TPMContext) LockoutHandleContext() ResourceContext

LockoutHandleContext returns the ResourceContext corresponding to the lockout hiearchy.

func (*TPMContext) MakeCredential

func (t *TPMContext) MakeCredential(context ResourceContext, credential Digest, objectName Name, sessions ...SessionContext) (credentialBlob IDObject, secret EncryptedSecret, err error)

MakeCredential executes the TPM2_MakeCredential command to allow the TPM to perform the actions of a certificate authority, in order to create an activation credential.

The object associated with context must be the public part of a storage key, which would typically be the endorsement key of the TPM from which the request originates. The certificate authority would normally be in receipt of the TPM manufacturer issued endorsement certificate corresponding to this key and would have validated this. The certificate is an assertion from the manufacturer that the key is a valid endorsement key (a restricted, non-duplicable decrypt key) that is resident on a genuine TPM.

The credential parameter is the activation credential, which would typically be used to protect the generated certificate or supply a challenge. The objectName parameter is the name of object for which a certificate is requested. The public part of this object would normally be validated by the certificate authority to ensure that it has the properties expected of an attestation key (it is a restricted, non-duplicable signing key).

If context does not correspond to an asymmetric restricted decrypt key, a *TPMHandleError error with an error code of ErrorType is returned.

If the size of credential is larger than the name algorithm associated with context, a *TPMParameterError error with an error code of ErrorSize will be returned for parameter index 1.

If the algorithm of the object associated with context is ObjectTypeECC, a *TPMError with an error code of ErrorKey will be returned if the ECC key is invalid. If the algorithm of the object associated with context is ObjectTypeRSA, a *TPMError with an error code of ErrorScheme will be returned if the padding scheme is invalid or not supported.

On success, the encrypted and integrity protected activation credential is returned as IDObject (see section 24 - "Credential Protection" of Part 1 of the Trusted Platform Module Library specification). A secret which can be used by the private part of the key associated with context to recover the seed used to protect the credential (using the TPM2_ActivateCredential command) is returned as EncryptedSecret.

func (*TPMContext) NVChangeAuth

func (t *TPMContext) NVChangeAuth(nvIndex ResourceContext, newAuth Auth, nvIndexAuthSession SessionContext, sessions ...SessionContext) error

NVChangeAuth executes the TPM2_NV_ChangeAuth command to change the authorization value for the NV index associated with nvIndex, setting it to the new value defined by newAuth. The command requires the admin auth role for nvIndex, with the session provided via nvIndexAuthSession.

If the size of newAuth is greater than the name algorithm for the index, a *TPMParameterError error with an error code of ErrorSize will be returned.

On successful completion, the authorization value of the NV index associated with nvIndex will be set to the value of newAuth, and nvIndex will be updated to reflect this - it isn't necessary to update nvIndex with ResourceContext.SetAuthValue in order to use it in authorization roles that require knowledge of the authorization value for the index.

func (*TPMContext) NVDefineSpace

func (t *TPMContext) NVDefineSpace(authContext ResourceContext, auth Auth, publicInfo *NVPublic, authContextAuthSession SessionContext, sessions ...SessionContext) (ResourceContext, error)

NVDefineSpace executes the TPM2_NV_DefineSpace command to reserve space to hold the data associated with a NV index described by the publicInfo parameter. The Index field of publicInfo defines the handle at which the index should be reserved. The NameAlg field defines the digest algorithm for computing the name of the NV index. The Attrs field is used to describe attributes for the index, as well as its type. An authorization policy for the index can be defined using the AuthPolicy field of publicInfo. The Size field defines the size of the index.

The name algorithm must be linked into the current binary. To create an NV index with a name algorithm that is not available, use TPMContext.NVDefineSpaceRaw.

The auth parameter specifies an authorization value for the NV index.

The authContext parameter specifies the hierarchy used for authorization, and should correspond to HandlePlatform or HandleOwner. The command requires authorization with the user auth role for the specified hierarchy, with session based authorization provided via authContextAuthSession.

If the Attrs field of publicInfo has AttrNVPolicyDelete set but TPM2_NV_UndefineSpaceSpecial isn't supported, or the Attrs field defines a type that is unsupported, a *TPMParameterError error with an error code of ErrorAttributes will be returned for parameter index 2.

If the AuthPolicy field of publicInfo defines an authorization policy digest then the digest length must match the size of the name algorithm defined by the NameAlg field of publicInfo, else a *TPMParameterError error with an error code of ErrorSize will be returned for parameter index 2.

If the length of auth is greater than the name algorithm selected by the NameAlg field of the publicInfo parameter, a *TPMParameterError error with an error code of ErrorSize will be returned for parameter index 1.

If authContext corresponds to HandlePlatform but the AttrPhEnableNV attribute is clear, a *TPMHandleError error with an error code of ErrorHierarchy will be returned.

If the type indicated by the Attrs field of publicInfo isn't supported by the TPM, a *TPMParameterError error with an error code of ErrorAttributes will be returned for parameter index 2.

If the type defined by publicInfo is NVTypeCounter, NVTypeBits, NVTypePinPass or NVTypePinFail, the Size field of publicInfo must be 8. If the type defined by publicInfo is NVTypeExtend, the Size field of publicInfo must match the size of the name algorithm defined by the NameAlg field. If the size is unexpected, or the size for an index of type NVTypeOrdinary is too large, a *TPMParameterError error with an error code of ErrorSize will be returned for parameter index 2.

If the type defined by publicInfo is NVTypeCounter, then the Attrs field must not have the AttrNVClearStClear attribute set, else a *TPMParameterError error with an error code of ErrorAttributes will be returned for parameter index 2.

If the type defined by publicInfo is NVTypePinFail, then the Attrs field must have the AttrNVNoDA attribute set. If the type is either NVTypePinPass or NVTypePinFail, then the Attrs field must have the AttrNVAuthWrite, AttrNVGlobalLock and AttrNVWriteDefine attributes clear, else a *TPMParameterError error with an error code of ErrorAttributes will be returned for parameter index 2.

If the Attrs field of publicInfo has either AttrNVWriteLocked, AttrNVReadLocked or AttrNVWritten set, a *TPMParameterError error with an error code of ErrorAttributes will be returned for parameter index 2.

The Attrs field of publicInfo must have one of either AttrNVPPWrite, AttrNVOwnerWrite, AttrNVAuthWrite or AttrNVPolicyWrite set, and must also have one of either AttrNVPPRead, AttrNVOwnerRead, AttrNVAuthRead or [AttrNVPolicyRead set]. If there is no way to read or write an index, a *TPMParameterError error with an error code of ErrorAttributes will be returned for parameter index 2.

If the Attrs field of publicInfo has AttrNVClearStClear set, a *TPMParameterError error with an error code of ErrorAttributes will be returned for parameter index 2 if AttrNVWriteDefine is set.

If authContext corresponds to HandlePlatform, then the Attrs field of publicInfo must have the AttrNVPlatformCreate attribute set. If authContext corresponds to HandleOwner, then the AttrNVPlatformCreate attributes must be clear, else a *TPMHandleError error with an error code of ErrorAttributes will be returned.

If the Attrs field of publicInfo has the AttrNVPolicyDelete attribute set, then HandlePlatform must be used for authorization via authContext, else a *TPMParameterError error with an error code of ErrorAttributes will be returned for parameter index 2.

If an index is already defined at the location specified by the Index field of publicInfo, a *TPMError error with an error code of ErrorNVDefined will be returned.

If there is insufficient space for the index, a *TPMError error with an error code of ErrorNVSpace will be returned.

On successful completion, the NV index will be defined and a ResourceContext corresponding to the new index will be returned. It will not be necessary to call ResourceContext.SetAuthValue on the returned ResourceContext - this function sets the correct authorization value so that it can be used in subsequent commands that require knowledge of it. The returned ResourceContext can be type asserted to NVIndexContext.

func (*TPMContext) NVDefineSpaceRaw added in v1.1.0

func (t *TPMContext) NVDefineSpaceRaw(authContext ResourceContext, auth Auth, publicInfo *NVPublic, authContextAuthSession SessionContext, sessions ...SessionContext) error

NVDefineSpaceRaw executes the TPM2_NV_DefineSpace command to reserve space to hold the data associated with a NV index described by the publicInfo parameter. The Index field of publicInfo defines the handle at which the index should be reserved. The NameAlg field defines the digest algorithm for computing the name of the NV index. The Attrs field is used to describe attributes for the index, as well as its type. An authorization policy for the index can be defined using the AuthPolicy field of publicInfo. The Size field defines the size of the index.

The auth parameter specifies an authorization value for the NV index.

The authContext parameter specifies the hierarchy used for authorization, and should correspond to HandlePlatform or HandleOwner. The command requires authorization with the user auth role for the specified hierarchy, with session based authorization provided via authContextAuthSession.

If the Attrs field of publicInfo has AttrNVPolicyDelete set but TPM2_NV_UndefineSpaceSpecial isn't supported, or the Attrs field defines a type that is unsupported, a *TPMParameterError error with an error code of ErrorAttributes will be returned for parameter index 2.

If the AuthPolicy field of publicInfo defines an authorization policy digest then the digest length must match the size of the name algorithm defined by the NameAlg field of publicInfo, else a *TPMParameterError error with an error code of ErrorSize will be returned for parameter index 2.

If the length of auth is greater than the name algorithm selected by the NameAlg field of the publicInfo parameter, a *TPMParameterError error with an error code of ErrorSize will be returned for parameter index 1.

If authContext corresponds to HandlePlatform but the AttrPhEnableNV attribute is clear, a *TPMHandleError error with an error code of ErrorHierarchy will be returned.

If the type indicated by the Attrs field of publicInfo isn't supported by the TPM, a *TPMParameterError error with an error code of ErrorAttributes will be returned for parameter index 2.

If the type defined by publicInfo is NVTypeCounter, NVTypeBits, NVTypePinPass or NVTypePinFail, the Size field of publicInfo must be 8. If the type defined by publicInfo is NVTypeExtend, the Size field of publicInfo must match the size of the name algorithm defined by the NameAlg field. If the size is unexpected, or the size for an index of type NVTypeOrdinary is too large, a *TPMParameterError error with an error code of ErrorSize will be returned for parameter index 2.

If the type defined by publicInfo is NVTypeCounter, then the Attrs field must not have the AttrNVClearStClear attribute set, else a *TPMParameterError error with an error code of ErrorAttributes will be returned for parameter index 2.

If the type defined by publicInfo is NVTypePinFail, then the Attrs field must have the AttrNVNoDA attribute set. If the type is either NVTypePinPass or NVTypePinFail, then the Attrs field must have the AttrNVAuthWrite, AttrNVGlobalLock and AttrNVWriteDefine attributes clear, else a *TPMParameterError error with an error code of ErrorAttributes will be returned for parameter index 2.

If the Attrs field of publicInfo has either AttrNVWriteLocked, AttrNVReadLocked or AttrNVWritten set, a *TPMParameterError error with an error code of ErrorAttributes will be returned for parameter index 2.

The Attrs field of publicInfo must have one of either AttrNVPPWrite, AttrNVOwnerWrite, AttrNVAuthWrite or AttrNVPolicyWrite set, and must also have one of either AttrNVPPRead, AttrNVOwnerRead, AttrNVAuthRead or [AttrNVPolicyRead set]. If there is no way to read or write an index, a *TPMParameterError error with an error code of ErrorAttributes will be returned for parameter index 2.

If the Attrs field of publicInfo has AttrNVClearStClear set, a *TPMParameterError error with an error code of ErrorAttributes will be returned for parameter index 2 if AttrNVWriteDefine is set.

If authContext corresponds to HandlePlatform, then the Attrs field of publicInfo must have the AttrNVPlatformCreate attribute set. If authContext corresponds to HandleOwner, then the AttrNVPlatformCreate attributes must be clear, else a *TPMHandleError error with an error code of ErrorAttributes will be returned.

If the Attrs field of publicInfo has the AttrNVPolicyDelete attribute set, then HandlePlatform must be used for authorization via authContext, else a *TPMParameterError error with an error code of ErrorAttributes will be returned for parameter index 2.

If an index is already defined at the location specified by the Index field of publicInfo, a *TPMError error with an error code of ErrorNVDefined will be returned.

If there is insufficient space for the index, a *TPMError error with an error code of ErrorNVSpace will be returned.

On successful completion, the NV index will be defined.

func (*TPMContext) NVExtend

func (t *TPMContext) NVExtend(authContext, nvIndex ResourceContext, data MaxNVBuffer, authContextAuthSession SessionContext, sessions ...SessionContext) error

NVExtend executes the TPM2_NV_Extend command to extend data to the NV index associated with nvIndex, using the index's name algorithm.

The command requires authorization, defined by the state of the AttrNVPPWrite, AttrNVOwnerWrite, AttrNVAuthWrite and AttrNVPolicyWrite attributes. The handle used for authorization is specified via authContext. If the NV index has the AttrNVPPWrite attribute, authorization can be satisfied with HandlePlatform. If the NV index has the AttrNVOwnerWrite attribute, authorization can be satisfied with HandleOwner. If the NV index has the AttrNVAuthWrite or AttrNVPolicyWrite attribute, authorization can be satisfied with nvIndex. The command requires authorization with the user auth role for authContext, with session based authorization provided via authContextAuthSession. If the resource associated with authContext is not permitted to authorize this access, a *TPMError error with an error code of ErrorNVAuthorization will be returned.

If nvIndex is being used for authorization and the AttrNVAuthWrite attribute is defined, the authorization can be satisfied by demonstrating knowledge of the authorization value, either via cleartext or HMAC authorization. If nvIndex is being used for authorization and the AttrNVPolicyWrite attribute is defined, the authorization can be satisfied using a policy session with a digest that matches the authorization policy for the index.

If the index has the AttrNVWriteLocked attribute set, a *TPMError error with an error code of ErrorNVLocked will be returned.

If the type of the index is not NVTypeExtend, a *TPMHandleError error with an error code of ErrorAttributes will be returned for handle index 2.

On successful completion, the AttrNVWritten flag will be set if this is the first time that the index has been written to. If nvIndex can be type asserted to NVIndexContext, the name of nvIndex will be updated accordingly.

func (*TPMContext) NVGlobalWriteLock

func (t *TPMContext) NVGlobalWriteLock(authContext ResourceContext, authContextAuthSession SessionContext, sessions ...SessionContext) error

NVGlobalWriteLock executes the TPM2_NV_GlobalWriteLock command to inhibit further writes for all NV indexes that have the AttrNVGlobalLock attribute set.

The authContext parameter specifies a hierarchy, and should correspond to either HandlePlatform or HandleOwner. The command requires the user auth role for authContext, with session based authorization provided via authContextAuthSession.

On successful completion, the AttrNVWriteLocked attribute will be set for all NV indexes that have the AttrNVGlobalLock attribute set. If an index also has the AttrNVWriteDefine attribute set, this will permanently inhibit further writes unless AttrNVWritten is clear. ResourceContext instances associated with NV indices that are updated as a consequence of this function will no longer be able to be used because the name will be incorrect.

func (*TPMContext) NVIncrement

func (t *TPMContext) NVIncrement(authContext, nvIndex ResourceContext, authContextAuthSession SessionContext, sessions ...SessionContext) error

NVIncrement executes the TPM2_NV_Increment command to increment the counter associated with nvIndex.

The command requires authorization, defined by the state of the AttrNVPPWrite, AttrNVOwnerWrite, AttrNVAuthWrite and AttrNVPolicyWrite attributes. The handle used for authorization is specified via authContext. If the NV index has the AttrNVPPWrite attribute, authorization can be satisfied with HandlePlatform. If the NV index has the AttrNVOwnerWrite attribute, authorization can be satisfied with HandleOwner. If the NV index has the AttrNVAuthWrite or AttrNVPolicyWrite attribute, authorization can be satisfied with nvIndex. The command requires authorization with the user auth role for authContext, with session based authorization provided via authContextAuthSession. If the resource associated with authContext is not permitted to authorize this access, a *TPMError error with an error code of ErrorNVAuthorization will be returned.

If nvIndex is being used for authorization and the AttrNVAuthWrite attribute is defined, the authorization can be satisfied by demonstrating knowledge of the authorization value, either via cleartext or HMAC authorization. If nvIndex is being used for authorization and the AttrNVPolicyWrite attribute is defined, the authorization can be satisfied using a policy session with a digest that matches the authorization policy for the index.

If the index has the AttrNVWriteLocked attribute set, a *TPMError error with an error code of ErrorNVLocked will be returned.

If the type of the index is not NVTypeCounter, a *TPMHandleError error with an error code of ErrorAttributes will be returned for handle index 2.

On successful completion, the AttrNVWritten flag will be set if this is the first time that the index has been written to. If nvIndex can be type asserted to NVIndexContext, the name of nvIndex will be updated accordingly.

func (*TPMContext) NVRead

func (t *TPMContext) NVRead(authContext, nvIndex ResourceContext, size, offset uint16, authContextAuthSession SessionContext, sessions ...SessionContext) (data []byte, err error)

NVRead executes the TPM2_NV_Read command to read the contents of the NV index associated with nvIndex. The amount of data to read, and the offset within the index are defined by the size and offset parameters.

The command requires authorization, defined by the state of the AttrNVPPRead, AttrNVOwnerRead, AttrNVAuthRead and AttrNVPolicyRead attributes. The handle used for authorization is specified via authContext. If the NV index has the AttrNVPPRead attribute, authorization can be satisfied with HandlePlatform. If the NV index has the AttrNVOwnerRead attribute, authorization can be satisfied with HandleOwner. If the NV index has the AttrNVAuthRead or AttrNVPolicyRead attribute, authorization can be satisfied with nvIndex. The command requires authorization with the user auth role for authContext, with session based authorization provided via authContextAuthSession. If the resource associated with authContext is not permitted to authorize this access, a *TPMError error with an error code of ErrorNVAuthorization will be returned.

If nvIndex is being used for authorization and the AttrNVAuthRead attribute is defined, the authorization can be satisfied by demonstrating knowledge of the authorization value, either via cleartext or HMAC authorization. If nvIndex is being used for authorization and the AttrNVPolicyRead attribute is defined, the authorization can be satisfied using a policy session with a digest that matches the authorization policy for the index.

If the requested data can not be read in a single command, this function will re-execute the TPM2_NV_Read command until all data is read. In this case, authContextAuth should not correspond to a policy session.

If the index has the AttrNVReadLocked attribute set, a *TPMError error with an error code of ErrorNVLocked will be returned.

If the index has not been initialized (ie, the AttrNVWritten attribute is not set), a *TPMError error with an error code of ErrorNVUninitialized will be returned.

If the value of size is too large, a *TPMParameterError error with an error code of ErrorValue will be returned for parameter index 1.

If the value of offset falls outside of the bounds of the index, a *TPMParameterError error with an error code of ErrorValue will be returned for parameter index 2.

If the data selection falls outside of the bounds of the index, a *TPMError error with an error code of ErrorNVRange will be returned.

On successful completion, the requested data will be returned.

func (*TPMContext) NVReadBits

func (t *TPMContext) NVReadBits(authContext, nvIndex ResourceContext, authContextAuthSession SessionContext, sessions ...SessionContext) (uint64, error)

NVReadBits is a convenience function for TPMContext.NVRead for reading the contents of the NV bit field index associated with nvIndex. If the type of nvIndex is not NVTypeBits, an error will be returned. This will return an error if nvIndex cannot be type asserted to NVIndexContext.

The command requires authorization, defined by the state of the AttrNVPPRead, AttrNVOwnerRead, AttrNVAuthRead and AttrNVPolicyRead attributes. The handle used for authorization is specified via authContext. If the NV index has the AttrNVPPRead attribute, authorization can be satisfied with HandlePlatform. If the NV index has the AttrNVOwnerRead attribute, authorization can be satisfied with HandleOwner. If the NV index has the AttrNVAuthRead or AttrNVPolicyRead attribute, authorization can be satisfied with nvIndex. The command requires authorization with the user auth role for authContext, with session based authorization provided via authContextAuthSession. If the resource associated with authContext is not permitted to authorize this access, a *TPMError error with an error code of ErrorNVAuthorization will be returned.

If nvIndex is being used for authorization and the AttrNVAuthRead attribute is defined, the authorization can be satisfied by demonstrating knowledge of the authorization value, either via cleartext or HMAC authorization. If nvIndex is being used for authorization and the AttrNVPolicyRead attribute is defined, the authorization can be satisfied using a policy session with a digest that matches the authorization policy for the index.

If the index has the AttrNVReadLocked attribute set, a *TPMError error with an error code of ErrorNVLocked will be returned.

If the index has not been initialized (ie, the AttrNVWritten attribute is not set), a *TPMError error with an error code of ErrorNVUninitialized will be returned.

On successful completion, the current bitfield value will be returned.

func (*TPMContext) NVReadCounter

func (t *TPMContext) NVReadCounter(authContext, nvIndex ResourceContext, authContextAuthSession SessionContext, sessions ...SessionContext) (uint64, error)

NVReadCounter is a convenience function for TPMContext.NVRead for reading the contents of the NV counter index associated with nvIndex. If the type of nvIndex is not NVTypeCounter, an error will be returned. This will return an error if nvIndex cannot be type asserted to NVIndexContext.

The command requires authorization, defined by the state of the AttrNVPPRead, AttrNVOwnerRead, AttrNVAuthRead and AttrNVPolicyRead attributes. The handle used for authorization is specified via authContext. If the NV index has the AttrNVPPRead attribute, authorization can be satisfied with HandlePlatform. If the NV index has the AttrNVOwnerRead attribute, authorization can be satisfied with HandleOwner. If the NV index has the AttrNVAuthRead or AttrNVPolicyRead attribute, authorization can be satisfied with nvIndex. The command requires authorization with the user auth role for authContext, with session based authorization provided via authContextAuthSession. If the resource associated with authContext is not permitted to authorize this access, a *TPMError error with an error code of ErrorNVAuthorization will be returned.

If nvIndex is being used for authorization and the AttrNVAuthRead attribute is defined, the authorization can be satisfied by demonstrating knowledge of the authorization value, either via cleartext or HMAC authorization. If nvIndex is being used for authorization and the AttrNVPolicyRead attribute is defined, the authorization can be satisfied using a policy session with a digest that matches the authorization policy for the index.

If the index has the AttrNVReadLocked attribute set, a *TPMError error with an error code of ErrorNVLocked will be returned.

If the index has not been initialized (ie, the AttrNVWritten attribute is not set), a *TPMError error with an error code of ErrorNVUninitialized will be returned.

On successful completion, the current counter value will be returned.

func (*TPMContext) NVReadLock

func (t *TPMContext) NVReadLock(authContext, nvIndex ResourceContext, authContextAuthSession SessionContext, sessions ...SessionContext) error

NVReadLock executes the TPM2_NV_ReadLock command to inhibit further reads of the NV index associated with nvIndex.

The command requires authorization, defined by the state of the AttrNVPPRead, AttrNVOwnerRead, AttrNVAuthRead and AttrNVPolicyRead attributes. The handle used for authorization is specified via authContext. If the NV index has the AttrNVPPRead attribute, authorization can be satisfied with HandlePlatform. If the NV index has the AttrNVOwnerRead attribute, authorization can be satisfied with HandleOwner. If the NV index has the AttrNVAuthRead or AttrNVPolicyRead attribute, authorization can be satisfied with nvIndex. The command requires authorization with the user auth role for authContext, with session based authorization provided via authContextAuthSession. If the resource associated with authContext is not permitted to authorize this access, a *TPMError error with an error code of ErrorNVAuthorization will be returned.

If nvIndex is being used for authorization and the AttrNVAuthRead attribute is defined, the authorization can be satisfied by demonstrating knowledge of the authorization value, either via cleartext or HMAC authorization. If nvIndex is being used for authorization and the AttrNVPolicyRead attribute is defined, the authorization can be satisfied using a policy session with a digest that matches the authorization policy for the index.

If the index doesn't have the AttrNVReadStClear attribute set, then a *TPMHandleError error with an error code of ErrorAttributes will be returned for handle index 2.

On successful completion, the AttrNVReadLocked attribute will be set. If nvIndex can be type asserted to NVIndexContext, the name of nvIndex will be updated accordingly. The attribute will be cleared again (and reads will be reenabled) on the next TPM reset or TPM restart.

func (*TPMContext) NVReadPinCounterParams

func (t *TPMContext) NVReadPinCounterParams(authContext, nvIndex ResourceContext, authContextAuthSession SessionContext, sessions ...SessionContext) (*NVPinCounterParams, error)

NVReadPinCounterParams is a convenience function for TPMContext.NVRead for reading the contents of the NV pin pass or NV pin fail index associated with nvIndex. If the type of nvIndex is not NVTypePinPass or NVTypePinFail, an error will be returned. This will return an error if nvIndex cannot be type asserted to NVIndexContext.

The command requires authorization, defined by the state of the AttrNVPPRead, AttrNVOwnerRead, AttrNVAuthRead and AttrNVPolicyRead attributes. The handle used for authorization is specified via authContext. If the NV index has the AttrNVPPRead attribute, authorization can be satisfied with HandlePlatform. If the NV index has the AttrNVOwnerRead attribute, authorization can be satisfied with HandleOwner. If the NV index has the AttrNVAuthRead or AttrNVPolicyRead attribute, authorization can be satisfied with nvIndex. The command requires authorization with the user auth role for authContext, with session based authorization provided via authContextAuthSession. If the resource associated with authContext is not permitted to authorize this access, a *TPMError error with an error code of ErrorNVAuthorization will be returned.

If nvIndex is being used for authorization and the AttrNVAuthRead attribute is defined, the authorization can be satisfied by demonstrating knowledge of the authorization value, either via cleartext or HMAC authorization. If nvIndex is being used for authorization and the AttrNVPolicyRead attribute is defined, the authorization can be satisfied using a policy session with a digest that matches the authorization policy for the index.

If the index has the AttrNVReadLocked attribute set, a *TPMError error with an error code of ErrorNVLocked will be returned.

If the index has not been initialized (ie, the AttrNVWritten attribute is not set), a *TPMError error with an error code of ErrorNVUninitialized will be returned.

On successful completion, the current PIN count and limit will be returned.

func (*TPMContext) NVReadPublic

func (t *TPMContext) NVReadPublic(nvIndex HandleContext, sessions ...SessionContext) (nvPublic *NVPublic, nvName Name, err error)

NVReadPublic executes the TPM2_NV_ReadPublic command to read the public area of the NV index associated with nvIndex.

func (*TPMContext) NVReadRaw

func (t *TPMContext) NVReadRaw(authContext, nvIndex ResourceContext, size, offset uint16, authContextAuthSession SessionContext, sessions ...SessionContext) (data MaxNVBuffer, err error)

NVReadRaw executes the TPM2_NV_Read command to read the contents of the NV index associated with nvIndex. The amount of data to read, and the offset within the index are defined by the size and offset parameters.

The command requires authorization, defined by the state of the AttrNVPPRead, AttrNVOwnerRead, AttrNVAuthRead and AttrNVPolicyRead attributes. The handle used for authorization is specified via authContext. If the NV index has the AttrNVPPRead attribute, authorization can be satisfied with HandlePlatform. If the NV index has the AttrNVOwnerRead attribute, authorization can be satisfied with HandleOwner. If the NV index has the AttrNVAuthRead or AttrNVPolicyRead attribute, authorization can be satisfied with nvIndex. The command requires authorization with the user auth role for authContext, with session based authorization provided via authContextAuthSession. If the resource associated with authContext is not permitted to authorize this access, a *TPMError error with an error code of ErrorNVAuthorization will be returned.

If nvIndex is being used for authorization and the AttrNVAuthRead attribute is defined, the authorization can be satisfied by demonstrating knowledge of the authorization value, either via cleartext or HMAC authorization. If nvIndex is being used for authorization and the AttrNVPolicyRead attribute is defined, the authorization can be satisfied using a policy session with a digest that matches the authorization policy for the index.

If the index has the AttrNVReadLocked attribute set, a *TPMError error with an error code of ErrorNVLocked will be returned.

If the index has not been initialized (ie, the AttrNVWritten attribute is not set), a *TPMError error with an error code of ErrorNVUninitialized will be returned.

If the value of size is too large, a *TPMParameterError error with an error code of ErrorValue will be returned for parameter index 1.

If the value of offset falls outside of the bounds of the index, a *TPMParameterError error with an error code of ErrorValue will be returned for parameter index 2.

If the data selection falls outside of the bounds of the index, a *TPMError error with an error code of ErrorNVRange will be returned.

On successful completion, the requested data will be returned.

func (*TPMContext) NVSetBits

func (t *TPMContext) NVSetBits(authContext, nvIndex ResourceContext, bits uint64, authContextAuthSession SessionContext, sessions ...SessionContext) error

NVSetBits executes the TPM2_NV_SetBits command to OR the value of bits with the contents of the NV index associated with nvIndex.

The command requires authorization, defined by the state of the AttrNVPPWrite, AttrNVOwnerWrite, AttrNVAuthWrite and AttrNVPolicyWrite attributes. The handle used for authorization is specified via authContext. If the NV index has the AttrNVPPWrite attribute, authorization can be satisfied with HandlePlatform. If the NV index has the AttrNVOwnerWrite attribute, authorization can be satisfied with HandleOwner. If the NV index has the AttrNVAuthWrite or AttrNVPolicyWrite attribute, authorization can be satisfied with nvIndex. The command requires authorization with the user auth role for authContext, with session based authorization provided via authContextAuthSession. If the resource associated with authContext is not permitted to authorize this access, a *TPMError error with an error code of ErrorNVAuthorization will be returned.

If nvIndex is being used for authorization and the AttrNVAuthWrite attribute is defined, the authorization can be satisfied by demonstrating knowledge of the authorization value, either via cleartext or HMAC authorization. If nvIndex is being used for authorization and the AttrNVPolicyWrite attribute is defined, the authorization can be satisfied using a policy session with a digest that matches the authorization policy for the index.

If the index has the AttrNVWriteLocked attribute set, a *TPMError error with an error code of ErrorNVLocked will be returned.

If the type of the index is not NVTypeBits, a *TPMHandleError error with an error code of ErrorAttributes will be returned for handle index 2.

On successful completion, the AttrNVWritten flag will be set if this is the first time that the index has been written to. If nvIndex can be type asserted to NVIndexContext, the name of nvIndex will be updated accordingly.

func (*TPMContext) NVSetPinCounterParams

func (t *TPMContext) NVSetPinCounterParams(authContext, nvIndex ResourceContext, params *NVPinCounterParams, authContextAuthSession SessionContext, sessions ...SessionContext) error

NVSetPinCounterParams is a convenience function for TPMContext.NVWrite for updating the contents of the NV pin pass or NV pin fail index associated with nvIndex. If the type of nvIndex is not NVTypePinPass of NVTypePinFail, an error will be returned. This will return an error if nvIndex cannot be type asserted to NVIndexContext.

The command requires authorization, defined by the state of the AttrNVPPWrite, AttrNVOwnerWrite, AttrNVAuthWrite and AttrNVPolicyWrite attributes. The handle used for authorization is specified via authContext. If the NV index has the AttrNVPPWrite attribute, authorization can be satisfied with HandlePlatform. If the NV index has the AttrNVOwnerWrite attribute, authorization can be satisfied with HandleOwner. If the NV index has the AttrNVAuthWrite or AttrNVPolicyWrite attribute, authorization can be satisfied with nvIndex. The command requires authorization with the user auth role for authContext, with session based authorization provided via authContextAuthSession. If the resource associated with authContext is not permitted to authorize this access, a *TPMError error with an error code of ErrorNVAuthorization will be returned.

If nvIndex is being used for authorization and the AttrNVAuthWrite attribute is defined, the authorization can be satisfied by demonstrating knowledge of the authorization value, either via cleartext or HMAC authorization. If nvIndex is being used for authorization and the AttrNVPolicyWrite attribute is defined, the authorization can be satisfied using a policy session with a digest that matches the authorization policy for the index.

If the index has the AttrNVWriteLocked attribute set, a *TPMError error with an error code of ErrorNVLocked will be returned.

On successful completion, the AttrNVWritten flag will be set if this is the first time that the index has been written to. If nvIndex can be type asserted to NVIndexContext, the name of nvIndex will be updated accordingly.

func (*TPMContext) NVUndefineSpace

func (t *TPMContext) NVUndefineSpace(authContext, nvIndex ResourceContext, authContextAuthSession SessionContext, sessions ...SessionContext) error

NVUndefineSpace executes the TPM2_NV_UndefineSpace command to remove the NV index associated with nvIndex, and free the resources used by it. If the index has the AttrNVPolicyDelete attribute set, then a *TPMHandleError error with an error code of ErrorAttributes will be returned for handle index 2.

The authContext parameter specifies the hierarchy used for authorization and should correspond to either HandlePlatform or HandleOwner. The command requires authorization with the user auth role for the specified hierarchy, with session based authorization provided via authContextAuthSession.

If authContext corresponds to HandleOwner and the NV index has the AttrNVPlatformCreate attribute set, then a *TPMError error with an error code of ErrorNVAuthorization will be returned.

On successful completion, nvIndex will be invalidated.

func (*TPMContext) NVUndefineSpaceSpecial

func (t *TPMContext) NVUndefineSpaceSpecial(nvIndex, platform ResourceContext, nvIndexAuthSession, platformAuthSession SessionContext, sessions ...SessionContext) error

NVUndefineSpaceSpecial executes the TPM2_NV_UndefineSpaceSpecial command to remove the NV index associated with nvIndex, and free the resources used by it. If the NV index does not have the AttrNVPolicyDelete attribute set, then a *TPMHandleError error with an error code of ErrorAttributes will be returned for handle index 1.

The platform parameter must correspond to HandlePlatform. The command requires authorization with the user auth role for the platform hierarchy, with session based authorization provided via platformAuthSession. The command requires authorization with the admin role for nvIndex, with the session provided via nvIndexAuthSession.

On successful completion, nvIndex will be invalidated.

func (*TPMContext) NVWrite

func (t *TPMContext) NVWrite(authContext, nvIndex ResourceContext, data []byte, offset uint16, authContextAuthSession SessionContext, sessions ...SessionContext) error

NVWrite executes the TPM2_NV_Write command to write data to the NV index associated with nvIndex, at the specified offset.

The command requires authorization, defined by the state of the AttrNVPPWrite, AttrNVOwnerWrite, AttrNVAuthWrite and AttrNVPolicyWrite attributes. The handle used for authorization is specified via authContext. If the NV index has the AttrNVPPWrite attribute, authorization can be satisfied with HandlePlatform. If the NV index has the AttrNVOwnerWrite attribute, authorization can be satisfied with HandleOwner. If the NV index has the AttrNVAuthWrite or AttrNVPolicyWrite attribute, authorization can be satisfied with nvIndex. The command requires authorization with the user auth role for authContext, with session based authorization provided via authContextAuthSession. If the resource associated with authContext is not permitted to authorize this access, a *TPMError error with an error code of ErrorNVAuthorization will be returned.

If nvIndex is being used for authorization and the AttrNVAuthWrite attribute is defined, the authorization can be satisfied by demonstrating knowledge of the authorization value, either via cleartext or HMAC authorization. If nvIndex is being used for authorization and the AttrNVPolicyWrite attribute is defined, the authorization can be satisfied using a policy session with a digest that matches the authorization policy for the index.

If data is too large to be written in a single command, this function will re-execute the TPM2_NV_Write command until all data is written. In this case, authContextAuthSession must not be a policy session.

If the index has the AttrNVWriteLocked attribute set, a *TPMError error with an error code of ErrorNVLocked will be returned.

If the type of the index is NVTypeCounter, NVTypeBits or NVTypeExtend, a *TPMError error with an error code of ErrorAttributes will be returned.

If the value of offset is outside of the bounds of the index, a *TPMParameterError error with an error code of ErrorValue will be returned for parameter index 2.

If the length of the data and the specified offset would result in a write outside of the bounds of the index, or if the index has the AttrNVWriteAll attribute set and the size of the data doesn't match the size of the index, a *TPMError error with an error code of ErrorNVRange will be returned.

On successful completion, the AttrNVWritten flag will be set if this is the first time that the index has been written to. If nvIndex can be type asserted to NVIndexContext, the name of nvIndex will be updated accordingly.

func (*TPMContext) NVWriteLock

func (t *TPMContext) NVWriteLock(authContext, nvIndex ResourceContext, authContextAuthSession SessionContext, sessions ...SessionContext) error

NVWriteLock executes the TPM2_NV_WriteLock command to inhibit further writes to the NV index associated with nvIndex.

The command requires authorization, defined by the state of the AttrNVPPWrite, AttrNVOwnerWrite, AttrNVAuthWrite and AttrNVPolicyWrite attributes. The handle used for authorization is specified via authContext. If the NV index has the AttrNVPPWrite attribute, authorization can be satisfied with HandlePlatform. If the NV index has the AttrNVOwnerWrite attribute, authorization can be satisfied with HandleOwner. If the NV index has the AttrNVAuthWrite or AttrNVPolicyWrite attribute, authorization can be satisfied with nvIndex. The command requires authorization with the user auth role for authContext, with session based authorization provided via authContextAuthSession. If the resource associated with authContext is not permitted to authorize this access, a *TPMError error with an error code of ErrorNVAuthorization will be returned.

If nvIndex is being used for authorization and the AttrNVAuthWrite attribute is defined, the authorization can be satisfied by demonstrating knowledge of the authorization value, either via cleartext or HMAC authorization. If nvIndex is being used for authorization and the AttrNVPolicyWrite attribute is defined, the authorization can be satisfied using a policy session with a digest that matches the authorization policy for the index.

If the index has neither the AttrNVWriteDefine or AttrNVWriteStClear attributes set, then a *TPMHandleError error with an error code of ErrorAttributes will be returned for handle index 2.

On successful completion, the AttrNVWriteLocked attribute will be set. If nvIndex can be type asserted to NVIndexContext, the name of nvIndex will be updated accordingly. The attribute will be cleared again (and writes will be reenabled) on the next TPM reset or TPM restart unless the index has the AttrNVWriteDefine attribute set and AttrNVWritten attribute is set.

func (*TPMContext) NVWriteRaw

func (t *TPMContext) NVWriteRaw(authContext, nvIndex ResourceContext, data MaxNVBuffer, offset uint16, authContextAuthSession SessionContext, sessions ...SessionContext) error

NVWriteRaw executes the TPM2_NV_Write command to write data to the NV index associated with nvIndex, at the specified offset.

The command requires authorization, defined by the state of the AttrNVPPWrite, AttrNVOwnerWrite, AttrNVAuthWrite and AttrNVPolicyWrite attributes. The handle used for authorization is specified via authContext. If the NV index has the AttrNVPPWrite attribute, authorization can be satisfied with HandlePlatform. If the NV index has the AttrNVOwnerWrite attribute, authorization can be satisfied with HandleOwner. If the NV index has the AttrNVAuthWrite or AttrNVPolicyWrite attribute, authorization can be satisfied with nvIndex. The command requires authorization with the user auth role for authContext, with session based authorization provided via authContextAuthSession. If the resource associated with authContext is not permitted to authorize this access, a *TPMError error with an error code of ErrorNVAuthorization will be returned.

If nvIndex is being used for authorization and the AttrNVAuthWrite attribute is defined, the authorization can be satisfied by demonstrating knowledge of the authorization value, either via cleartext or HMAC authorization. If nvIndex is being used for authorization and the AttrNVPolicyWrite attribute is defined, the authorization can be satisfied using a policy session with a digest that matches the authorization policy for the index.

If the index has the AttrNVWriteLocked attribute set, a *TPMError error with an error code of ErrorNVLocked will be returned.

If the type of the index is NVTypeCounter, NVTypeBits or NVTypeExtend, a *TPMError error with an error code of ErrorAttributes will be returned.

If the value of offset is outside of the bounds of the index, a *TPMParameterError error with an error code of ErrorValue will be returned for parameter index 2.

If the length of the data and the specified offset would result in a write outside of the bounds of the index, or if the index has the AttrNVWriteAll attribute set and the size of the data doesn't match the size of the index, a *TPMError error with an error code of ErrorNVRange will be returned.

On successful completion, the AttrNVWritten flag will be set if this is the first time that the index has been written to. If nvIndex can be type asserted to NVIndexContext, the name of nvIndex will be updated accordingly.

func (*TPMContext) NewResourceContext added in v1.1.0

func (t *TPMContext) NewResourceContext(handle Handle, sessions ...SessionContext) (ResourceContext, error)

NewResourceContext creates and returns a new ResourceContext for the specified handle. It will execute a command to read the public area from the TPM in order to initialize state that is maintained on the host side. A *ResourceUnavailableError error will be returned if the specified handle references a resource that doesn't exist.

The public area and name returned from the TPM are checked for consistency as long as the corresponding name algorithm is linked into the current binary.

If any sessions are supplied, the public area is read from the TPM twice. The second time uses the supplied sessions.

This function will return an error if handle doesn't correspond to a NV index, transient object or persistent object.

If subsequent use of the returned ResourceContext requires knowledge of the authorization value of the corresponding TPM resource, this should be provided by calling ResourceContext.SetAuthValue.

If the specified handle is an object, the returned context can be type asserted to ObjectContext. If the specified handle is a NV index, the returned context can be type asserted to NVIndexContext.

func (*TPMContext) NullHandleContext

func (t *TPMContext) NullHandleContext() ResourceContext

NulHandleContext returns the ResourceContext corresponding to the null hiearchy.

func (*TPMContext) ObjectChangeAuth

func (t *TPMContext) ObjectChangeAuth(objectContext, parentContext ResourceContext, newAuth Auth, objectContextAuthSession SessionContext, sessions ...SessionContext) (outPrivate Private, err error)

ObjectChangeAuth executes the TPM2_ObjectChangeAuth to change the authorization value of the object associated with objectContext. This command requires authorization with the admin role for objectContext, with sessio based authorization provided via objectContextAuthSession.

The new authorization value is provided via newAuth. The parentContext parameter must correspond to the parent object for objectContext. No authorization is required for parentContext.

If the object associated with objectContext is a sequence object, a *TPMHandleError error with an error code of ErrorType will be returned for handle index 1.

If the length of newAuth is longer than the name algorithm for objectContext, a *TPMParameterError error with an error code of ErrorSize will be returned.

If the object associated with parentContext is not the parent object of objectContext, a *TPMHandleError error with an error code of ErrorType will be returned for handle index 2.

On success, this returns a new private area for the object associated with objectContext. This function does not make any changes to the version of the object that is currently loaded in to the TPM.

func (*TPMContext) OwnerHandleContext

func (t *TPMContext) OwnerHandleContext() ResourceContext

OwnerHandleContext returns the ResouceContext corresponding to the owner hiearchy.

func (*TPMContext) PCRAllocate added in v1.7.6

func (t *TPMContext) PCRAllocate(authContext ResourceContext, pcrAllocation PCRSelectionList, authContextAuthSession SessionContext, sessions ...SessionContext) (allocationSuccess bool, maxPCR uint32, sizeNeeded uint32, sizeAvailable uint32, err error)

PCRAllocate executes the TPM2_PCR_Allocate command to set the PCR allocation, which is persistent even across TPM2_Clear. The supplied authContext parameter must correspond to HandlePlatform. This command requires authorization of authContext with the user auth role, with session based authorization provided via authContextAuthSession.

The desired PCR allocation is supplied via the pcrAllocation argument. The function indicates whether the allocation was successful. This will only be true if no error is returned. Note that the allocation takes effect after the next TPM reset. The function returns the maximum number of PCRs supported per bank, plus the size needed for the new allocation and the the size available.

func (*TPMContext) PCREvent

func (t *TPMContext) PCREvent(pcrContext ResourceContext, eventData Event, pcrContextAuthSession SessionContext, sessions ...SessionContext) (digests TaggedHashList, err error)

PCREvent executes the TPM2_PCR_Event command to extend the PCR associated with the pcrContext parameter with a digest of the provided eventData, hashed with the algorithm for each supported PCR bank.

If pcrContext is nil, this function will do nothing. The command requires authorization with the user auth role for pcrContext, with session based authorization provided via pcrContextAuthSession.

If the PCR associated with pcrContext can not be extended from the current locality, a *TPMError error with an error code of [ErrorLocality] will be returned.

On success, this function will return a list of tagged digests that the PCR associated with pcrContext was extended with.

func (*TPMContext) PCRExtend

func (t *TPMContext) PCRExtend(pcrContext ResourceContext, digests TaggedHashList, pcrContextAuthSession SessionContext, sessions ...SessionContext) error

PCRExtend executes the TPM2_PCR_Extend command to extend the PCR associated with the pcrContext parameter with the tagged digests provided via the digests argument. The tagged digests can be created using TaggedHashListBuilder.

If pcrContext is nil, this function will do nothing. The command requires authorization with the user auth role for pcrContext, with session based authorization provided via pcrContextAuthSession.

If the PCR associated with pcrContext can not be extended from the current locality, a *TPMError error with an error code of [ErrorLocality] will be returned.

func (*TPMContext) PCRHandleContext

func (t *TPMContext) PCRHandleContext(pcr int) ResourceContext

PCRHandleContext returns the ResourceContext corresponding to the PCR at the specified index. It will panic if pcr is not a valid PCR index.

func (*TPMContext) PCRRead

func (t *TPMContext) PCRRead(pcrSelectionIn PCRSelectionList, sessions ...SessionContext) (pcrUpdateCounter uint32, pcrValues PCRValues, err error)

PCRRead executes the TPM2_PCR_Read command to return the values of the PCRs defined in the pcrSelectionIn parameter. The underlying command may not be able to read all of the specified PCRs in a single transaction, so this function will re-execute the TPM2_PCR_Read command until all requested values have been read. As a consequence, any SessionContext instances provided should have the AttrContinueSession attribute defined.

This function will call TPMContext.InitProperties if it hasn't already been called.

On success, the current value of pcrUpdateCounter is returned, as well as the requested PCR values.

func (*TPMContext) PCRReset

func (t *TPMContext) PCRReset(pcrContext ResourceContext, pcrContextAuthSession SessionContext, sessions ...SessionContext) error

PCRReset executes the TPM2_PCR_Reset command to reset the PCR associated with pcrContext in all banks. This command requires authorization with the user auth role for pcrContext, with session based authorization provided via pcrContextAuthSession.

If the PCR associated with pcrContext can not be reset from the current locality, a *TPMError error with an error code of [ErrorLocality] will be returned.

func (*TPMContext) PlatformHandleContext

func (t *TPMContext) PlatformHandleContext() ResourceContext

PlatformHandleContext returns the ResourceContext corresponding to the platform hiearchy.

func (*TPMContext) PlatformNVHandleContext

func (t *TPMContext) PlatformNVHandleContext() ResourceContext

PlatformNVHandleContext returns the ResourceContext corresponding to the platform hiearchy.

func (*TPMContext) PolicyAuthValue

func (t *TPMContext) PolicyAuthValue(policySession SessionContext, sessions ...SessionContext) error

PolicyAuthValue executes the TPM2_PolicyAuthValue command to bind the policy to the authorization value of the entity on which the authorization is used. This is a deferred assertion. On successful completion, the policy digest of the session context associated with policySession will be extended to record that this assertion has been executed, and a flag will be set on the session context to indicate that the authorization value of the entity on which the authorization is used must be included in the key for computing the command HMAC when the session is used.

When using policySession in a subsequent authorization, the authorization value of the entity being authorized must be provided by calling ResourceContext.SetAuthValue.

func (*TPMContext) PolicyAuthorize

func (t *TPMContext) PolicyAuthorize(policySession SessionContext, approvedPolicy Digest, policyRef Nonce, keySign Name, checkTicket *TkVerified, sessions ...SessionContext) error

PolicyAuthorize executes the TPM2_PolicyAuthorize command, which allows policies to change. This is an immediate assertion. The command allows an authorizing entity to sign a new policy that can be used in an existing policy. The authorizing party signs a digest that is computed as follows:

digest := H(approvedPolicy||policyRef)

... where H is the name algorithm of the key used to sign the digest.

The signature can be created by github.com/canonical/go-tpm2/policyutil.SignPolicyAuthorization.

The signature is then verified by TPMContext.VerifySignature, which provides a ticket that is used by this function. The digest that is signed can be created by github.com/canonical/go-tpm2/policyutil.ComputePolicyAuthorizationTBSDigest.

If the name algorithm of the signing key is not supported, a *TPMParameterError error with an error code of ErrorHash will be returned for parameter index 3.

If the length of keySign does not match the length of the name algorithm, a *TPMParameterError error with an error code of ErrorSize will be returned for parameter index 3.

If policySession is not associated with a trial session, the current digest of the session associated with policySession will be compared with approvedPolicy. If they don't match, then a *TPMParameterError error with an error code of ErrorValue will be returned for parameter index 1.

If policySession is not associated with a trial session and checkTicket is invalid, a *TPMParameterError error with an error code of ErrorValue will be returned for parameter index 4.

On successful completion, the policy digest of the session context associated with policySession is cleared, and then extended to include the value of keySign and policyRef.

func (*TPMContext) PolicyCommandCode

func (t *TPMContext) PolicyCommandCode(policySession SessionContext, code CommandCode, sessions ...SessionContext) error

PolicyCommandCode executes the TPM2_PolicyCommandCode command to indicate that an authorization policy should be limited to a specific command. Ths is a deferred assertion.

If the command code is not implemented, a *TPMParameterError error with an error code of ErrorPolicyCC will be returned. If the session associated with policySession has already been limited to a different command code, a *TPMParameterError error with an error code of ErrorValue will be returned.

On successful completion, the policy digest of the session context associated with policySession will be extended to include the value of the specified command code, and the command code will be recorded on the session context to limit usage of the session.

func (*TPMContext) PolicyCounterTimer

func (t *TPMContext) PolicyCounterTimer(policySession SessionContext, operandB Operand, offset uint16, operation ArithmeticOp, sessions ...SessionContext) error

PolicyCounterTimer executes the TPM2_PolicyCounterTimer command to gate a policy based on the contents of the TimeInfo structure, and is an immediate assertion. The caller specifies a value to be used for the comparison via the operandB argument, an offset from the start of the TimeInfo structure from which to start the comparison via the offset argument, and a comparison operator via the operation argument.

If the comparison fails and policySession does not correspond to a trial session, a *TPMError error will be returned with an error code of ErrorPolicy.

On successful completion, the policy digest of the session context associated with policySession is extended to include the values of operandB, offset and operation.

func (*TPMContext) PolicyCpHash

func (t *TPMContext) PolicyCpHash(policySession SessionContext, cpHashA Digest, sessions ...SessionContext) error

PolicyCpHash executes the TPM2_PolicyCpHash command to bind a policy to a specific command and set of command parameters. This is a deferred assertion.

TPMContext.PolicySigned, TPMContext.PolicySecret and TPMContext.PolicyTicket allow an authorizing entity to execute an arbitrary command as the cpHashA parameter is not included in the session's policy digest. TPMContext.PolicyCommandCode allows the policy to be limited to a specific command. This command allows the policy to be limited further to a specific command and set of command parameters.

Command parameter digests can be computed using github.com/canonical/go-tpm2/policyutil.ComputeCpHash, using the digest algorithm for the session.

If the size of cpHashA is inconsistent with the digest algorithm for the session, a *TPMParameterError error with an error code of ErrorSize will be returned.

If the session associated with policySession already has a command parameter digest, name digest or template digest defined, a *TPMError error with an error code of ErrorCpHash will be returned if cpHashA does not match the digest already recorded on the session context.

On successful completion, the policy digest of the session context associated with policySession will be extended to include the value of cpHashA, and the value of cpHashA will be recorded on the session context to limit usage of the session to the specific command and set of command parameters.

func (*TPMContext) PolicyDuplicationSelect

func (t *TPMContext) PolicyDuplicationSelect(policySession SessionContext, objectName, newParentName Name, includeObject bool, sessions ...SessionContext) error

PolicyDuplicationSelect executes the TPM2_PolicyDuplicationSelect command to allow the policy to be restricted to duplication and to allow duplication to a specific new parent. The objectName argument corresponds to the name of the object to be duplicated. The newParentName argument corresponds to the name of the new parent object. This is a deferred assertion.

If the session associated with policySession already has a command parameter digest, name digest or template digest defined, a *TPMError error with an error code of ErrorCpHash will be returned.

If the session associated with policySession has already been limited to a specific command code, a *TPMError error with an error code of ErrorCommandCode will be returned.

On successful completion, the policy digest of the session context associated with policySession will be extended to include the value of newParentName and includeObject. If includeObject is true, the policy digest of the session will be extended to also include the value of objectName. A digest of objectName and newParentName will be recorded as the name hash on the session context to limit usage of the session to those entities, and the CommandDuplicate command code will be recorded to limit usage of the session to TPMContext.Duplicate.

func (*TPMContext) PolicyGetDigest

func (t *TPMContext) PolicyGetDigest(policySession SessionContext, sessions ...SessionContext) (policyDigest Digest, err error)

PolicyGetDigest executes the TPM2_PolicyGetDigest command to return the current policy digest of the session context associated with policySession.

func (*TPMContext) PolicyNV

func (t *TPMContext) PolicyNV(authContext, nvIndex ResourceContext, policySession SessionContext, operandB Operand, offset uint16, operation ArithmeticOp, authContextAuthSession SessionContext, sessions ...SessionContext) error

PolicyNV executes the TPM2_PolicyNV command to gate a policy based on the contents of the NV index associated with nvIndex, and is an immediate assertion. The caller specifies a value to be used for the comparison via the operandB argument, an offset from the start of the NV index data from which to start the comparison via the offset argument, and a comparison operator via the operation argument.

The command requires authorization to read the NV index, defined by the state of the AttrNVPPRead, AttrNVOwnerRead, AttrNVAuthRead and AttrNVPolicyRead attributes. The handle used for authorization is specified via authContext. If the NV index has the AttrNVPPRead attribute, authorization can be satisfied with HandlePlatform. If the NV index has the AttrNVOwnerRead attribute, authorization can be satisfied with HandleOwner. If the NV index has the AttrNVAuthRead or AttrNVPolicyRead attribute, authorization can be satisfied with nvIndex. The command requires authorization with the user auth role for authContext, with session based authorization provided via authContextAuthSession. If the resource associated with authContext is not permitted to authorize this access and policySession does not correspond to a trial session, a *TPMError error with an error code of ErrorNVAuthorization will be returned.

If nvIndex is being used for authorization and the AttrNVAuthRead attribute is defined, the authorization can be satisfied by demonstrating knowledge of the authorization value, either via cleartext or HMAC authorization. If nvIndex is being used for authorization and the AttrNVPolicyRead attribute is defined, the authorization can be satisfied using a policy session with a digest that matches the authorization policy for the index.

If the index associated with nvIndex has the AttrNVReadLocked attribute set and policySession does not correspond to a trial session, a *TPMError error with an error code of ErrorNVLocked will be returned.

If the index associated with nvIndex has not been initialized (ie, the AttrNVWritten attribute is not set) and policySession does not correspond to a trial session, a *TPMError with an error code of ErrorNVUninitialized will be returned.

If the session associated with policySession is not a trial session and offset is outside of the bounds of the NV index, a *TPMParameterError error with an error code of ErrorValue is returned for paramter index 2.

If the session associated with policySession is not a trial session and the size of operandB in combination with the value of offset would result in a read outside of the bounds of the NV index, a *TPMParameterError error with an error code of ErrorSize is returned for paramter index 1.

If the comparison fails and policySession does not correspond to a trial session, a *TPMError error will be returned with an error code of ErrorPolicy.

On successful completion, the policy digest of the session context associated with policySession is extended to include the values of operandB, offset, operation and the name of nvIndex.

func (*TPMContext) PolicyNameHash

func (t *TPMContext) PolicyNameHash(policySession SessionContext, nameHash Digest, sessions ...SessionContext) error

PolicyNameHash executes the TPM2_PolicyNameHash command to bind a policy to a specific set of TPM entities, without being bound to the parameters of the command. This is a deferred assertion.

The name hash can be computed using github.com/canonical/go-tpm2/policyutil.ComputeNameHash, using the digest algorithm for the session.

If the size of nameHash is inconsistent with the digest algorithm for the session, a *TPMParameterError error with an error code of ErrorSize will be returned.

If the session associated with policySession already has a name digest, command parameter digest or template digest defined, a *TPMError error with an error code of ErrorCpHash will be returned.

On successful completion, the policy digest of the session context associated with policySession will be extended to include the value of nameHash, and the value of nameHash will be recorded on the session context to limit usage of the session to the specific set of TPM entities.

func (*TPMContext) PolicyNvWritten

func (t *TPMContext) PolicyNvWritten(policySession SessionContext, writtenSet bool, sessions ...SessionContext) error

PolicyNvWritten executes the TPM2_PolicyNvWritten command to bind a policy to the value of the AttrNVWritten attribute of the NV index being authorized, and is a deferred assertion.

If this command has been executed previously in this session, and the value of writtenSet doesn't match the value provided previously, a *TPMParameterError error with an error code of ErrorValue will be returned.

On successful completion, the policy digest of the session associated with policySession will be extended to include the value of writtenSet. A flag will be set on the session context so that the value of the AttrNVWritten attribute of the NV index being authorized will be compared to writtenSet when the session is used.

func (*TPMContext) PolicyOR

func (t *TPMContext) PolicyOR(policySession SessionContext, pHashList DigestList, sessions ...SessionContext) error

PolicyOR executes the TPM2_PolicyOR command to allow a policy to be satisfied by different sets of conditions, and is an immediate assertion. If policySession does not correspond to a trial session, it determines if the current policy digest of the session context associated with policySession is contained in the list of digests specified via pHashList. If it is not, then a *TPMParameterError error with an error code of ErrorValue is returned without making any changes to the session context.

On successful completion, the policy digest of the session context associated with policySession is cleared, and then extended to include a digest of the concatenation of all of the digests contained in pHashList.

func (*TPMContext) PolicyPCR

func (t *TPMContext) PolicyPCR(policySession SessionContext, pcrDigest Digest, pcrs PCRSelectionList, sessions ...SessionContext) error

PolicyPCR executes the TPM2_PolicyPCR command to gate a policy based on the values of the PCRs selected via the pcrs parameter. If no digest has been specified via the pcrDigest parameter, then it is a deferred assertion and the policy digest of the session context associated with policySession will be extended to include the value of the PCR selection and a digest computed from the selected PCR contents.

If pcrDigest is provided, then it is a combined assertion. If policySession does not correspond to a trial session, the digest computed from the selected PCRs will be compared to the value of pcrDigest and a *TPMParameterError error with an error code of ErrorValue will be returned for parameter index 1 if they don't match, without making any changes to the session context. If policySession corresponds to a trial session, the digest computed from the selected PCRs is not compared to the value of pcrDigest; instead, the policy digest of the session is extended to include the value of the PCR selection and the value of pcrDigest.

If the PCR contents have changed since the last time this command was executed for this session, a *TPMError error will be returned with an error code of ErrorPCRChanged.

This function will call TPMContext.InitProperties if it hasn't already been called.

func (*TPMContext) PolicyPassword

func (t *TPMContext) PolicyPassword(policySession SessionContext, sessions ...SessionContext) error

PolicyPassword executes the TPM2_PolicyPassword command to bind the policy to the authorization value of the entity on which the authorization is used. This is a deferred assertion. On successful completion, the policy digest of the session context associated with policySession will be extended to record that this assertion has been executed, and a flag will be set on the session context to indicate that the authorization value of the entity on which the authorization is used must be included in cleartext in the command authorization when the session is used.

When using policySession in a subsequent authorization, the authorization value of the entity being authorized must be provided by calling ResourceContext.SetAuthValue.

func (*TPMContext) PolicyRestart

func (t *TPMContext) PolicyRestart(sessionContext SessionContext, sessions ...SessionContext) error

PolicyRestart executes the TPM2_PolicyRestart command on the policy session associated with sessionContext, to reset the policy authorization session to its initial state.

func (*TPMContext) PolicySecret

func (t *TPMContext) PolicySecret(authContext ResourceContext, policySession SessionContext, cpHashA Digest, policyRef Nonce, expiration int32, authContextAuthSession SessionContext, sessions ...SessionContext) (timeout Timeout, policyTicket *TkAuth, err error)

PolicySecret executes the TPM2_PolicySecret command to include a secret-based authorization to the policy session associated with policySession, and is a combined assertion. The command requires authorization with the user auth role for authContext, with session based authorization provided via authContextAuthSession. If authContextAuthSession corresponds a policy session, and that session does not include a TPM2_PolicyPassword or TPM2_PolicyAuthValue assertion, a *TPMSessionError error with an error code of ErrorMode will be returned for session index 1.

This function includes the most recently received TPM nonce value for the session associated with policySession as the first command parameter.

The cpHashA parameter allows the session to be bound to a specific command and set of command parameters by providing a command parameter digest. Command parameter digests can be computed using github.com/canonical/go-tpm2/policyutil.ComputeCpHash, using the digest algorithm for the session. Note that this only binds the use of the session to a specific set of command parameters - this assertion cannot be used to bind a policy to a specific set of command parameters. For that, use TPMContext.PolicyCpHash. If the cpHashA parameter is not provided, the session is not bound to a specific command and set of command parameters.

If policySession does not correspond to a trial session and cpHashA is supplied, a *TPMError error with an error code of ErrorCpHash will be returned if the session context already has a command parameter digest, name digest or template digest recorded on it and cpHashA does not match it.

If policySession does not correspond to a trial session, cpHashA is supplied and its length does not match the digest algorithm for the session, a *TPMParameterError error with an error code of ErrorSize will be returned for parameter index 2.

If the expiration parameter is not 0, it sets a timeout based on the absolute value of expiration in seconds, by which time the authorization will expire. The timeout is measured from the time that the current TPM nonce was generated for the session. If the session associated with policySession is not a trial session and expiration corresponds to a time in the past, or the TPM's time epoch has changed since the session was started, a *TPMParameterError error with an error code of ErrorExpired will be returned for parameter index 4.

On successful completion, knowledge of the authorization value associated with authContext is proven. The policy digest of the session associated with policySession will be extended to include the name of authContext and the value of policyRef. If provided, the value of cpHashA will be recorded on the session context to restrict the session's usage. If expiration is non-zero, the expiration time of the session context will be updated unless it already has an expiration time that is earlier. If expiration is less than zero, a timeout value and corresponding *TkAuth ticket will be returned if policySession does not correspond to a trial session.

func (*TPMContext) PolicySigned

func (t *TPMContext) PolicySigned(authContext ResourceContext, policySession SessionContext, includeNonceTPM bool, cpHashA Digest, policyRef Nonce, expiration int32, auth *Signature, sessions ...SessionContext) (timeout Timeout, policyTicket *TkAuth, err error)

PolicySigned executes the TPM2_PolicySigned command to include a signed authorization in a policy. This is a combined assertion that binds a policy to the signing key associated with authContext.

An authorizing entity signs a digest of authorization qualifiers with the key associated with authContext. The digest is computed as:

digest := H(nonceTPM||expiration||cpHashA||policyRef)

... where H is the digest algorithm associated with the auth parameter.

Where there are no restrictions, the digest is computed from 4 zero bytes, which corresponds to an expiration time of zero. The authorization qualifiers must match the arguments passed to this command. The signature is provided via the auth parameter.

The signature can be created using github.com/canonical/go-tpm2/policyutil.SignPolicySignedAuthorization.

If includeNonceTPM is set to true, this function includes the most recently received TPM nonce value for the session associated with policySession as the first command parameter. In this case, the nonce value must be included in the digest that is signed by the authorizing entity. The current nonce value can be obtained and sent to the signer from the SessionContextState obtained from SessionContext.

The cpHashA parameter allows the session to be bound to a specific command and set of command parameters by providing a command parameter digest. Command parameter digests can be computed using github.com/canonical/go-tpm2/policyutil.ComputeCpHash, using the digest algorithm for the session. If provided, the cpHashA value must be included in the digest that is signed by the authorizing entity. Note that this only binds the use of the session to a specific set of command parameters - this assertion cannot be used to bind a policy to a specific set of command parameters. For that, use TPMContext.PolicyCpHash. If the cpHashA parameter is not provided, the session is not bound to a specific command and set of command parameters.

If policySession does not correspond to a trial session and cpHashA is supplied, a *TPMError error with an error code of ErrorCpHash will be returned if the session context already has a command parameter digest, name digest or template digest recorded on it and cpHashA does not match it.

If policySession does not correspond to a trial session, cpHashA is supplied and its length does not match the digest algorithm for the session, a *TPMParameterError error with an error code of ErrorSize will be returned for parameter index 2.

If the expiration parameter is not 0, it sets a timeout based on the absolute value of expiration in seconds, by which time the authorization will expire. If includeNonceTPM is true then the timeout is measured from the time that the current TPM nonce was generated for the session, else it is measured from the time that this command is executed. If the session associated with policySession is not a trial session and expiration corresponds to a time in the past, or the TPM's time epoch has changed since the session was started, a *TPMParameterError error with an error code of ErrorExpired will be returned for parameter index 4.

If the session associated with policySession is not a trial session and the signing scheme or digest algorithm associated with the auth parameter is not supported by the TPM, a *TPMParameterError error with an error code of ErrorScheme will be returned for parameter index 5.

If the session associated with policySession is not a trial session, the signature will be validated against a digest computed from the provided arguments, using the key associated with authContext. If the signature is invalid, a *TPMParameterError error with an error code of ErrorSignature will be returned for parameter index 5.

On successful completion, the policy digest of the session associated with policySession will be extended to include the name of authContext and the value of policyRef. If provided, the value of cpHashA will be recorded on the session context to restrict the session's usage. If expiration is non-zero, the expiration time of the session context will be updated unless it already has an expiration time that is earlier. If expiration is less than zero, a timeout value and corresponding *TkAuth ticket will be returned if policySession does not correspond to a trial session. If includeNonceTPM is false, the returned ticket will expire on the next TPM reset if that occurs before the timeout.

func (*TPMContext) PolicyTicket

func (t *TPMContext) PolicyTicket(policySession SessionContext, timeout Timeout, cpHashA Digest, policyRef Nonce, authName Name, ticket *TkAuth, sessions ...SessionContext) error

PolicyTicket executes the TPM2_PolicyTicket command, and behaves similarly to TPMContext.PolicySigned with the exception that it takes an authorization ticket rather than a signed authorization. The ticket parameter represents a valid authorization with an expiration time, and will have been returned from a previous call to TPMContext.PolicySigned or TPMContext.PolicySecret when called with an expiration time of less than zero.

If policySession corresponds to a trial session, a *TPMHandleError error with an error code of ErrorAttributes will be returned.

If the size of timeout is not the expected size, a *TPMParameterError with an error code of ErrorSize will be returned for parameter index 1.

A *TPMError error with an error code of ErrorCpHash will be returned if cpHashA is supplied and the session context already has a command parameter digest, name digest or template digest recorded on it and cpHashA does not match it.

The cpHashA and policyRef arguments must match the values passed to the command that originally produced the ticket. If the command that produced the ticket was TPMContext.PolicySecret, authName must correspond to the name of the entity of which knowledge of the authorization value was proven. If the command that produced the ticket was TPMContext.PolicySigned, authName must correspond to the name of the key that produced the signed authorization.

If the ticket is invalid, a *TPMParameterError error with an error code of ErrorTicket will be returned for parameter index 5. If the ticket corresponds to an authorization that has expired, a *TPMParameterError error with an error code of ErrorExpired will be returned for parameter index 1.

On successful verification of the ticket, the policy digest of the session context associated with policySession will be extended with the same values that the command that produced the ticket would extend it with. If provided, the value of cpHashA will be recorded on the session context to restrict the session's usage. The expiration time of the session context will be updated with the value of timeout, unless it already has an expiration time that is earlier.

func (*TPMContext) Quote

func (t *TPMContext) Quote(signContext ResourceContext, qualifyingData Data, inScheme *SigScheme, pcrs PCRSelectionList, signContextAuthSession SessionContext, sessions ...SessionContext) (quoted *Attest, signature *Signature, err error)

Quote executes the TPM2_Quote command in order to quote a set of PCR values. The TPM will hash the set of PCRs specified by the pcrs parameter.

If signContext is not nil, the returned attestation will be signed by the key associated with it. This command requires authorization with the user auth role for signContext, with session based authorization provided via signContextAuthSession.

If signContext is not nil and the object associated with signContext is not a signing key, a *TPMHandleError error with an error code of ErrorKey will be returned for handle index 1.

If signContext is not nil and if the scheme of the key associated with signContext is AsymSchemeNull, then inScheme must be provided to specify a valid signing scheme for the key. If it isn't, a *TPMParameterError error with an error code of ErrorScheme will be returned for parameter index 2.

If signContext is not nil and the scheme of the key associated with signContext is not AsymSchemeNull, then inScheme may be nil. If it is provided, then the specified scheme must match that of the signing key, else a *TPMParameterError error with an error code of ErrorScheme will be returned for parameter index 2.

This function will call TPMContext.InitProperties if it hasn't already been called.

On success, it returns an attestation structure containing the hash of the PCRs selected by the pcrs parameter. If signContext is not nil, the attestation structure will be signed by the associated key and returned too.

func (*TPMContext) ReadClock

func (t *TPMContext) ReadClock(sessions ...SessionContext) (currentTime *TimeInfo, err error)

ReadClock executes the TPM2_ReadClock command. On succesful completion, it will return a TimeInfo struct that contains the current value of time, clock, reset and restart counts.

func (*TPMContext) ReadPublic

func (t *TPMContext) ReadPublic(objectContext HandleContext, sessions ...SessionContext) (outPublic *Public, name Name, qualifiedName Name, err error)

ReadPublic executes the TPM2_ReadPublic command to read the public area of the object associated with objectContext.

If objectContext corresponds to a sequence object, a *TPMError with an error code of ErrorSequence will be returned.

On success, the public part of the object is returned, along with the object's name and qualified name.

func (*TPMContext) RunCommand

func (t *TPMContext) RunCommand(commandCode CommandCode, cHandles HandleList, cAuthArea []AuthCommand, cpBytes []byte, rHandle *Handle) (rpBytes []byte, rAuthArea []AuthResponse, err error)

RunCommand is a low-level interface for executing a command. The caller supplies the command code, list of command handles, command auth area and marshalled command parameters. The caller should also supply a pointer to a response handle if the command returns one. On success, the response parameter bytes and response auth area are returned. This function does no checking of the auth response.

A *TransportError will be returned if the transmission interface returns an error.

One of *TPMWarning, *TPMError, *TPMParameterError, *TPMHandleError or *TPMSessionError will be returned if the TPM returns a response code other than ResponseSuccess.

There's almost no need for most users to use this API directly. Most users will want to use one of the many convenience functions provided by TPMContext instead, or TPMContext.StartCommand if one doesn't already exist.

func (*TPMContext) RunCommandBytes

func (t *TPMContext) RunCommandBytes(packet CommandPacket) (ResponsePacket, error)

RunCommandBytes is a low-level interface for executing a command. The caller is responsible for supplying a properly serialized command packet, which can be created with MarshalCommandPacket.

If successful, this function will return the response packet. No checking is performed on this response packet. An error will only be returned if the transmission interface returns an error.

Most users will want to use one of the many convenience functions provided by TPMContext instead, or TPMContext.StartCommand if one doesn't already exist.

func (*TPMContext) SelfTest

func (t *TPMContext) SelfTest(fullTest bool, sessions ...SessionContext) error

func (*TPMContext) SequenceComplete

func (t *TPMContext) SequenceComplete(sequenceContext ResourceContext, buffer MaxBuffer, hierarchy Handle, sequenceContextAuthSession SessionContext, sessions ...SessionContext) (result Digest, validation *TkHashcheck, err error)

SequenceComplete executes the TPM2_SequenceComplete command to add the last part of the data the HMAC or hash sequence associated with sequenceContext, and returns the result. This command requires authorization with the user auth role for sequenceContext, with session based authorization provided via sequenceContextAuthSession.

If sequenceContext does not correspond to a HMAC or hash sequence object, then a *TPMHandleError error with an error code of ErrorMode will be returned.

If sequenceContext corresponds to a hash sequence and the hash sequence is intended to produce a digest that will be signed with a restricted signing key, the first block of data added to this sequence must be 4 bytes and not the value of TPMGeneratedValue. If the returned digest is safe to sign with a restricted signing key, then a ticket that can be passed to TPMContext.Sign will be returned. In this case, the hierarchy argument is used to specify the hierarchy for the ticket.

On success, the sequence object associated with sequenceContext will be evicted, and sequenceContext will become invalid.

func (*TPMContext) SequenceExecute

func (t *TPMContext) SequenceExecute(sequenceContext ResourceContext, buffer []byte, hierarchy Handle, sequenceContextAuthSession SessionContext, sessions ...SessionContext) (result Digest, validation *TkHashcheck, err error)

SequenceExecute executes a hash or HMAC sequence to completion and returns the result by adding the provided data to the sequence with a number of TPM2_SequenceUpdate commands appropriate for the size of buffer, and executing a final TPM2_SequenceComplete command. This command requires authorization with the user auth role for sequenceContext, with session based authorization provided via sequenceContextAuthSession.

If sequenceContext does not correspond to a hash or HMAC sequence object, then a *TPMHandleError error with an error code of ErrorMode will be returned.

If sequenceContext corresponds to a hash sequence and the hash sequence is intended to produce a digest that will be signed with a restricted signing key, the first block of data added to this sequence must be 4 bytes and not the value of TPMGeneratedValue. If the returned digest is safe to sign with a restricted signing key, then a ticket that can be passed to TPMContext.Sign will be returned. In this case, the hierarchy argument is used to specify the hierarchy for the ticket.

On success, the sequence object associated with sequenceContext will be evicted, and sequenceContext will become invalid.

func (*TPMContext) SequenceUpdate

func (t *TPMContext) SequenceUpdate(sequenceContext ResourceContext, buffer MaxBuffer, sequenceContextAuthSession SessionContext, sessions ...SessionContext) error

SequenceUpdate executes the TPM2_SequenceUpdate command to add data to the HMAC, hash or event sequence associated with sequenceContext. This command requires authorization with the user auth role for sequenceContext, with session based authorization provided via sequenceContextAuthSession.

If sequenceContext does not correspond to a sequence object, then a *TPMHandleError error with an error code of ErrorMode will be returned.

If sequenceContext corresponds to a hash sequence and the hash sequence is intended to produce a digest that will be signed with a restricted signing key, the first block of data added to this sequence must be 4 bytes and not the value of TPMGeneratedValue.

func (*TPMContext) SetCommandCodeAuditStatus

func (t *TPMContext) SetCommandCodeAuditStatus(auth ResourceContext, auditAlg HashAlgorithmId, setList, clearList CommandCodeList, authAuthSession SessionContext, sessions ...SessionContext) error

SetCommandCodeAuditStatus executes the TPM2_SetCommandCodeAuditStatus command to allow the privacy administrator or platform to change the audit status of a command, or change the digest algorithm used for command auditing (but not both at the same time).

The auth parameter should be a ResourceContext corresponding to either HandlePlatform or HandleOwner. This command requires authorization of auth with the user auth role, with session based authorization provided via authAuthSession.

The auditAlg argument specifies the digest algorithm for command auditing. The setList argument is used to specify which commands should be added to the list of commands to be audited. The clearList argument is used to specify which commands should be removed from the list of commands to be audited.

If auditAlg is not HashAlgorithmNull or the current audit digest algorithm, and the length of setList or clearList is greater than zero, a *TPMParameterError error with an error code of ErrorValue will be returned for parameter index 1.

func (*TPMContext) SetCommandTimeout deprecated added in v1.1.0

func (t *TPMContext) SetCommandTimeout(timeout time.Duration) error

SetCommandTimeout sets the maximum time that the context will wait for a response before a command times out. Set this to InfiniteTimeout to disable the timeout entirely, which is the default value.

Note that there isn't a way to reattempt to the fetch the result of a command that times out. If a command times out, the connection will generally be unusable for future commands.

Deprecated: This always returns ErrTimeoutNotSupported. Timing out after a command has been submitted doesn't make sense for this API, as there is no mechanism to obtain a response from a command that previously timed out.

func (*TPMContext) SetMaxSubmissions deprecated

func (t *TPMContext) SetMaxSubmissions(max uint)

SetMaxSubmissions sets the maximum number of times that CommandContext will attempt to submit a command before failing with an error. The default value is 5. Setting this to 1 disables resubmission. Note that 1 and 0 behave the same.

Each submission is performed after an incremental delay. The first submission is delayed for 20ms, with the delay time doubling for each subsequent submission.

Deprecated: This doesn't do anything now.

func (*TPMContext) Shutdown

func (t *TPMContext) Shutdown(shutdownType StartupType, sessions ...SessionContext) error

Shutdown executes the TPM2_Shutdown command with the specified StartupType, and is used to prepare the TPM for a power cycle. Calling this with shutdownType == StartupClear prepares the TPM for a TPM reset. Calling it with shutdownType == StartupState prepares the TPM for either a TPM restart or TPM resume, depending on how TPMContext.Startup is called. Some commands executed after TPMContext.Shutdown but before a power cycle will nullify the effect of this function.

If a PCR bank has been reconfigured and shutdownType == StartupState, a *TPMParameterError error with an error code of ErrorType will be returned.

func (*TPMContext) Sign

func (t *TPMContext) Sign(keyContext ResourceContext, digest Digest, inScheme *SigScheme, validation *TkHashcheck, keyContextAuthSession SessionContext, sessions ...SessionContext) (signature *Signature, err error)

Sign executes the TPM2_Sign command to sign the provided digest with the key associated with keyContext. The function requires authorization with the user auth role for keyContext, with session based authorization provided via keyContextAuthSession.

If the object associated with keyContext is not a signing key, a *TPMHandleError error with an error code of ErrorKey will be returned.

If the scheme of the key associated with keyContext is AsymSchemeNull, then inScheme must be provided to specify a valid signing scheme for the key. If it isn't, a *TPMParameterError error with an error code of ErrorScheme will be returned for parameter index 2.

If the scheme of the key associated with keyContext is not AsymSchemeNull, then inScheme may be nil. If it is provided, then the specified scheme must match that of the signing key, else a *TPMParameterError error with an error code of ErrorScheme will be returned for parameter index 2.

If the chosen scheme is unsupported, a *TPMError error with an error code of ErrorScheme will be returned.

If the length of digest does not match the size of the digest associated with the selected signing scheme, a *TPMParameterError error with an error code of ErrorSize will be returned for parameter index 1.

If the key associated with keyContext has the AttrRestricted attribute, then the validation parameter must be provided as proof that the supplied digest was created by the TPM. If the key associated with keyContext does not have the AttrRestricted attribute, then validation may be nil. If validation is not nil and doesn't correspond to a valid ticket, or it is nil and the key associated with keyContext has the AttrRestricted attribute set, a *TPMParameterError error with an error code of ErrorTicket will be returned for parameter index 3.

func (*TPMContext) StartAuthSession

func (t *TPMContext) StartAuthSession(tpmKey, bind ResourceContext, sessionType SessionType, symmetric *SymDef, authHash HashAlgorithmId, sessions ...SessionContext) (sessionContext SessionContext, err error)

StartAuthSession executes the TPM2_StartAuthSession command to start an authorization session. On successful completion, it will return a SessionContext that corresponds to the new session.

The type of session is defined by the sessionType parameter. If sessionType is SessionTypeHMAC or SessionTypePolicy, then the created session may be used for authorization. If sessionType is SessionTypeTrial, then the created session can only be used for computing an authorization policy digest.

The authHash parameter defines the algorithm used for computing command and response parameter digests, command and response HMACs, and derivation of the session key and symmetric keys for parameter encryption where used. The size of the digest algorithm is used to determine the nonce size used for the session.

If tpmKey is provided then a salted session is created. In this case, it must be possible to type assert the provided key to ObjectContext. The key must correspond to an asymmetric decrypt key in the TPM - it must have a type of ObjectTypeRSA or ObjectTypeECC and it must have the AttrDecrypt attribute set. In this case, a random salt value will be established which will contribute to the session key derivation. If tpmKey has the type of ObjectTypeRSA, the random salt will be created on the host and RSA-OAEP encrypted with the public part of tpmKey before being sent to the TPM. If tpmKey has the type of ObjectTypeECC, a random salt is established using ECDH key exchange and an ephemeral host key. If tpmKey is provided but does not correspond to an asymmetric key, a *TPMHandleError error with an error code of ErrorKey will be returned for handle index 1. If tpmKey is provided but corresponds to an object with only its public part loaded, a *TPMHandleError error with an error code of ErrorHandle will be returned for handle index 1. If tpmKey is provided but does not correspond to a decrypt key, a *TPMHandleError error with an error code of ErrorAttributes will be returned for handle index 1.

If tpmkey is provided but establishment of the salt fails on the TPM, a *TPMParameterError error with an error code of ErrorValue or ErrorKey may be returned for parameter index 2.

If tpmKey is not provided, an unsalted session is created.

If bind is specified then a bound session is created. The authorization value for the corresponding bind resource must be known, by calling ResourceContext.SetAuthValue on bind before calling this function. In this case, the authorization value will contribute to the session key derivation. The created session will be bound to the resource associated with bind, unless the authorization value of that resource is subsequently changed. If bind corresponds to a transient object and only the public part of the object is loaded, or if bind corresponds to a NV index with a type of NVTypePinPass or NVTypePinFail, a *TPMHandleError error with an error code of ErrorHandle will be returned for handle index 2.

If tpmKey or bind is specified, a session key is computed. If neither tpmKey or bind are specified, then no session key is computed.

When the created session is used for authorization, a HMAC key used to generate and verify command and response HMACs is created. If the session is used for authorization of the bound resource, then the HMAC key is generated from the session key if there is one. If the session is used for authorization of any other resource, then the HMAC key is generated from the session key (if there is one) and the authorization value of the resource that the session is being used for authorization of.

If symmetric is provided, it defines the symmetric algorithm to use if the session is subsequently used for session based command or response parameter encryption. Session based parameter encryption allows the first command and/or response parameter for a command to be encrypted between the TPM and host CPU for supported parameter types (go types that correspond to TPM2B prefixed types). If symmetric is provided and corresponds to a symmetric block cipher (ie, the Algorithm field is not SymAlgorithmXOR) then the symmetric mode must be SymModeCFB, else a *TPMParameterError error with an error code of ErrorMode is returned for parameter index 4.

When the created session is used for parameter encryption, the encryption key is derived from the session key if there is one. If the session is also used for authorization, then the encryption key derivation also uses the authorization value of the resource that the session is being used for authorization of, regardless of whether it is bound to it.

If a SessionContext instance with the AttrCommandEncrypt attribute set is provided in the variable length sessions parameter, then the initial caller nonce will be encrypted as this is the first command parameter, despite not being exposed via this API. If a SessionContext instance with the AttrResponseEncrypt attribute set is provided, then the initial TPM nonce will be encrypted in the response.

If sessionType is SessionTypeHMAC and the session is subsequently used for authorization of a resource to which the session is not bound, the authorization value of that resource must be known as it is used to derive the key for computing command and response HMACs.

If no more sessions can be created without first context loading the oldest saved session, then a *TPMWarning error with a warning code of WarningContextGap will be returned. If there are no more slots available for loaded sessions, a *TPMWarning error with a warning code of WarningSessionMemory will be returned. If there are no more session handles available, a *[TPMwarning] error with a warning code of WarningSessionHandles will be returned.

func (*TPMContext) StartCommand added in v0.2.0

func (t *TPMContext) StartCommand(commandCode CommandCode) *CommandContext

StartCommand is the high-level function for beginning the process of executing a command. It returns a CommandContext that can be used to assemble a command, properly serialize a command packet and then submit the packet for execution via TPMContext.RunCommand.

Most users will want to use one of the many convenience functions provided by TPMContext, which are just wrappers around this.

func (*TPMContext) Startup

func (t *TPMContext) Startup(startupType StartupType) error

Startup executes the TPM2_Startup command with the specified StartupType. If this isn't preceded by _TPM_Init then it will return a *TPMError error with an error code of ErrorInitialize. The shutdown and startup sequence determines how the TPM responds to this call:

If called with startupType == StartupState, a *TPMError error with an error code of ErrorNVUninitialized will be returned if the saved state cannot be recovered. In this case, the function must be called with startupType == StartupClear.

Subsequent use of HandleContext instances corresponding to entities that are evicted as a consequence of this function will no longer work.

func (*TPMContext) StirRandom

func (t *TPMContext) StirRandom(inData SensitiveData, sessions ...SessionContext) error

func (*TPMContext) TestParms

func (t *TPMContext) TestParms(parameters *PublicParams, sessions ...SessionContext) error

TestParms executes the TPM2_TestParms command to check if the specified combination of algorithm parameters is supported.

func (*TPMContext) Transport added in v1.4.0

func (t *TPMContext) Transport() Transport

Transport returns the underlying transmission channel for this context.

func (*TPMContext) Unseal

func (t *TPMContext) Unseal(itemContext ResourceContext, itemContextAuthSession SessionContext, sessions ...SessionContext) (outData SensitiveData, err error)

Unseal executes the TPM2_Unseal command to decrypt the sealed data object associated with itemContext and retrieve its sensitive data. The command requires authorization with the user auth role for itemContext, with session based authorization provided via itemContextAuthSession.

If the type of object associated with itemContext is not ObjectTypeKeyedHash, a *TPMHandleError error with an error code of ErrorType will be returned. If the object associated with itemContext has either the AttrDecrypt, AttrSign or AttrRestricted attributes set, a *TPMHandleError error with an error code of ErrorAttributes will be returned.

On success, the object's sensitive data is returned in decrypted form.

func (*TPMContext) VerifySignature

func (t *TPMContext) VerifySignature(keyContext ResourceContext, digest Digest, signature *Signature, sessions ...SessionContext) (validation *TkVerified, err error)

VerifySignature executes the TPM2_VerifySignature command to validate the provided signature against a message with the provided digest, using the key associated with keyContext. If keyContext corresponds to an object that isn't a signing key, a *TPMHandleError error with an error code of ErrorAttributes will be returned.

If the signature is invalid, a *TPMParameterError error with an error code of ErrorSignature will be returned for parameter index 2. If the signature references an unsupported signature scheme, a *TPMParameterError error with an error code of ErrorScheme will be returned for parameter index 2.

If keyContext corresponds to a HMAC key but only the public part is loaded, a *TPMParameterError error with an error code of ErrorHandle will be returned for parameter index 2.

On success, a valid TkVerified structure will be returned.

type TPMDevice added in v1.1.0

type TPMDevice interface {
	// Open opens a communication channel with the TPM device. The returned
	// channel will only be used from the same goroutine that TPMContext is
	// used from. Implementations must handle command reads and writes that
	// are split across multiple calls. Implementations of Open should be
	// safe to call from multiple goroutines simultaneously.
	Open() (Transport, error)

	fmt.Stringer
}

TPMDevice corresponds a TPM device.

type TPMError

type TPMError struct {
	Command CommandCode // Command code associated with this error
	Code    ErrorCode   // Error code
}

TPMError represents a TPM response that indicates an error that is not associated with a specific handle, parameter or session.

func AsTPMError added in v1.7.7

func AsTPMError(err error, code ErrorCode, command CommandCode) *TPMError

AsTPMError returns a TPMError if the supplied error is one or any within its chain is. It will only return a TPMError if the supplied parameters match - see IsTPMError for how this works.

func (*TPMError) CommandCode added in v1.7.7

func (e *TPMError) CommandCode() CommandCode

func (*TPMError) Error

func (e *TPMError) Error() string

func (*TPMError) Is

func (e *TPMError) Is(target error) bool

func (*TPMError) ResponseCode

func (e *TPMError) ResponseCode() ResponseCode

ResponseCode returns a TPM response code for this error. It will panic if it cannot be converted to a valid error response code.

type TPMErrorBadTag added in v0.2.0

type TPMErrorBadTag struct {
	Command CommandCode
}

TPMErrorBadTag represents a TPM response that indicates that the tag field of the command header was invalid (rc == ResponseBadTag). This error will occur when trying to execute a TPM2 command on a TPM1.2 device (along with a response tag == TagRspCommand).

func (*TPMErrorBadTag) CommandCode added in v1.7.7

func (e *TPMErrorBadTag) CommandCode() CommandCode

func (*TPMErrorBadTag) Error added in v0.2.0

func (e *TPMErrorBadTag) Error() string

func (TPMErrorBadTag) ResponseCode added in v0.2.0

func (TPMErrorBadTag) ResponseCode() ResponseCode

ResponseCode returns a TPM response code for this error.

type TPMGenerated

type TPMGenerated uint32

TPMGenerated corresponds to the TPM_GENERATED type.

const (
	TPMGeneratedValue TPMGenerated = 0xff544347 // TPM_GENERATED_VALUE
)

type TPMHandleError

type TPMHandleError struct {
	*TPMError
	// Index is the index of the handle associated with this error in the command handle area, starting from 1. An index of 0 corresponds
	// to an unspecified handle
	Index int
}

TPMHandleError represents a TPM response that indicates an error that is associated with a command handle.

func AsTPMHandleError added in v1.7.7

func AsTPMHandleError(err error, code ErrorCode, command CommandCode, handle int) *TPMHandleError

AsTPMHandleError returns a TPMHandleError if the supplied error is one or any within its chain is. It will only return a TPMHandleError if the supplied parameters match - see IsTPMHandleError for how this works.

func (*TPMHandleError) Error

func (e *TPMHandleError) Error() string

func (*TPMHandleError) Is

func (e *TPMHandleError) Is(target error) bool

func (*TPMHandleError) ResponseCode

func (e *TPMHandleError) ResponseCode() ResponseCode

ResponseCode returns a TPM response code for this error. It will panic if it cannot be converted to a valid handle error response code.

func (*TPMHandleError) Unwrap

func (e *TPMHandleError) Unwrap() error

type TPMManufacturer

type TPMManufacturer uint32

TPMManufacturer corresponds to the TPM manufacturer and is returned when querying the value PropertyManufacturer.

const (
	TPMManufacturerAMD  TPMManufacturer = 0x414D4400 // AMD
	TPMManufacturerATML TPMManufacturer = 0x41544D4C // Atmel
	TPMManufacturerBRCM TPMManufacturer = 0x4252434D // Broadcom
	TPMManufacturerHPE  TPMManufacturer = 0x48504500 // HPE
	TPMManufacturerIBM  TPMManufacturer = 0x49424d00 // IBM
	TPMManufacturerIFX  TPMManufacturer = 0x49465800 // Infineon
	TPMManufacturerINTC TPMManufacturer = 0x494E5443 // Intel
	TPMManufacturerLEN  TPMManufacturer = 0x4C454E00 // Lenovo
	TPMManufacturerMSFT TPMManufacturer = 0x4D534654 // Microsoft
	TPMManufacturerNSM  TPMManufacturer = 0x4E534D20 // National Semiconductor
	TPMManufacturerNTZ  TPMManufacturer = 0x4E545A00 // Nationz
	TPMManufacturerNTC  TPMManufacturer = 0x4E544300 // Nuvoton Technology
	TPMManufacturerQCOM TPMManufacturer = 0x51434F4D // Qualcomm
	TPMManufacturerSMSC TPMManufacturer = 0x534D5343 // SMSC
	TPMManufacturerSTM  TPMManufacturer = 0x53544D20 // ST Microelectronics
	TPMManufacturerSMSN TPMManufacturer = 0x534D534E // Samsung
	TPMManufacturerSNS  TPMManufacturer = 0x534E5300 // Sinosun
	TPMManufacturerTXN  TPMManufacturer = 0x54584E00 // Texas Instruments
	TPMManufacturerWEC  TPMManufacturer = 0x57454300 // Winbond
	TPMManufacturerROCC TPMManufacturer = 0x524F4343 // Fuzhou Rockchip
	TPMManufacturerGOOG TPMManufacturer = 0x474F4F47 // Google
)

func (TPMManufacturer) Format

func (m TPMManufacturer) Format(s fmt.State, f rune)

func (TPMManufacturer) String

func (m TPMManufacturer) String() string

type TPMParameterError

type TPMParameterError struct {
	*TPMError
	Index int // Index of the parameter associated with this error in the command parameter area, starting from 1
}

TPMParameterError represents a TPM response that indicates an error that is associated with a command parameter.

func AsTPMParameterError added in v1.7.7

func AsTPMParameterError(err error, code ErrorCode, command CommandCode, handle int) *TPMParameterError

AsTPMParameterError returns a TPMParameterError if the supplied error is one or any within its chain is. It will only return a TPMParameterError if the supplied parameters match - see IsTPMParameterError for how this works.

func (*TPMParameterError) Error

func (e *TPMParameterError) Error() string

func (*TPMParameterError) Is

func (e *TPMParameterError) Is(target error) bool

func (*TPMParameterError) ResponseCode

func (e *TPMParameterError) ResponseCode() ResponseCode

ResponseCode returns a TPM response code for this error. It will panic if it cannot be converted to a valid parameter error response code.

func (*TPMParameterError) Unwrap

func (e *TPMParameterError) Unwrap() error

type TPMSessionError

type TPMSessionError struct {
	*TPMError
	Index int // Index of the session associated with this error in the authorization area, starting from 1
}

TPMSessionError represents a TPM response that indicates an error that is associated with a session.

func AsTPMSessionError added in v1.7.7

func AsTPMSessionError(err error, code ErrorCode, command CommandCode, handle int) *TPMSessionError

AsTPMSessionError returns a TPMSessionError if the supplied error is one or any within its chain is. It will only return a TPMSessionError if the supplied parameters match - see IsTPMSessionError for how this works.

func (*TPMSessionError) Error

func (e *TPMSessionError) Error() string

func (*TPMSessionError) Is

func (e *TPMSessionError) Is(target error) bool

func (*TPMSessionError) ResponseCode

func (e *TPMSessionError) ResponseCode() ResponseCode

ResponseCode returns a TPM response code for this error. It will panic if it cannot be converted to a valid session error response code.

func (*TPMSessionError) Unwrap

func (e *TPMSessionError) Unwrap() error

type TPMVendorError

type TPMVendorError struct {
	Command CommandCode  // Command code associated with this error
	Code    ResponseCode // Response code
}

TPMVendorError represents a TPM response that indicates a vendor-specific error (rc & 0x580 == 0x500).

func AsTPMVendorError added in v1.7.7

func AsTPMVendorError(err error, rc ResponseCode, command CommandCode) *TPMVendorError

AsTPMVendorError returns a TPMVendorError if the supplied error is one or any within its chainis. It wil only return a TPMVendorError if the supplied parameters match - see IsTPMVendorError for how this works.

func (*TPMVendorError) CommandCode added in v1.7.7

func (e *TPMVendorError) CommandCode() CommandCode

func (*TPMVendorError) Error

func (e *TPMVendorError) Error() string

func (*TPMVendorError) Is added in v1.7.7

func (e *TPMVendorError) Is(target error) bool

func (*TPMVendorError) ResponseCode added in v0.2.0

func (e *TPMVendorError) ResponseCode() ResponseCode

ResponseCode returns a TPM response code for this error. It will panic if it cannot be converted to a valid vendor error response code.

type TPMWarning

type TPMWarning struct {
	Command CommandCode // Command code associated with this error
	Code    WarningCode // Warning code
}

TPMWarning represents a TPM response that indicates a warning.

func AsTPMWarning added in v1.7.7

func AsTPMWarning(err error, code WarningCode, command CommandCode) *TPMWarning

AsTPMWarningError returns a TPMWarning if the supplied error is one or any within its chain is. It will only return a TPMWarning if the supplied parameters match - see IsTPMWarning for how this works.

func (*TPMWarning) CommandCode added in v1.7.7

func (e *TPMWarning) CommandCode() CommandCode

func (*TPMWarning) Error

func (e *TPMWarning) Error() string

func (*TPMWarning) Is

func (e *TPMWarning) Is(target error) bool

func (*TPMWarning) ResponseCode

func (e *TPMWarning) ResponseCode() ResponseCode

ResponseCode returns a TPM response code for this error. It will panic if it cannot be converted to a valid warning response code.

type TaggedHash

type TaggedHash struct {
	HashAlg    HashAlgorithmId // Algorithm of the digest contained with Digest
	DigestData *TaggedHashU    // Digest data
}

TaggedHash corresponds to the TPMT_HA type.

func MakeTaggedHash added in v1.0.2

func MakeTaggedHash(alg HashAlgorithmId, digest Digest) TaggedHash

MakeTaggedHash creates a new tagged hash that represents the specified digest. It will panic if the algorithm is invalid. The supplied digest should be the correct length - it will be padded if it's too short or truncated if it's too long.

func NewTaggedHash deprecated added in v0.9.9

func NewTaggedHash(alg HashAlgorithmId, digest Digest) (*TaggedHash, error)

NewTaggedHash creates a new tagged hash that represents the specified digest. It will return an error if the algorithm is invalid or the size of the digest doesn't match the algorithm.

Deprecated: Use MakeTaggedHash.

func (*TaggedHash) Digest

func (h *TaggedHash) Digest() Digest

Digest returns the value of this tagged hash. It will panic if the digest algorithm is invalid and not HashAlgorithmNull. It will be valid if this tagged hash was created by unmarshalling it, else check the value of the HashAlg field first.

type TaggedHashList

type TaggedHashList []TaggedHash

TaggedHashList is a slice of TaggedHash values, and corresponds to the TPML_DIGEST_VALUES type.

type TaggedHashListBuilder deprecated added in v0.9.9

type TaggedHashListBuilder struct {
	// contains filtered or unexported fields
}

TaggedHashListBuilder facilitates creating a TaggedHashList. It allows a list to be constructed without having to check for errors until the end.

Deprecated: Use TaggedHashList and MakeTaggedHash.

func NewTaggedHashListBuilder deprecated added in v0.9.9

func NewTaggedHashListBuilder() *TaggedHashListBuilder

NewTaggedHashListBuilder returns a new TaggedHashListBuilder.

Deprecated: Use TaggedHashList and MakeTaggedHash.

func (*TaggedHashListBuilder) Append added in v0.9.9

Append appends the digest with the specified algorithm to the list.

func (*TaggedHashListBuilder) Finish added in v0.9.9

Finish returns the final list, or an error if one occurred whilst the list was being built.

func (*TaggedHashListBuilder) MustFinish added in v0.9.9

func (b *TaggedHashListBuilder) MustFinish() TaggedHashList

MustFinish is the same as TaggedHashListBuilder.Finish except if panics if an error occurred.

type TaggedHashU added in v0.9.9

type TaggedHashU struct {
	SHA1         [20]byte
	SHA256       [32]byte
	SHA384       [48]byte
	SHA512       [64]byte
	SHA256_192   [24]byte
	SM3_256      [32]byte
	SHA3_256     [32]byte
	SHA3_384     [48]byte
	SHA3_512     [64]byte
	SHAKE256_192 [24]byte
	SHAKE256_256 [32]byte
	SHAKE256_512 [64]byte
}

TaggedHashU is a union type that corresponds to the TPMU_HA type. The selector type is HashAlgorithmId. Mapping of selector values to fields is as follows:

  • HashAlgorithmSHA1: SHA1
  • HashAlgorithmSHA256: SHA256
  • HashAlgorithmSHA384: SHA384
  • HashAlgorithmSHA512: SHA512
  • HashAlgorithmSHA256_192: SHA256_192
  • HashAlgorithmSM3_256: SM_256
  • HashAlgorithmSHA3_256: SHA3_256
  • HashAlgorithmSHA3_384: SHA3_384
  • HashAlgorithmSHA3_512: SHA3_512
  • HashAlgorithmSHAKE256_192: SHAKE256_192
  • HashAlgorithmSHAKE256_256: SHAKE256_256
  • HashAlgorithmSHAKE256_512: SHAKE256_512

func (*TaggedHashU) Select added in v0.9.9

func (u *TaggedHashU) Select(selector reflect.Value) interface{}

Select implements mu.Union.

type TaggedPCRPropertyList

type TaggedPCRPropertyList []TaggedPCRSelect

TaggedPCRPropertyList is a slice of TaggedPCRSelect values, and corresponds to the TPML_TAGGED_PCR_PROPERTY type.

type TaggedPCRSelect

type TaggedPCRSelect struct {
	Tag    PropertyPCR // Property identifier
	Select PCRSelect   // PCRs associated with Tag
}

TaggedPCRSelect corresponds to the TPMS_TAGGED_PCR_SELECT type. It is used to report the PCR indexes associated with a property.

type TaggedPolicy

type TaggedPolicy struct {
	Handle     Handle     // Permanent handle
	PolicyHash TaggedHash // Policy algorithm and hash
}

TaggedPolicy corresponds to the TPMS_TAGGED_POLICY type. It is used to report the authorization policy for a permanent resource.

type TaggedPolicyList

type TaggedPolicyList []TaggedPolicy

TaggedPolicyList is a slice of TaggedPolicy values, and corresponds to the TPML_TAGGED_POLICY type.

type TaggedProperty

type TaggedProperty struct {
	Property Property // Property identifier
	Value    uint32   // Value of the property
}

TaggedProperty corresponds to the TPMS_TAGGED_PROPERTY type. It is used to report the value of a property.

type TaggedTPMPropertyList

type TaggedTPMPropertyList []TaggedProperty

TaggedTPMPropertyList is a slice of TaggedProperty values, and corresponds to the TPML_TAGGED_TPM_PROPERTY type.

type TctiError deprecated

type TctiError = TransportError

TctiError is returned from any TPMContext method if the underlying Transport returns an error. If this error occurs, the underlying connection will generally be unusable for subsequent commands.

Deprecated: Use TransportError.

type Template

type Template []byte

Template corresponds to the TPM2B_TEMPLATE type

type TimeAttestInfo

type TimeAttestInfo struct {
	Time            TimeInfo // Time information
	FirmwareVersion uint64   // TPM vendor specific value indicating the version of the firmware
}

TimeAttestInfo corresponds to the TPMS_TIME_ATTEST_INFO type, and is returned by TPMContext.GetTime.

type TimeInfo

type TimeInfo struct {
	Time      uint64    // Time value in milliseconds since the last TPM startup
	ClockInfo ClockInfo // Clock information
}

TimeInfo corresponds to the TPMS_TIME_INFO type.

type Timeout

type Timeout []byte

Timeout corresponds to the TPM2B_TIMEOUT type. The spec defines this as having a maximum size of 8 bytes. It is always 8 bytes in the reference implementation and so could be represented as a uint64, but we have to preserve the original buffer because there is no guarantees that it is always 8 bytes, and the actual TPM buffer must be recreated accurately in order for ticket validation to work correctly in TPMContext.PolicyTicket.

func (Timeout) Value

func (t Timeout) Value() uint64

Value returns the value as a uint64. The spec defines the TPM2B_TIMEOUT type as having a size of up to 8 bytes. If an implementation creates a larger value then the result of this is undefined.

type TkAuth

type TkAuth struct {
	Tag       StructTag // Ticket structure tag (TagAuthSecret or TagAuthSigned)
	Hierarchy Handle    // The hierarchy of the object used to produce this ticket
	Digest    Digest    // HMAC computed using the proof value of Hierarchy
}

TkAuth corresponds to the TPMT_TK_AUTH type. It is created by TPMContext.PolicySigned and TPMContext.PolicySecret when the authorization has an expiration time.

type TkCreation

type TkCreation struct {
	Tag       StructTag // Ticket structure tag (TagCreation)
	Hierarchy Handle    // The hierarchy of the object to which this ticket belongs.
	Digest    Digest    // HMAC computed using the proof value of Hierarchy
}

TkCreation corresponds to the TPMT_TK_CREATION type. It is created by TPMContext.Create and TPMContext.CreatePrimary, and is used to cryptographically bind the CreationData to the created object.

type TkHashcheck

type TkHashcheck struct {
	Tag       StructTag // Ticket structure tag (TagHashcheck)
	Hierarchy Handle    // The hierarchy of the object used to produce this ticket
	Digest    Digest    // HMAC computed using the proof value of Hierarchy
}

TkHashcheck corresponds to the TPMT_TK_HASHCHECK type.

type TkVerified

type TkVerified struct {
	Tag       StructTag // Ticket structure tag (TagVerified)
	Hierarchy Handle    // The hierarchy of the object to which this ticket belongs.
	Digest    Digest    // HMAC computed using the proof value of Hierarcht
}

TkVerified corresponds to the TPMT_TK_VERIFIED type. It is created by TPMContext.VerifySignature and provides evidence that the TPM has verified that a digest was signed by a specific key.

type Transport added in v1.4.0

type Transport interface {
	// Read is used to receive a response to a previously transmitted command.
	Read(p []byte) (int, error)

	// Write is used to transmit a serialized command to the TPM implementation.
	Write(p []byte) (int, error)

	// Close closes the transport.
	Close() error
}

Transport represents a communication channel to a TPM implementation. Implementations of this should not be used from multiple goroutines simultaneously.

type TransportError added in v1.4.0

type TransportError struct {
	Op string // The operation that caused the error
	// contains filtered or unexported fields
}

TransportError is returned from any TPMContext method if the underlying Transport returns an error. If this error occurs, the underlying connection will generally be unusable for subsequent commands.

func (*TransportError) Error added in v1.4.0

func (e *TransportError) Error() string

func (*TransportError) Unwrap added in v1.4.0

func (e *TransportError) Unwrap() error

type WarningCode

type WarningCode uint8

WarningCode represents a TPM warning. These are TCG defined format 0 response codes with the severity bit set (response codes 0x900 to 0x97f).

const (
	WarningContextGap     WarningCode = 0x01 // TPM_RC_CONTEXT_GAP
	WarningObjectMemory   WarningCode = 0x02 // TPM_RC_OBJECT_MEMORY
	WarningSessionMemory  WarningCode = 0x03 // TPM_RC_SESSION_MEMORY
	WarningMemory         WarningCode = 0x04 // TPM_RC_MEMORY
	WarningSessionHandles WarningCode = 0x05 // TPM_RC_SESSION_HANDLES
	WarningObjectHandles  WarningCode = 0x06 // TPM_RC_OBJECT_HANDLES

	// WarningLocality corresponds to TPM_RC_LOCALITY and is returned for a command if a policy
	// session is used for authorization and the session includes a TPM2_PolicyLocality assertion, but
	// the command isn't executed with the authorized locality.
	WarningLocality WarningCode = 0x07

	// WarningYielded corresponds to TPM_RC_YIELDED and is returned for any command that is suspended
	// as a hint that the command can be retried. This is handled automatically when executing
	// commands using CommandContext by resubmitting the command.
	WarningYielded WarningCode = 0x08

	// WarningCanceled corresponds to TPM_RC_CANCELED and is returned for any command that is canceled
	// before being able to complete.
	WarningCanceled WarningCode = 0x09

	WarningTesting     WarningCode = 0x0a // TPM_RC_TESTING
	WarningReferenceH0 WarningCode = 0x10 // TPM_RC_REFERENCE_H0
	WarningReferenceH1 WarningCode = 0x11 // TPM_RC_REFERENCE_H1
	WarningReferenceH2 WarningCode = 0x12 // TPM_RC_REFERENCE_H2
	WarningReferenceH3 WarningCode = 0x13 // TPM_RC_REFERENCE_H3
	WarningReferenceH4 WarningCode = 0x14 // TPM_RC_REFERENCE_H4
	WarningReferenceH5 WarningCode = 0x15 // TPM_RC_REFERENCE_H5
	WarningReferenceH6 WarningCode = 0x16 // TPM_RC_REFERENCE_H6
	WarningReferenceS0 WarningCode = 0x18 // TPM_RC_REFERENCE_S0
	WarningReferenceS1 WarningCode = 0x19 // TPM_RC_REFERENCE_S1
	WarningReferenceS2 WarningCode = 0x1a // TPM_RC_REFERENCE_S2
	WarningReferenceS3 WarningCode = 0x1b // TPM_RC_REFERENCE_S3
	WarningReferenceS4 WarningCode = 0x1c // TPM_RC_REFERENCE_S4
	WarningReferenceS5 WarningCode = 0x1d // TPM_RC_REFERENCE_S5
	WarningReferenceS6 WarningCode = 0x1e // TPM_RC_REFERENCE_S6

	// WarningNVRate corresponds to TPM_RC_NV_RATE and is returned for any command that requires NV
	// access if NV access is currently rate limited to prevent the NV memory from wearing out.
	WarningNVRate WarningCode = 0x20

	// WarningLockout corresponds to TPM_RC_LOCKOUT and is returned for any command that requires
	// authorization for an entity that is subject to dictionary attack protection, and the TPM is in
	// dictionary attack lockout mode.
	WarningLockout WarningCode = 0x21

	// WarningRetry corresponds to TPM_RC_RETRY and is returned for any command if the TPM was not
	// able to start the command. This is handled automatically when executing comands using
	// CommandContext by resubmitting the command.
	WarningRetry WarningCode = 0x22

	// WarningNVUnavailable corresponds to TPM_RC_NV_UNAVAILABLE and is returned for any command that
	// requires NV access but NV memory is currently not available.
	WarningNVUnavailable WarningCode = 0x23
)

func (WarningCode) Format

func (e WarningCode) Format(s fmt.State, f rune)

func (WarningCode) String

func (e WarningCode) String() string

Directories

Path Synopsis
Package crypto is deprecated and should't be used - use cryptutil instead.
Package crypto is deprecated and should't be used - use cryptutil instead.
Package cryptutil contains some cryptographic functions that are useful when using go-tpm2.
Package cryptutil contains some cryptographic functions that are useful when using go-tpm2.
internal
ppi
Package linux provides an interface for communicating with TPMs using a Linux TPM character device
Package linux provides an interface for communicating with TPMs using a Linux TPM character device
Package mssim provides an interface for communicating with a TPM simulator
Package mssim provides an interface for communicating with a TPM simulator
Package mu contains functions for marshalling go values to and unmarshalling them from the TPM wire format.
Package mu contains functions for marshalling go values to and unmarshalling them from the TPM wire format.
Package objectutil contains utilities for creating and working with objects.
Package objectutil contains utilities for creating and working with objects.
Package policyutil contains utilties for constructing and executing authorization policies.
Package policyutil contains utilties for constructing and executing authorization policies.
Package ppi provides a way of interacting with the TCG PC Client Physical Presence Interface
Package ppi provides a way of interacting with the TCG PC Client Physical Presence Interface
Package templates is deprecated and shouldn't be used - use objectutil instead.
Package templates is deprecated and shouldn't be used - use objectutil instead.
Package testutil contains utilities for writing unit tests using go-tpm2.
Package testutil contains utilities for writing unit tests using go-tpm2.
Package util contains helper functions that are useful when using go-tpm2.
Package util contains helper functions that are useful when using go-tpm2.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL