attest

package
v0.0.0-...-09fc040 Latest Latest
Warning

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

Go to latest
Published: Oct 3, 2023 License: Apache-2.0 Imports: 32 Imported by: 0

Documentation

Overview

Package attest abstracts TPM attestation operations.

Index

Examples

Constants

View Source
const (
	BitlockerStatusCached   = 0x01
	BitlockerStatusMedia    = 0x02
	BitlockerStatusTPM      = 0x04
	BitlockerStatusPin      = 0x10
	BitlockerStatusExternal = 0x20
	BitlockerStatusRecovery = 0x40
)

Valid BitlockerStatus values.

Variables

View Source
var (
	HashSHA1   = HashAlg(tpm2.AlgSHA1)
	HashSHA256 = HashAlg(tpm2.AlgSHA256)
)

Valid hash algorithms.

View Source
var (

	// ErrTPMNotAvailable is returned in response to OpenTPM() when
	// either no TPM is available, or a TPM of the requested version
	// is not available (if TPMVersion was set in the provided config).
	ErrTPMNotAvailable = errors.New("TPM device not available")
	// ErrTPM12NotImplemented is returned in response to methods which
	// need to interact with the TPM1.2 device in ways that have not
	// yet been implemented.
	ErrTPM12NotImplemented = errors.New("TPM 1.2 support not yet implemented")
)

Functions

func AppendEvents

func AppendEvents(base []byte, additional ...[]byte) ([]byte, error)

AppendEvents takes a series of TPM 2.0 event logs and combines them into a single sequence of events with a single header.

Additional logs must not use a digest algorithm which was not present in the original log.

func ParseEKCertificate

func ParseEKCertificate(ekCert []byte) (*x509.Certificate, error)

ParseEKCertificate parses a raw DER encoded EK certificate blob.

Types

type AK

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

AK represents a key which can be used for attestation.

Example
package main

import (
	"log"

	"github.com/google/go-attestation/attest"
)

func main() {
	tpm, err := attest.OpenTPM(nil)
	if err != nil {
		log.Fatalf("Failed to open the TPM: %v", err)
	}
	defer tpm.Close()

	// Create a new AK.
	ak, err := tpm.NewAK(nil)
	if err != nil {
		log.Fatalf("Failed to create AK: %v", err)
	}
	// Save a re-loadable representation to blob.
	blob, err := ak.Marshal()
	if err != nil {
		log.Fatalf("Failed to marshal AK: %v", err)
	}
	// Close our handle to the AK.
	if err := ak.Close(tpm); err != nil {
		log.Fatalf("Failed to close AK: %v", err)
	}

	// Re-load the created AK from the blob.
	ak, err = tpm.LoadAK(blob)
	if err != nil {
		log.Fatalf("Failed to load AK: %v", err)
	}
	if err := ak.Close(tpm); err != nil {
		log.Fatalf("Failed to close AK: %v", err)
	}
}
Output:

Example (CredentialActivation)
package main

import (
	"crypto/subtle"
	"log"

	"github.com/google/go-attestation/attest"
)

func main() {
	tpm, err := attest.OpenTPM(nil)
	if err != nil {
		log.Fatalf("Failed to open TPM: %v", err)
	}
	defer tpm.Close()

	// Create a new AK.
	ak, err := tpm.NewAK(nil)
	if err != nil {
		log.Fatalf("Failed to create AK: %v", err)
	}
	defer ak.Close(tpm)

	// Read the EK.
	ek, err := tpm.EKs()
	if err != nil {
		log.Fatalf("Failed to enumerate EKs: %v", err)
	}

	// Read parameters necessary to generate a challenge.
	ap := ak.AttestationParameters()

	// Generate a credential activation challenge (usually done on the server).
	activation := attest.ActivationParameters{
		TPMVersion: tpm.Version(),
		EK:         ek[0].Public,
		AK:         ap,
	}
	secret, challenge, err := activation.Generate()
	if err != nil {
		log.Fatalf("Failed to generate activation challenge: %v", err)
	}

	// Challenge the AK & EK properties to recieve the decrypted secret.
	decrypted, err := ak.ActivateCredential(tpm, *challenge)
	if err != nil {
		log.Fatalf("Failed to activate credential: %v", err)
	}

	// Check that the AK completed the challenge (usually done on the server).
	if subtle.ConstantTimeCompare(secret, decrypted) == 0 {
		log.Fatal("Activation response did not match secret")
	}
}
Output:

Example (CredentialActivationWithEK)
package main

import (
	"crypto/subtle"
	"log"

	"github.com/google/go-attestation/attest"
)

func main() {
	tpm, err := attest.OpenTPM(nil)
	if err != nil {
		log.Fatalf("Failed to open TPM: %v", err)
	}
	defer tpm.Close()

	// Create a new AK.
	ak, err := tpm.NewAK(nil)
	if err != nil {
		log.Fatalf("Failed to create AK: %v", err)
	}
	defer ak.Close(tpm)

	// Read the EK certificates.
	ekCerts, err := tpm.EKCertificates()
	if err != nil {
		log.Fatalf("Failed to enumerate EKs: %v", err)
	}

	// Read parameters necessary to generate a challenge.
	ap := ak.AttestationParameters()

	// Try activating with each EK certificate.
	for _, ek := range ekCerts {
		// Generate a credential activation challenge (usually done on the server).
		activation := attest.ActivationParameters{
			TPMVersion: tpm.Version(),
			EK:         ek.Public,
			AK:         ap,
		}
		secret, challenge, err := activation.Generate()
		if err != nil {
			log.Fatalf("Failed to generate activation challenge: %v", err)
		}

		// Challenge the AK & EK properties to recieve the decrypted secret.
		decrypted, err := ak.ActivateCredentialWithEK(tpm, *challenge, ek)
		if err != nil {
			log.Fatalf("Failed to activate credential: %v", err)
		}

		// Check that the AK completed the challenge (usually done on the server).
		if subtle.ConstantTimeCompare(secret, decrypted) == 0 {
			log.Fatal("Activation response did not match secret")
		}
	}
}
Output:

func (*AK) ActivateCredential

func (k *AK) ActivateCredential(tpm *TPM, in EncryptedCredential) (secret []byte, err error)

ActivateCredential decrypts the secret using the key to prove that the AK was generated on the same TPM as the EK. This method can be used with TPMs that have the default EK, i.e. RSA EK with handle 0x81010001.

This operation is synonymous with TPM2_ActivateCredential.

func (*AK) ActivateCredentialWithEK

func (k *AK) ActivateCredentialWithEK(tpm *TPM, in EncryptedCredential, ek EK) (secret []byte, err error)

ActivateCredential decrypts the secret using the key to prove that the AK was generated on the same TPM as the EK. This method can be used with TPMs that have an ECC EK. The 'ek' argument must be one of EKs returned from TPM.EKs() or TPM.EKCertificates().

This operation is synonymous with TPM2_ActivateCredential.

func (*AK) AttestationParameters

func (k *AK) AttestationParameters() AttestationParameters

AttestationParameters returns information about the AK, typically used to generate a credential activation challenge.

func (*AK) Certify

func (k *AK) Certify(tpm *TPM, handle interface{}) (*CertificationParameters, error)

Certify uses the attestation key to certify the key with `handle`. It returns certification parameters which allow to verify the properties of the attested key. Depending on the actual instantiation it can accept different handle types (e.g., tpmutil.Handle on Linux or uintptr on Windows).

func (*AK) Close

func (k *AK) Close(t *TPM) error

Close unloads the AK from the system.

func (*AK) Marshal

func (k *AK) Marshal() ([]byte, error)

Marshal encodes the AK in a format that can be reloaded with tpm.LoadAK(). This method exists to allow consumers to store the key persistently and load it as a later time. Users SHOULD NOT attempt to interpret or extract values from this blob.

func (*AK) Quote

func (k *AK) Quote(tpm *TPM, nonce []byte, alg HashAlg) (*Quote, error)

Quote returns a quote over the platform state, signed by the AK.

This is a low-level API. Consumers seeking to attest the state of the platform should use tpm.AttestPlatform() instead.

func (*AK) QuotePCRs

func (k *AK) QuotePCRs(tpm *TPM, nonce []byte, alg HashAlg, pcrs []int) (*Quote, error)

QuotePCRs is like Quote() but allows the caller to select a subset of the PCRs.

type AKConfig

type AKConfig struct {
	// Parent describes the Storage Root Key that will be used as a parent.
	// If nil, the default SRK (i.e. RSA with handle 0x81000001) is assumed.
	// Supported only by TPM 2.0 on Linux.
	Parent *ParentKeyConfig
}

AKConfig encapsulates parameters for minting keys.

type AKPublic

type AKPublic struct {
	// Public is the public part of the AK. This can either be an *rsa.PublicKey or
	// and *ecdsa.PublicKey.
	Public crypto.PublicKey
	// Hash is the hashing algorithm the AK will use when signing quotes.
	Hash crypto.Hash
}

AKPublic holds structured information about an AK's public key.

func ParseAKPublic

func ParseAKPublic(version TPMVersion, public []byte) (*AKPublic, error)

ParseAKPublic parses the Public blob from the AttestationParameters, returning the public key and signing parameters for the key.

func (*AKPublic) Verify

func (a *AKPublic) Verify(quote Quote, pcrs []PCR, nonce []byte) error

Verify is used to prove authenticity of the PCR measurements. It ensures that the quote was signed by the AK, and that its contents matches the PCR and nonce combination. An error is returned if a provided PCR index was not part of the quote. QuoteVerified() will return true on PCRs which were verified by a quote.

Do NOT use this method if you have multiple quotes to verify: Use VerifyAll instead.

The nonce is used to prevent replays of Quote and PCRs and is signed by the quote. Some TPMs don't support nonces longer than 20 bytes, and if the nonce is used to tie additional data to the quote, the additional data should be hashed to construct the nonce.

func (*AKPublic) VerifyAll

func (a *AKPublic) VerifyAll(quotes []Quote, pcrs []PCR, nonce []byte) error

VerifyAll uses multiple quotes to verify the authenticity of all PCR measurements. See documentation on Verify() for semantics.

An error is returned if any PCRs provided were not covered by a quote, or if no quote/nonce was provided.

type ActivateOpts

type ActivateOpts struct {
	// EK, the endorsement key, describes an asymmetric key whose
	// private key is permanently bound to the TPM.
	//
	// Activation will verify that the provided EK is held on the same
	// TPM as the key we're certifying. However, it is the caller's responsibility to
	// ensure the EK they provide corresponds to the the device which
	// they are trying to associate the certified key with.
	EK crypto.PublicKey
	// VerifierKeyNameDigest is the name digest of the public key we're using to
	// verify the certification of the tpm-generated key being activated.
	// The verifier key (usually the AK) that owns this digest should be the same
	// key used in VerifyOpts.Public.
	// Use tpm2.Public.Name() to produce the digest for a provided key.
	VerifierKeyNameDigest *tpm2.HashValue
}

ActivateOpts specifies options for the key certification's challenge generation.

func NewActivateOpts

func NewActivateOpts(verifierPubKey tpm2.Public, ek crypto.PublicKey) (*ActivateOpts, error)

NewActivateOpts creates options for use in generating an activation challenge for a certified key. The computed hash is the name digest of the public key used to verify the certification of our key.

type ActivationParameters

type ActivationParameters struct {
	// TPMVersion holds the version of the TPM, either 1.2 or 2.0.
	TPMVersion TPMVersion

	// EK, the endorsement key, describes an asymmetric key whose
	// private key is permanently bound to the TPM.
	//
	// Activation will verify that the provided EK is held on the same
	// TPM as the AK. However, it is the caller's responsibility to
	// ensure the EK they provide corresponds to the the device which
	// they are trying to associate the AK with.
	EK crypto.PublicKey

	// AK, the Attestation Key, describes the properties of
	// an asymmetric key (managed by the TPM) which signs attestation
	// structures.
	// The values from this structure can be obtained by calling
	// Parameters() on an attest.AK.
	AK AttestationParameters

	// Rand is a source of randomness to generate a seed and secret for the
	// challenge.
	//
	// If nil, this defaults to crypto.Rand.
	Rand io.Reader
}

ActivationParameters encapsulates the inputs for activating an AK.

func (*ActivationParameters) Generate

func (p *ActivationParameters) Generate() (secret []byte, ec *EncryptedCredential, err error)

Generate returns a credential activation challenge, which can be provided to the TPM to verify the AK parameters given are authentic & the AK is present on the same TPM as the EK.

The caller is expected to verify the secret returned from the TPM as as result of calling ActivateCredential() matches the secret returned here. The caller should use subtle.ConstantTimeCompare to avoid potential timing attack vectors.

type Algorithm

type Algorithm string

Algorithm indicates an asymmetric algorithm to be used.

const (
	ECDSA Algorithm = "ECDSA"
	RSA   Algorithm = "RSA"
)

Algorithm types supported.

type AttestationParameters

type AttestationParameters struct {
	// Public represents the AK's canonical encoding. This blob includes the
	// public key, as well as signing parameters such as the hash algorithm
	// used to generate quotes.
	//
	// Use ParseAKPublic to access the key's data.
	Public []byte

	// UseTCSDActivationFormat is set when tcsd (trousers daemon) is operating
	// as an intermediary between this library and the TPM. A value of true
	// indicates that activation challenges should use the TCSD-specific format.
	UseTCSDActivationFormat bool

	// CreateData represents the properties of a TPM 2.0 key. It is encoded
	// as a TPMS_CREATION_DATA structure.
	CreateData []byte
	// CreateAttestation represents an assertion as to the details of the key.
	// It is encoded as a TPMS_ATTEST structure.
	CreateAttestation []byte
	// CreateSignature represents a signature of the CreateAttestation structure.
	// It is encoded as a TPMT_SIGNATURE structure.
	CreateSignature []byte
}

AttestationParameters describes information about a key which is necessary for verifying its properties remotely.

type BitlockerStatus

type BitlockerStatus uint8

BitlockerStatus describes the status of BitLocker on a Windows system.

type CertificationParameters

type CertificationParameters struct {
	// Public represents the key's canonical encoding (a TPMT_PUBLIC structure).
	// It includes the public key and signing parameters.
	Public []byte
	// CreateData represents the properties of a TPM 2.0 key. It is encoded
	// as a TPMS_CREATION_DATA structure.
	CreateData []byte
	// CreateAttestation represents an assertion as to the details of the key.
	// It is encoded as a TPMS_ATTEST structure.
	CreateAttestation []byte
	// CreateSignature represents a signature of the CreateAttestation structure.
	// It is encoded as a TPMT_SIGNATURE structure.
	CreateSignature []byte
}

CertificationParameters encapsulates the inputs for certifying an application key. Only TPM 2.0 is supported at this point.

func (*CertificationParameters) Generate

func (p *CertificationParameters) Generate(rnd io.Reader, verifyOpts VerifyOpts, activateOpts ActivateOpts) (secret []byte, ec *EncryptedCredential, err error)

Generate returns a credential activation challenge, which can be provided to the TPM to verify the AK parameters given are authentic & the AK is present on the same TPM as the EK.

The caller is expected to verify the secret returned from the TPM as as result of calling ActivateCredential() matches the secret returned here. The caller should use subtle.ConstantTimeCompare to avoid potential timing attack vectors.

func (*CertificationParameters) Verify

func (p *CertificationParameters) Verify(opts VerifyOpts) error

Verify verifies the TPM2-produced certification parameters checking whether: - the key length is secure - the attestation parameters matched the attested key - the key was TPM-generated and resides within TPM - the key can sign/decrypt outside-TPM objects - the signature is successfuly verified against the passed public key For now, it accepts only RSA verification keys.

type CommandChannelTPM20

type CommandChannelTPM20 interface {
	io.ReadWriteCloser
	MeasurementLog() ([]byte, error)
}

CommandChannelTPM20 represents a pipe along which TPM 2.0 commands can be issued, and measurement logs read.

type DriverLoadSource

type DriverLoadSource uint8

DriverLoadSource describes the logical origin of a boot services driver.

const (
	UnknownSource DriverLoadSource = iota
	PciMmioSource
)

type EK

type EK struct {
	// Public key of the EK.
	Public crypto.PublicKey

	// Certificate is the EK certificate for TPMs that provide it.
	Certificate *x509.Certificate

	// For Intel TPMs, Intel hosts certificates at a public URL derived from the
	// Public key. Clients or servers can perform an HTTP GET to this URL, and
	// use ParseEKCertificate on the response body.
	CertificateURL string
	// contains filtered or unexported fields
}

EK is a burned-in endorcement key bound to a TPM. This optionally contains a certificate that can chain to the TPM manufacturer.

type EncryptedCredential

type EncryptedCredential struct {
	Credential []byte
	Secret     []byte
}

EncryptedCredential represents encrypted parameters which must be activated against a key.

type Event

type Event struct {

	// Index of the PCR that this event was replayed against.
	Index int
	// Untrusted type of the event. This value is not verified by event log replays
	// and can be tampered with. It should NOT be used without additional context,
	// and unrecognized event types should result in errors.
	Type EventType

	// Data of the event. For certain kinds of events, this must match the event
	// digest to be valid.
	Data []byte
	// Digest is the verified digest of the event data. While an event can have
	// multiple for different hash values, this is the one that was matched to the
	// PCR value.
	Digest []byte
	// contains filtered or unexported fields
}

Event is a single event from a TCG event log. This reports descrete items such as BIOS measurements or EFI states.

There are many pitfalls for using event log events correctly to determine the state of a machine[1]. In general it's much safer to only rely on the raw PCR values and use the event log for debugging.

[1] https://github.com/google/go-attestation/blob/master/docs/event-log-disclosure.md

type EventLog

type EventLog struct {
	// Algs holds the set of algorithms that the event log uses.
	Algs []HashAlg
	// contains filtered or unexported fields
}

EventLog is a parsed measurement log. This contains unverified data representing boot events that must be replayed against PCR values to determine authenticity.

func ParseEventLog

func ParseEventLog(measurementLog []byte) (*EventLog, error)

ParseEventLog parses an unverified measurement log.

func (*EventLog) Events

func (e *EventLog) Events(hash HashAlg) []Event

Events returns events that have not been replayed against the PCR values and are therefore unverified. The returned events contain the digest that matches the provided hash algorithm, or are empty if that event didn't contain a digest for that hash.

This method is insecure and should only be used for debugging.

func (*EventLog) Verify

func (e *EventLog) Verify(pcrs []PCR) ([]Event, error)

Verify replays the event log against a TPM's PCR values, returning the events which could be matched to a provided PCR value.

PCRs provide no security guarantees unless they're attested to have been generated by a TPM. Verify does not perform these checks.

An error is returned if the replayed digest for events with a given PCR index do not match any provided value for that PCR index.

type EventType

type EventType uint32

EventType indicates what kind of data an event is reporting.

https://trustedcomputinggroup.org/wp-content/uploads/TCG_PCClientSpecPlat_TPM_2p0_1p04_pub.pdf#page=103

func (EventType) String

func (e EventType) String() string

String returns the Spec name of the EventType, for example "EV_ACTION". If unknown, it returns a formatted string of the EventType value.

type HashAlg

type HashAlg uint8

HashAlg identifies a hashing Algorithm.

func (HashAlg) String

func (a HashAlg) String() string

String returns a human-friendly representation of the hash algorithm.

type Key

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

Key represents a key which can be used for signing and decrypting outside-TPM objects.

func (*Key) Blobs

func (k *Key) Blobs() (pub, priv []byte, err error)

Blobs returns public and private blobs to be used by tpm2.Load().

func (*Key) CertificationParameters

func (k *Key) CertificationParameters() CertificationParameters

CertificationParameters returns information about the key required to verify key certification.

func (*Key) Close

func (k *Key) Close() error

Close unloads the key from the system.

func (*Key) Marshal

func (k *Key) Marshal() ([]byte, error)

Marshal encodes the key in a format that can be loaded with tpm.LoadKey(). This method exists to allow consumers to store the key persistently and load it as a later time. Users SHOULD NOT attempt to interpret or extract values from this blob.

func (*Key) Private

func (k *Key) Private(pub crypto.PublicKey) (crypto.PrivateKey, error)

Private returns an object allowing to use the TPM-backed private key. For now it implements only crypto.Signer.

func (*Key) Public

func (k *Key) Public() crypto.PublicKey

Public returns the public key corresponding to the private key.

type KeyConfig

type KeyConfig struct {
	// Algorithm to be used, either RSA or ECDSA.
	Algorithm Algorithm
	// Size is used to specify the bit size of the key or elliptic curve. For
	// example, '256' is used to specify curve P-256.
	Size int
	// Parent describes the Storage Root Key that will be used as a parent.
	// If nil, the default SRK (i.e. RSA with handle 0x81000001) is assumed.
	// Supported only by TPM 2.0 on Linux.
	Parent *ParentKeyConfig
}

KeyConfig encapsulates parameters for minting keys.

type OpenConfig

type OpenConfig struct {
	// TPMVersion indicates which TPM version the library should
	// attempt to use. If the specified version is not available,
	// ErrTPMNotAvailable is returned. Defaults to TPMVersionAgnostic.
	TPMVersion TPMVersion

	// CommandChannel provides a TPM 2.0 command channel, which can be
	// used in-lieu of any TPM present on the platform.
	CommandChannel CommandChannelTPM20
}

OpenConfig encapsulates settings passed to OpenTPM().

type PCR

type PCR struct {
	Index     int
	Digest    []byte
	DigestAlg crypto.Hash
	// contains filtered or unexported fields
}

PCR encapsulates the value of a PCR at a point in time.

func (*PCR) QuoteVerified

func (p *PCR) QuoteVerified() bool

QuoteVerified returns true if the value of this PCR was previously verified against a Quote, in a call to AKPublic.Verify or AKPublic.VerifyAll.

type ParentKeyConfig

type ParentKeyConfig struct {
	Algorithm Algorithm
	Handle    tpmutil.Handle
}

ParentKeyConfig describes the Storage Root Key that is used as a parent for new keys.

type PlatformAttestConfig

type PlatformAttestConfig struct {
	// If non-nil, the raw event log will be read from EventLog
	// instead of being obtained from the running system.
	EventLog []byte
}

PlatformAttestConfig configures how attestations are generated through tpm.AttestPlatform().

type PlatformParameters

type PlatformParameters struct {
	// The version of the TPM which generated this attestation.
	TPMVersion TPMVersion
	// The public blob of the AK which endorsed the platform state. This can
	// be decoded to verify the adjacent quotes using ParseAKPublic().
	Public []byte
	// The set of quotes which endorse the state of the PCRs.
	Quotes []Quote
	// The set of expected PCR values, which are used in replaying the event log
	// to verify digests were not tampered with.
	PCRs []PCR
	// The raw event log provided by the platform. This can be processed with
	// ParseEventLog().
	EventLog []byte
}

PlatformParameters encapsulates the set of information necessary to attest the booted state of the machine the TPM is attached to.

The digests contained in the event log can be considered authentic if:

  • The AK public corresponds to the known AK for that platform.
  • All quotes are verified with AKPublic.Verify(), and return no errors.
  • The event log parsed successfully using ParseEventLog(), and a call to EventLog.Verify() with the full set of PCRs returned no error.

type Quote

type Quote struct {
	Version   TPMVersion
	Quote     []byte
	Signature []byte
}

Quote encapsulates the results of a Quote operation against the TPM, using an attestation key.

type ReplayError

type ReplayError struct {
	Events []Event
	// InvalidPCRs reports the set of PCRs where the event log replay failed.
	InvalidPCRs []int
}

ReplayError describes the parsed events that failed to verify against a particular PCR.

func (ReplayError) Error

func (e ReplayError) Error() string

Error returns a human-friendly description of replay failures.

type SecurebootState

type SecurebootState struct {
	Enabled bool

	// PlatformKeys enumerates keys which can sign a key exchange key.
	PlatformKeys []x509.Certificate
	// PlatformKeys enumerates key hashes which can sign a key exchange key.
	PlatformKeyHashes [][]byte

	// ExchangeKeys enumerates keys which can sign a database of permitted or
	// forbidden keys.
	ExchangeKeys []x509.Certificate
	// ExchangeKeyHashes enumerates key hashes which can sign a database or
	// permitted or forbidden keys.
	ExchangeKeyHashes [][]byte

	// PermittedKeys enumerates keys which may sign binaries to run.
	PermittedKeys []x509.Certificate
	// PermittedHashes enumerates hashes which permit binaries to run.
	PermittedHashes [][]byte

	// ForbiddenKeys enumerates keys which must not permit a binary to run.
	ForbiddenKeys []x509.Certificate
	// ForbiddenKeys enumerates hashes which must not permit a binary to run.
	ForbiddenHashes [][]byte

	// PreSeparatorAuthority describes the use of a secure-boot key to authorize
	// the execution of a binary before the separator.
	PreSeparatorAuthority []x509.Certificate
	// PostSeparatorAuthority describes the use of a secure-boot key to authorize
	// the execution of a binary after the separator.
	PostSeparatorAuthority []x509.Certificate

	// DriverLoadSourceHints describes the origin of boot services drivers.
	// This data is not tamper-proof and must only be used as a hint.
	DriverLoadSourceHints []DriverLoadSource

	// DMAProtectionDisabled is true if the platform reports during boot that
	// DMA protection is supported but disabled.
	//
	// See: https://docs.microsoft.com/en-us/windows-hardware/design/device-experiences/oem-kernel-dma-protection
	DMAProtectionDisabled bool
}

SecurebootState describes the secure boot status of a machine, as determined by processing its event log.

func ParseSecurebootState

func ParseSecurebootState(events []Event) (*SecurebootState, error)

ParseSecurebootState parses a series of events to determine the configuration of secure boot on a device. An error is returned if the state cannot be determined, or if the event log is structured in such a way that it may have been tampered post-execution of platform firmware.

type TCGVendorID

type TCGVendorID uint32

TCGVendorID represents a unique TCG manufacturer code. The canonical reference used is located at: https://trustedcomputinggroup.org/wp-content/uploads/TCG-TPM-Vendor-ID-Registry-Version-1.01-Revision-1.00.pdf

func (TCGVendorID) String

func (id TCGVendorID) String() string

type TPM

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

TPM interfaces with a TPM device on the system.

func InjectSimulatedTPMForTest

func InjectSimulatedTPMForTest(rwc io.ReadWriteCloser) *TPM

InjectSimulatedTPMForTest returns a fake TPM that interfaces with the provided simulated TPM. This method should be used for testing only.

func OpenTPM

func OpenTPM(config *OpenConfig) (*TPM, error)

OpenTPM initializes access to the TPM based on the config provided.

func (*TPM) AttestPlatform

func (t *TPM) AttestPlatform(ak *AK, nonce []byte, config *PlatformAttestConfig) (*PlatformParameters, error)

AttestPlatform computes the set of information necessary to attest the state of the platform. For TPM 2.0 devices, AttestPlatform will attempt to read both SHA1 & SHA256 PCR banks and quote both of them, so bugs in platform firmware which break replay for one PCR bank can be mitigated using the other. The provided config, if not nil, can be used to configure aspects of the platform attestation.

Example
package main

import (
	"log"

	"github.com/google/go-attestation/attest"
)

func main() {
	tpm, err := attest.OpenTPM(nil)
	if err != nil {
		log.Fatalf("Failed to open TPM: %v", err)
	}
	defer tpm.Close()

	// Create a new AK.
	ak, err := tpm.NewAK(nil)
	if err != nil {
		log.Fatalf("Failed to create AK: %v", err)
	}
	defer ak.Close(tpm)

	// The nonce would typically be provided by the server.
	nonce := []byte{1, 2, 3, 4, 5, 6, 7, 8}

	// Perform an attestation against the state of the plaform. Usually, you
	// would pass a nil config, and the event log would be read from the
	// platform. To ensure this example runs on platforms without event logs,
	// we pass a fake EventLog value.
	att, err := tpm.AttestPlatform(ak, nonce, &attest.PlatformAttestConfig{
		EventLog: []byte{0},
	})
	if err != nil {
		log.Fatalf("Failed to attest the platform state: %v", err)
	}

	// Construct an AKPublic struct from the parameters of the key. This
	// will be used to  verify the quote signatures.
	pub, err := attest.ParseAKPublic(tpm.Version(), ak.AttestationParameters().Public)
	if err != nil {
		log.Fatalf("Failed to parse AK public: %v", err)
	}

	for i, q := range att.Quotes {
		if err := pub.Verify(q, att.PCRs, nonce); err != nil {
			log.Fatalf("quote[%d] verification failed: %v", i, err)
		}
	}
}
Output:

func (*TPM) Close

func (t *TPM) Close() error

Close shuts down the connection to the TPM.

func (*TPM) EKCertificates

func (t *TPM) EKCertificates() ([]EK, error)

EKCertificates returns the endorsement key certificates burned-in to the platform. It is guaranteed that each EK.Certificate field will be populated.

func (*TPM) EKs

func (t *TPM) EKs() ([]EK, error)

EKs returns the endorsement keys burned-in to the platform.

func (*TPM) Info

func (t *TPM) Info() (*TPMInfo, error)

Info returns information about the TPM.

func (*TPM) LoadAK

func (t *TPM) LoadAK(opaqueBlob []byte) (*AK, error)

LoadAK loads a previously-created ak into the TPM for use. A key loaded via this function needs to be closed with .Close(). Only blobs generated by calling AK.Marshal() are valid parameters to this function.

func (*TPM) LoadAKWithParent

func (t *TPM) LoadAKWithParent(opaqueBlob []byte, parent ParentKeyConfig) (*AK, error)

LoadAKWithParent loads a previously-created ak into the TPM under the given parent for use.

func (*TPM) LoadKey

func (t *TPM) LoadKey(opaqueBlob []byte) (*Key, error)

LoadKey loads a previously-created application key into the TPM for use. A key loaded via this function needs to be closed with .Close(). Only blobs generated by calling Key.Marshal() are valid parameters to this function.

func (*TPM) MeasurementLog

func (t *TPM) MeasurementLog() ([]byte, error)

MeasurementLog returns the present value of the System Measurement Log.

This is a low-level API. Consumers seeking to attest the state of the platform should use tpm.AttestPlatform() instead.

func (*TPM) NewAK

func (t *TPM) NewAK(opts *AKConfig) (*AK, error)

NewAK creates an attestation key.

func (*TPM) NewKey

func (t *TPM) NewKey(ak *AK, opts *KeyConfig) (*Key, error)

NewKey creates an application key certified by the attestation key. If opts is nil then DefaultConfig is used.

func (*TPM) PCRs

func (t *TPM) PCRs(alg HashAlg) ([]PCR, error)

PCRs returns the present value of Platform Configuration Registers with the given digest algorithm.

This is a low-level API. Consumers seeking to attest the state of the platform should use tpm.AttestPlatform() instead.

func (*TPM) Version

func (t *TPM) Version() TPMVersion

Version returns the version of the TPM.

type TPMInfo

type TPMInfo struct {
	Version      TPMVersion
	Interface    TPMInterface
	VendorInfo   string
	Manufacturer TCGVendorID

	// FirmwareVersionMajor and FirmwareVersionMinor describe
	// the firmware version of the TPM, but are only available
	// for TPM 2.0 devices.
	FirmwareVersionMajor int
	FirmwareVersionMinor int
}

TPMInfo contains information about the version & interface of an open TPM.

func AvailableTPMs

func AvailableTPMs(config *OpenConfig) ([]TPMInfo, error)

AvailableTPMs returns information about available TPMs matching the given config, without opening the devices.

type TPMInterface

type TPMInterface uint8

TPMInterface indicates how the client communicates with the TPM.

const (
	TPMInterfaceDirect TPMInterface = iota
	TPMInterfaceKernelManaged
	TPMInterfaceDaemonManaged
	TPMInterfaceCommandChannel
)

TPM interfaces

type TPMVersion

type TPMVersion uint8

TPMVersion is used to configure a preference in which TPM to use, if multiple are available.

const (
	TPMVersionAgnostic TPMVersion = iota
	TPMVersion12
	TPMVersion20
)

TPM versions

type Ternary

type Ternary uint8

Ternary describes a boolean value that can additionally be unknown.

const (
	TernaryUnknown Ternary = iota
	TernaryTrue
	TernaryFalse
)

Valid Ternary values.

type VerifyOpts

type VerifyOpts struct {
	// Public is the public key used to verify key ceritification.
	Public crypto.PublicKey
	// Hash is the hash function used for signature verification. It can be
	// extracted from the properties of the certifying key.
	Hash crypto.Hash
}

VerifyOpts specifies options for the key certification's verification.

type WinCSPAlg

type WinCSPAlg uint32
const (
	WinAlgMD4    WinCSPAlg = 0x02
	WinAlgMD5    WinCSPAlg = 0x03
	WinAlgSHA1   WinCSPAlg = 0x04
	WinAlgSHA256 WinCSPAlg = 0x0c
	WinAlgSHA384 WinCSPAlg = 0x0d
	WinAlgSHA512 WinCSPAlg = 0x0e
)

Valid CSP Algorithm IDs.

type WinELAM

type WinELAM struct {
	Measured []byte
	Config   []byte
	Policy   []byte
}

WinELAM describes the configuration of an Early Launch AntiMalware driver. These values represent the 3 measured registry values stored in the ELAM hive for the driver.

type WinEvents

type WinEvents struct {
	// ColdBoot is set to true if the system was not resuming from hibernation.
	ColdBoot bool
	// BootCount contains the value of the monotonic boot counter. This
	// value is not set for TPM 1.2 devices and some TPMs with buggy
	// implementations of monotonic counters.
	BootCount uint64
	// LoadedModules contains authenticode hashes for binaries which
	// were loaded during boot.
	LoadedModules map[string]WinModuleLoad
	// ELAM describes the configuration of each Early Launch AntiMalware driver,
	// for each AV Vendor key.
	ELAM map[string]WinELAM
	// BootDebuggingEnabled is true if boot debugging was ever reported
	// as enabled.
	BootDebuggingEnabled bool
	// KernelDebugEnabled is true if kernel debugging was recorded as
	// enabled at any point during boot.
	KernelDebugEnabled bool
	// DEPEnabled is true if NX (Data Execution Prevention) was consistently
	// reported as enabled.
	DEPEnabled Ternary
	// CodeIntegrityEnabled is true if code integrity was consistently
	// reported as enabled.
	CodeIntegrityEnabled Ternary
	// TestSigningEnabled is true if test-mode signature verification was
	// ever reported as enabled.
	TestSigningEnabled bool
	// BitlockerUnlocks reports the bitlocker status for every instance of
	// a disk unlock, where bitlocker was used to secure the disk.
	BitlockerUnlocks []BitlockerStatus
}

WinEvents describes information from the event log recorded during bootup of Microsoft Windows.

func ParseWinEvents

func ParseWinEvents(events []Event) (*WinEvents, error)

ParseWinEvents parses a series of events to extract information about the bringup of Microsoft Windows. This information is not trustworthy unless the integrity of platform & bootloader events has already been established.

type WinModuleLoad

type WinModuleLoad struct {
	// FilePath represents the path from which the module was loaded. This
	// information is not always present.
	FilePath string
	// AuthenticodeHash contains the authenticode hash of the binary
	// blob which was loaded.
	AuthenticodeHash []byte
	// ImageBase describes all the addresses to which the the blob was loaded.
	ImageBase []uint64
	// ImageSize describes the size of the image in bytes. This information
	// is not always present.
	ImageSize uint64
	// HashAlgorithm describes the hash algorithm used.
	HashAlgorithm WinCSPAlg
	// ImageValidated is set if the post-boot loader validated the image.
	ImageValidated bool

	// AuthorityIssuer identifies the issuer of the certificate which certifies
	// the signature on this module.
	AuthorityIssuer string
	// AuthorityPublisher identifies the publisher of the certificate which
	// certifies the signature on this module.
	AuthorityPublisher string
	// AuthoritySerial contains the serial of the certificate certifying this
	// module.
	AuthoritySerial []byte
	// AuthoritySHA1 is the SHA1 hash of the certificate thumbprint.
	AuthoritySHA1 []byte
}

WinModuleLoad describes a module which was loaded while Windows booted.

Directories

Path Synopsis
Binary attest-tool performs attestation operations on the local system.
Binary attest-tool performs attestation operations on the local system.
internal
Package internal contains marshalling structures for attest-tool and tests.
Package internal contains marshalling structures for attest-tool and tests.
internal/eventlog
Package eventlog implements experimental logic for parsing the TCG event log format.
Package eventlog implements experimental logic for parsing the TCG event log format.

Jump to

Keyboard shortcuts

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