tpm2

package
v0.0.0-...-f29c5df Latest Latest
Warning

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

Go to latest
Published: Jul 14, 2019 License: Apache-2.0 Imports: 14 Imported by: 0

README

TPM 2.0 client library

Integration tests

tpm2_test.go contains integration tests that run against a real TPM device (emulated or hardware).

By default, running go test will skip them. To run the tests on a host with available TPM device, run

go test --tpm_path=/dev/tpm0

where /dev/tpm0 is path to a TPM character device or a Unix socket.

Tip: if your TPM host is remote and you don't want to install Go on it, use go test -c to compile a test binary. It can be copied to remote host and run without extra dependencies.

Documentation

Overview

Package tpm2 supports direct communication with a TPM 2.0 device under Linux.

Index

Constants

View Source
const (
	HandleOwner tpmutil.Handle = 0x40000001 + iota
	HandleRevoke
	HandleTransport
	HandleOperator
	HandleAdmin
	HandleEK
	HandleNull
	HandleUnassigned
	HandlePasswordSession
	HandleLockout
	HandleEndorsement
	HandlePlatform
)

Reserved Handles.

View Source
const (
	TagNull          tpmutil.Tag = 0x8000
	TagNoSessions    tpmutil.Tag = 0x8001
	TagSessions      tpmutil.Tag = 0x8002
	TagAttestCertify tpmutil.Tag = 0x8017
	TagHashCheck     tpmutil.Tag = 0x8024
)

TPM Structure Tags. Tags are used to disambiguate structures, similar to Alg values: tag value defines what kind of data lives in a nested field.

View Source
const (
	CurveNISTP192 = EllipticCurve(iota + 1)
	CurveNISTP224
	CurveNISTP256
	CurveNISTP384
	CurveNISTP521

	CurveBNP256 = EllipticCurve(iota + 10)
	CurveBNP638

	CurveSM2P256 = EllipticCurve(0x0020)
)

ECC curves supported by TPM 2.0 spec.

Variables

View Source
var OpenTPM = tpmutil.OpenTPM

OpenTPM opens a channel to the TPM at the given path. If the file is a device, then it treats it like a normal TPM device, and if the file is a Unix domain socket, then it opens a connection to the socket.

Functions

func ActivateCredential

func ActivateCredential(rw io.ReadWriter, activeHandle, keyHandle tpmutil.Handle, activePassword, protectorPassword string, credBlob, secret []byte) ([]byte, error)

ActivateCredential associates an object with a credential. Returns decrypted certificate information.

func Certify

func Certify(rw io.ReadWriter, parentAuth, ownerAuth string, object, signer tpmutil.Handle, qualifyingData []byte) ([]byte, []byte, error)

Certify generates a signature of a loaded TPM object with a signing key signer. Returned values are: attestation data (TPMS_ATTEST), signature and error, if any.

func ContextLoad

func ContextLoad(rw io.ReadWriter, saveArea []byte) (tpmutil.Handle, error)

ContextLoad reloads context data created by ContextSave.

func ContextSave

func ContextSave(rw io.ReadWriter, handle tpmutil.Handle) ([]byte, error)

ContextSave returns an encrypted version of the session, object or sequence context for storage outside of the TPM. The handle references context to store.

func CreateKey

func CreateKey(rw io.ReadWriter, owner tpmutil.Handle, sel PCRSelection, parentPassword, ownerPassword string, pub Public) ([]byte, []byte, error)

CreateKey creates a new key pair under the owner handle. Returns private key and public key blobs.

func CreatePrimary

func CreatePrimary(rw io.ReadWriter, owner tpmutil.Handle, sel PCRSelection, parentPassword, ownerPassword string, pub Public) (tpmutil.Handle, crypto.PublicKey, error)

CreatePrimary initializes the primary key in a given hierarchy. Second return value is the public part of the generated key.

func CreatePrimaryRawTemplate

func CreatePrimaryRawTemplate(rw io.ReadWriter, owner tpmutil.Handle, sel PCRSelection, parentPassword, ownerPassword string, public []byte) (tpmutil.Handle, crypto.PublicKey, error)

CreatePrimaryRawTemplate is CreatePrimary, but with the public template (TPMT_PUBLIC) provided pre-encoded. This is commonly used with key templates stored in NV RAM.

func EvictControl

func EvictControl(rw io.ReadWriter, ownerAuth string, owner, objectHandle, persistentHandle tpmutil.Handle) error

EvictControl toggles persistence of an object within the TPM.

func FlushContext

func FlushContext(rw io.ReadWriter, handle tpmutil.Handle) error

FlushContext removes an object or session under handle to be removed from the TPM. This must be called for any loaded handle to avoid out-of-memory errors in TPM.

func GetCapability

func GetCapability(rw io.ReadWriter, cap Capability, count uint32, property uint32) ([]tpmutil.Handle, error)

GetCapability returns various information about the TPM state.

Currently only CapabilityHandles is supported (list active handles).

func GetRandom

func GetRandom(rw io.ReadWriteCloser, size uint16) ([]byte, error)

GetRandom gets random bytes from the TPM.

func Hash

func Hash(rw io.ReadWriter, alg Algorithm, buf []byte) ([]byte, error)

Hash computes a hash of data in buf using the TPM.

func Load

func Load(rw io.ReadWriter, parentHandle tpmutil.Handle, parentAuth string, publicBlob, privateBlob []byte) (tpmutil.Handle, []byte, error)

Load loads public/private blobs into an object in the TPM. Returns loaded object handle and its name.

func LoadExternal

func LoadExternal(rw io.ReadWriter, pub Public, private Private, hierarchy tpmutil.Handle) (tpmutil.Handle, []byte, error)

LoadExternal loads a public (and optionally a private) key into an object in the TPM. Returns loaded object handle and its name.

func MakeCredential

func MakeCredential(rw io.ReadWriter, protectorHandle tpmutil.Handle, credential, activeName []byte) ([]byte, []byte, error)

MakeCredential creates an encrypted credential for use in MakeCredential. Returns encrypted credential and wrapped secret used to encrypt it.

func NVDefineSpace

func NVDefineSpace(rw io.ReadWriter, owner, handle tpmutil.Handle, ownerAuth, authString string, policy []byte, attributes uint32, dataSize uint16) error

NVDefineSpace creates an index in TPM's NV storage.

func NVIncrement

func NVIncrement(rw io.ReadWriter, handle tpmutil.Handle, authString string) error

NVIncrement increments a counter in NVRAM.

func NVRead

func NVRead(rw io.ReadWriter, index tpmutil.Handle) ([]byte, error)

NVRead reads a full data blob from an NV index.

func NVUndefineSpace

func NVUndefineSpace(rw io.ReadWriter, ownerAuth string, owner, index tpmutil.Handle) error

NVUndefineSpace removes an index from TPM's NV storage.

func PCREvent

func PCREvent(rw io.ReadWriter, pcr tpmutil.Handle, eventData []byte) error

PCREvent writes an update to the specified PCR.

func PolicyGetDigest

func PolicyGetDigest(rw io.ReadWriter, handle tpmutil.Handle) ([]byte, error)

PolicyGetDigest returns the current policyDigest of the session.

func PolicyPCR

func PolicyPCR(rw io.ReadWriter, session tpmutil.Handle, expectedDigest []byte, sel PCRSelection) error

PolicyPCR sets PCR state binding for authorization on a session.

func PolicyPassword

func PolicyPassword(rw io.ReadWriter, handle tpmutil.Handle) error

PolicyPassword sets password authorization requirement on the object.

func ReadClock

func ReadClock(rw io.ReadWriter) (uint64, uint64, error)

ReadClock returns current clock values from the TPM.

First return value is time in milliseconds since TPM was initialized (since system startup).

Second return value is time in milliseconds since TPM reset (since Storage Primary Seed is changed).

func ReadPCR

func ReadPCR(rw io.ReadWriteCloser, pcr int, hashAlg Algorithm) ([]byte, error)

ReadPCR reads the value of the given PCR.

func ReadPCRs

func ReadPCRs(rw io.ReadWriter, sel PCRSelection) (map[int][]byte, error)

ReadPCRs reads PCR values from the TPM.

func Seal

func Seal(rw io.ReadWriter, parentHandle tpmutil.Handle, parentPassword, objectPassword string, objectAuthPolicy []byte, sensitiveData []byte) ([]byte, []byte, error)

Seal creates a data blob object that seals the sensitive data under a parent and with a password and auth policy. Access to the parent must be available with a simple password. Returns private and public portions of the created object.

func Shutdown

func Shutdown(rw io.ReadWriter, typ StartupType) error

Shutdown shuts down a TPM (usually done by the OS).

func StartAuthSession

func StartAuthSession(rw io.ReadWriter, tpmKey, bindKey tpmutil.Handle, nonceCaller, secret []byte, se SessionType, sym, hashAlg Algorithm) (tpmutil.Handle, []byte, error)

StartAuthSession initializes a session object. Returns session handle and the initial nonce from the TPM.

func Startup

func Startup(rw io.ReadWriter, typ StartupType) error

Startup initializes a TPM (usually done by the OS).

func Unseal

func Unseal(rw io.ReadWriter, itemHandle tpmutil.Handle, password string) ([]byte, error)

Unseal returns the data for a loaded sealed object.

func UnsealWithSession

func UnsealWithSession(rw io.ReadWriter, sessionHandle, itemHandle tpmutil.Handle, password string) ([]byte, error)

UnsealWithSession returns the data for a loaded sealed object.

Types

type Algorithm

type Algorithm uint16

Algorithm represents a TPM_ALG_ID value.

const (
	AlgUnknown   Algorithm = 0x0000
	AlgRSA       Algorithm = 0x0001
	AlgSHA1      Algorithm = 0x0004
	AlgAES       Algorithm = 0x0006
	AlgKeyedHash Algorithm = 0x0008
	AlgSHA256    Algorithm = 0x000B
	AlgSHA384    Algorithm = 0x000C
	AlgSHA512    Algorithm = 0x000D
	AlgNull      Algorithm = 0x0010
	AlgRSASSA    Algorithm = 0x0014
	AlgRSAES     Algorithm = 0x0015
	AlgRSAPSS    Algorithm = 0x0016
	AlgOAEP      Algorithm = 0x0017
	AlgECDSA     Algorithm = 0x0018
	AlgECDH      Algorithm = 0x0019
	AlgECDAA     Algorithm = 0x001A
	AlgKDF2      Algorithm = 0x0021
	AlgECC       Algorithm = 0x0023
	AlgCTR       Algorithm = 0x0040
	AlgOFB       Algorithm = 0x0041
	AlgCBC       Algorithm = 0x0042
	AlgCFB       Algorithm = 0x0043
	AlgECB       Algorithm = 0x0044
)

Supported Algorithms.

func (Algorithm) IsNull

func (a Algorithm) IsNull() bool

IsNull returns true if a is AlgNull or zero (unset).

func (Algorithm) UsesCount

func (a Algorithm) UsesCount() bool

UsesCount returns true if a signature algorithm uses count value.

type AttestationData

type AttestationData struct {
	Magic               uint32
	Type                tpmutil.Tag
	QualifiedSigner     Name
	ExtraData           []byte
	ClockInfo           ClockInfo
	FirmwareVersion     uint64
	AttestedCertifyInfo *CertifyInfo
}

AttestationData contains data attested by TPM commands (like Certify).

func DecodeAttestationData

func DecodeAttestationData(in []byte) (*AttestationData, error)

DecodeAttestationData decode a TPMS_ATTEST message. No error is returned if the input has extra trailing data.

func (AttestationData) Encode

func (ad AttestationData) Encode() ([]byte, error)

Encode serializes an AttestationData structure in TPM wire format.

type Capability

type Capability uint32

Capability identifies some TPM property or state type.

const (
	CapabilityAlgs Capability = iota
	CapabilityHandles
	CapabilityCommands
	CapabilityPPCommands
	CapabilityAuditCommands
	CapabilityPCRs
	CapabilityTPMProperties
	CapabilityPCRProperties
	CapabilityECCCurves
	CapabilityAuthPolicies
)

TPM Capabilies.

type CertifyInfo

type CertifyInfo struct {
	Name          Name
	QualifiedName Name
}

CertifyInfo contains Certify-specific data for TPMS_ATTEST.

type ClockInfo

type ClockInfo struct {
	Clock        uint64
	ResetCount   uint32
	RestartCount uint32
	Safe         byte
}

ClockInfo contains TPM state info included in AttestationData.

type ECCParams

type ECCParams struct {
	Symmetric *SymScheme
	Sign      *SigScheme
	CurveID   EllipticCurve
	KDF       *KDFScheme
	Point     ECPoint
}

ECCParams represents parameters of an ECC key pair.

Symmetric, Sign and KDF may be nil, depending on key Attributes in Public.

type ECPoint

type ECPoint struct {
	X, Y *big.Int
}

ECPoint represents a ECC coordinates for a point.

type EllipticCurve

type EllipticCurve uint16

EllipticCurve identifies specific EC curves.

type HashValue

type HashValue struct {
	Alg   Algorithm
	Value []byte
}

HashValue is an algorithm-specific hash value.

type KDFScheme

type KDFScheme struct {
	Alg  Algorithm
	Hash Algorithm
}

KDFScheme represents a KDF (Key Derivation Function) scheme.

type KeyProp

type KeyProp uint32

KeyProp is a bitmask used in Attributes field of key templates. Individual flags should be OR-ed to form a full mask.

const (
	FlagFixedTPM            KeyProp = 0x00000002
	FlagFixedParent         KeyProp = 0x00000010
	FlagSensitiveDataOrigin KeyProp = 0x00000020
	FlagUserWithAuth        KeyProp = 0x00000040
	FlagAdminWithPolicy     KeyProp = 0x00000080
	FlagNoDA                KeyProp = 0x00000400
	FlagRestricted          KeyProp = 0x00010000
	FlagDecrypt             KeyProp = 0x00020000
	FlagSign                KeyProp = 0x00040000

	FlagSealDefault   = FlagFixedTPM | FlagFixedParent
	FlagSignerDefault = FlagSign | FlagRestricted | FlagFixedTPM |
		FlagFixedParent | FlagSensitiveDataOrigin | FlagUserWithAuth
	FlagStorageDefault = FlagDecrypt | FlagRestricted | FlagFixedTPM |
		FlagFixedParent | FlagSensitiveDataOrigin | FlagUserWithAuth
)

Key properties.

type NVPublic

type NVPublic struct {
	NVIndex    tpmutil.Handle
	NameAlg    Algorithm
	Attributes KeyProp
	AuthPolicy []byte
	DataSize   uint16
}

NVPublic contains the public area of an NV index.

type Name

type Name struct {
	Handle *tpmutil.Handle
	Digest *HashValue
}

Name contains a name for TPM entities. Only one of Handle/Digest should be set.

func (Name) MatchesPublic

func (n Name) MatchesPublic(p Public) (bool, error)

MatchesPublic compares Digest in Name against given Public structure. Note: this only works for regular Names, not Qualified Names.

type PCRSelection

type PCRSelection struct {
	Hash Algorithm
	PCRs []int
}

PCRSelection contains a slice of PCR indexes and a hash algorithm used in them.

type Private

type Private struct {
	Type      Algorithm
	AuthValue []byte
	SeedValue []byte
	Sensitive []byte
}

Private contains private section of a TPM key.

func (Private) Encode

func (p Private) Encode() ([]byte, error)

Encode serializes a Private structure in TPM wire format.

type Public

type Public struct {
	Type       Algorithm
	NameAlg    Algorithm
	Attributes KeyProp
	AuthPolicy []byte

	// If Type is AlgKeyedHash, then do not set these.
	// Otherwise, only one of the Parameters fields should be set. When encoding/decoding,
	// one will be picked based on Type.
	RSAParameters *RSAParams
	ECCParameters *ECCParams
}

Public contains the public area of an object.

func DecodePublic

func DecodePublic(in *bytes.Buffer) (Public, error)

DecodePublic decodes a serialized Public Key in TPM Wire Formatted bytes to a Public structure.

func ReadPublic

func ReadPublic(rw io.ReadWriter, handle tpmutil.Handle) (Public, []byte, []byte, error)

ReadPublic reads the public part of the object under handle. Returns the public data, name and qualified name.

func (Public) Encode

func (p Public) Encode() ([]byte, error)

Encode serializes a Public structure in TPM wire format.

type RSAParams

type RSAParams struct {
	Symmetric  *SymScheme
	Sign       *SigScheme
	KeyBits    uint16
	Exponent   uint32
	ModulusRaw []byte
	Modulus    *big.Int
}

RSAParams represents parameters of an RSA key pair.

Symmetric and Sign may be nil, depending on key Attributes in Public.

One of Modulus and ModulusRaw must always be non-nil. Modulus takes precedence. ModulusRaw is used for key templates where the field named "unique" must be a byte array of all zeroes.

type SessionAttributes

type SessionAttributes byte

SessionAttributes represents an attribute of a session.

const (
	AttrContinueSession SessionAttributes = 1 << iota
	AttrAuditExclusive
	AttrAuditReset

	AttrDecrypt
	AttrEcrypt
	AttrAudit
)

type SessionType

type SessionType uint8

SessionType defines the type of session created in StartAuthSession.

const (
	SessionHMAC   SessionType = 0x00
	SessionPolicy SessionType = 0x01
	SessionTrial  SessionType = 0x03
)

Supported session types.

type SigScheme

type SigScheme struct {
	Alg   Algorithm
	Hash  Algorithm
	Count uint32
}

SigScheme represents a signing scheme.

type Signature

type Signature struct {
	Alg Algorithm
	RSA *SignatureRSA
	ECC *SignatureECC
}

Signature combines all possible signatures from RSA and ECC keys. Only one of RSA or ECC will be populated.

func Quote

func Quote(rw io.ReadWriter, signingHandle tpmutil.Handle, parentPassword, ownerPassword string, toQuote []byte, sel PCRSelection, sigAlg Algorithm) ([]byte, *Signature, error)

Quote returns a quote of PCR values. A quote is a signature of the PCR values, created using a signing TPM key.

Returns attestation data and the signature.

Note: currently only RSA signatures are supported.

func Sign

func Sign(rw io.ReadWriter, key tpmutil.Handle, password string, digest []byte, sigScheme *SigScheme) (*Signature, error)

Sign computes a signature for digest using a given loaded key. Signature algorithm depends on the key type.

type SignatureECC

type SignatureECC struct {
	HashAlg Algorithm
	R       *big.Int
	S       *big.Int
}

SignatureECC is an ECC-specific signature value.

type SignatureRSA

type SignatureRSA struct {
	HashAlg   Algorithm
	Signature []byte
}

SignatureRSA is an RSA-specific signature value.

type StartupType

type StartupType uint16

StartupType instructs the TPM on how to handle its state during Shutdown or Startup.

const (
	StartupClear StartupType = iota
	StartupState
)

Startup types

type SymScheme

type SymScheme struct {
	Alg     Algorithm
	KeyBits uint16
	Mode    Algorithm
}

SymScheme represents a symmetric encryption scheme.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL