efitcg2

package module
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Oct 5, 2026 License: BSD-3-Clause Imports: 1 Imported by: 1 module, 1 package

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

go-tpm2/efitcg2

go-tpm2/efitcg2

CI Go Reference Coverage License

A pure-Go TPM 2.0 transport backed by the UEFI EFI_TCG2_PROTOCOL. v0.2.0.

Firmware-validated: the cloud-boot loader extends PCR4 through this transport's MeasureToPCR (HashLogExtendEvent) on real x86 OVMF firmware (Fedora OVMF.stateless.fd + tpm-crb + swtpm), confirmed in the firmware DEBUG log. v0.1.1 fixed the SubmitCommand output block to respect the firmware's MaxResponseSize (the CRB ceiling is 3968 = 0x1000−0x80, not 4096) — found by that real-firmware run.

v0.2.0 adds GetEventLog: fetch the firmware-maintained TCG event log (via the optional EventLogCaller) so go-tpm2/attest can ParseEventLog + ReplayPCRs it and confirm the replay matches the firmware's PCRs — the attestation payoff of a measured boot.

efitcg2 implements github.com/go-tpm2/common's Transport so that go-tpm2's command layer (Quote, GetCapability, seal/unseal, …) can drive a firmware TPM while the machine is still in Boot Services — for example a TamaGo + UEFI loader running under OVMF, where the TPM is owned by firmware and raw TIS/CRB MMIO is the wrong interface.

The protocol is the TCG EFI Protocol Specification, Family 2.0, clause EFI_TCG2_PROTOCOL (surfaced in the UEFI specification).

Why not TIS/CRB here?

Under a pre-ExitBootServices loader the firmware already owns the TPM: localities, active PCR banks, and the TCG event log are established, and firmware is still servicing the device. EFI_TCG2_PROTOCOL.SubmitCommand is the supported path for a marshaled TPM 2.0 command, and HashLogExtendEvent is the supported measured-boot primitive (it extends a PCR and appends an event-log record in one firmware call). Poking TIS/CRB registers directly at that point races firmware and is incorrect.

Dependency discipline

go-tpm2 stays UEFI/TamaGo-dependency-free. This package never imports an EFI runtime, never dereferences a protocol pointer, and never uses package unsafe. It takes an injected firmware-call mechanism — a Caller the loader implements — exactly the way go-tpm2/tis and go-tpm2/crb take an injected common.Regs. The loader owns the protocol pointer and the EFI calling convention; efitcg2 only marshals buffers and interprets results.

The injected-Caller contract (this is what the loader implements)

// Caller is the entire UEFI-facing surface of efitcg2. The loader holds the
// EFI_TCG2_PROTOCOL pointer + the platform efiCall and performs the actual
// firmware invocation; efitcg2 hands it marshaled buffers and reads the
// returned EFI_STATUS. A non-nil err reports a failure to perform the call
// itself (distinct from a non-success status); when err is nil, status
// alone decides success.
type Caller interface {
    // EFI_TCG2_PROTOCOL.SubmitCommand(This, len(inputBlock), inputBlock,
    //                                 len(output), output)
    // Firmware writes the TPM response into output in place.
    SubmitCommand(inputBlock []byte, output []byte) (status uintptr, err error)

    // EFI_TCG2_PROTOCOL.HashLogExtendEvent(This, flags, dataToHash,
    //                                      len(dataToHash), event)
    // event is the serialized EFI_TCG2_EVENT (its leading Size states its
    // own length).
    HashLogExtendEvent(flags uint64, dataToHash []byte, event []byte) (status uintptr, err error)
}

status is the raw EFI_STATUS as a uintptr, so the platform's native word width carries the high "error" bit unchanged. efitcg2 maps it: EFI_SUCCESS → nil, and EFI_INVALID_PARAMETER / EFI_BUFFER_TOO_SMALL / EFI_DEVICE_ERROR / EFI_NOT_FOUND / any-other-error to typed sentinels.

A loader that prefers a single low-level dispatcher may implement Caller over a Call(method int, args ...uintptr) uintptr closure using the exported Method* ordinals (MethodGetCapability … MethodGetResultOfSetActivePcrBanks, declaration order) — that is invisible to efitcg2.

Optional extensions (CapabilityCaller, EventLogCaller)

A Caller MAY also implement either of these optional interfaces; efitcg2 type-asserts for them and degrades gracefully when they are absent.

// CapabilityCaller (v0.1.1) — report EFI_TCG2_BOOT_SERVICE_CAPABILITY.
// MaxResponseSize so Send clamps its SubmitCommand output block to it
// (CRB/TIS-backed firmware rejects an over-large block). Vtable index 0.
// (0, nil) = "not reported, use the requested/default size".
type CapabilityCaller interface {
    GetCapability() (maxResponseSize uint32, err error)
}

// EventLogCaller (v0.2.0) — fetch the FIRMWARE-maintained TCG event log.
// EFI_TCG2_PROTOCOL.GetEventLog (vtable index 1) returns firmware-memory
// ADDRESSES, not bytes, so the loader performs the whole firmware op:
// call GetEventLog → take EventLogLocation/EventLogLastEntry/
// EventLogTruncated → size the last TCG_PCR_EVENT2 entry → read the byte
// range [location, lastEntry + sizeof(last entry)) from firmware memory →
// return the assembled bytes + the firmware's truncation flag.
type EventLogCaller interface {
    GetEventLog(format uint32) (log []byte, truncated bool, err error)
}

Reading firmware memory needs the loader's identity-mapped access, which is outside efitcg2's UEFI-free remit — hence the firmware-memory read lives in the Caller, exactly like SubmitCommand/HashLogExtendEvent. efitcg2 only defines the format constants, type-asserts, and returns the assembled bytes for attest.ParseEventLog.

Loader-side integration sketch (cloud-boot)

import (
    "github.com/go-tpm2/common"
    "github.com/go-tpm2/efitcg2"
    // loader's own UEFI bindings — NOT imported by efitcg2/go-tpm2:
    "example.com/cloudboot/uefi"
)

// 1. Locate the protocol once, early in Boot Services.
var tcg2 *uefi.Protocol
err := bootServices.LocateProtocol(efitcg2.TCG2ProtocolGUID, nil, &tcg2)

// 2. Implement Caller over the located pointer + the platform efiCall.
type fwCaller struct{ p *uefi.Protocol }

func (f fwCaller) SubmitCommand(in, out []byte) (uintptr, error) {
    // efiCall(f.p.SubmitCommand, This, inLen, &in[0], outLen, &out[0])
    return uefi.Call(f.p.SubmitCommand,
        uintptr(unsafe.Pointer(f.p)),
        uintptr(len(in)), uintptr(unsafe.Pointer(&in[0])),
        uintptr(len(out)), uintptr(unsafe.Pointer(&out[0]))), nil
}
func (f fwCaller) HashLogExtendEvent(flags uint64, data, event []byte) (uintptr, error) {
    return uefi.Call(f.p.HashLogExtendEvent,
        uintptr(unsafe.Pointer(f.p)), uintptr(flags),
        uintptr(unsafe.Pointer(&data[0])), uintptr(len(data)),
        uintptr(unsafe.Pointer(&event[0]))), nil
}

// 3. Wrap it as a common.Transport and hand it to go-tpm2.
tpm := efitcg2.New(fwCaller{p: tcg2})    // *efitcg2.TCG2 satisfies common.Transport
rsp, err := tpm.Send(cmd)                // any tpm2 command works over EFI_TCG2

// 4. Measured boot: extend a PCR AND append a TCG event-log record.
err = tpm.MeasureToPCR(8, eventType, imageBytes, []byte("kernel"))

(The unsafe/efiCall lives in the loader, never in efitcg2.)

API

  • New(c Caller) *TCG2 / NewWithOutputSize(c, n) — bind the transport; the output buffer defaults to DefaultOutputSize (3968, the firmware-proven CRB ceiling 0x1000−0x80), or the CapabilityCaller-reported MaxResponseSize when smaller.
  • (*TCG2) Send(cmd []byte) ([]byte, error) — common.Transport. Calls SubmitCommand with cmd as the InputParameterBlock, parses the 10-byte TPM response header (common.GetU32 of responseSize), bounds-checks it, and returns the response trimmed to that size.
  • (*TCG2) MeasureToPCR(pcr, eventType uint32, data, eventDesc []byte) error / MeasureToPCRWithFlags(flags, …) — build an EFI_TCG2_EVENT and call HashLogExtendEvent.
  • (*TCG2) GetEventLog() ([]byte, error) — fetch the firmware's crypto-agile (EventLogFormatTCG_2) TCG event log via the optional EventLogCaller; the bytes feed attest.ParseEventLog verbatim. Returns ErrEventLogUnsupported when the Caller does not implement EventLogCaller (firmware never asked), and surfaces the bytes alongside ErrEventLogTruncated when the firmware reports the log overflowed (a truncated log will not replay to the PCRs — reject it for attestation; check errors.Is(err, efitcg2.ErrEventLogTruncated)).
  • TCG2ProtocolGUID (607f766c-7455-42be-930b-e4d76db2720f) — pass to LocateProtocol.

EFI_TCG2_EVENT layout emitted by MeasureToPCR

Little-endian, packed, 1-byte aligned (UEFI #pragma pack(1)), unlike the big-endian TPM 2.0 wire stream Send carries. TCG "EFI Protocol Specification", EFI_TCG2_EVENT / EFI_TCG2_EVENT_HEADER:

offset size field
  0     u32  Size                 = 18 + len(eventDesc)   (total)
  4     u32  Header.HeaderSize    = 14
  8     u16  Header.HeaderVersion = 1
 10     u32  Header.PCRIndex      = pcr
 14     u32  Header.EventType     = eventType
 18     ...  Event[]              = eventDesc

INFERRED items (confirm under OVMF)

The spec fixes the method order, GUID, struct fields, flags, and EFI_STATUS codes; the EFI ABI details are platform-dependent and marked // INFERRED: in the source for the OVMF validation:

  • Vtable byte offsets — Method* ordinals map to ordinal*sizeof(void*) only if firmware packs the protocol struct with no inter-member padding. efitcg2 itself never indexes the vtable (it has no protocol pointer); only a Call-style loader does.
  • EFI_TCG2_EVENT packing/alignment — assumed #pragma pack(1), little-endian, no padding. Byte-asserted in tests against a hand-derived buffer; OVMF confirms firmware accepts it.
  • DefaultOutputSize = 3968 — CONFIRMED on OVMF: the original 4096 was too large — OVMF's CRB-backed EFI_TCG2_PROTOCOL advertises MaxResponseSize = 0xF80 = 3968 and rejects a larger SubmitCommand output block with EFI_INVALID_PARAMETER. CapabilityCaller lets the firmware's actual ceiling override this fallback.

The unit tests here use a fake firmware Caller (including a fake EventLogCaller returning a canned crypto-agile log). End-to-end firmware validation — MeasureToPCR/HashLogExtendEvent, the SubmitCommand readback, and the GetEventLog→attest replay loop — lives in the cloud-boot integration step against real OVMF + swtpm.

Conventions

Pure Go, CGO_ENABLED=0, no assembly, BSD-3-Clause, 100% statement coverage (GOWORK=off go test -cover). Spec citations are inline; ABI-dependent values are marked // INFERRED:.

Documentation

Overview

Package efitcg2 implements a TPM 2.0 github.com/go-tpm2/common.Transport backed by the UEFI EFI_TCG2_PROTOCOL, so that go-tpm2's command layer can drive a firmware TPM while the machine is still in Boot Services.

Motivation. Under a pre-ExitBootServices UEFI loader (for example a TamaGo + UEFI image running under OVMF), the TPM is owned by firmware and reached through the EFI_TCG2_PROTOCOL, not through raw TIS/CRB MMIO. The firmware has already established locality, banks, and the event log; touching the TIS/CRB register file directly at that point is wrong and races the firmware. EFI_TCG2_PROTOCOL.SubmitCommand is the supported way to pass a marshaled TPM 2.0 command to the firmware TPM, and HashLogExtendEvent is the supported measured-boot primitive (it extends a PCR *and* appends a TCG event-log record in one firmware call).

Specification. The protocol is defined by the TCG "EFI Protocol Specification, Family 2.0" (a.k.a. the TCG EFI Protocol Specification), clause "EFI_TCG2_PROTOCOL", and surfaced in the UEFI specification. Every GUID, method order, structure layout, EFI_STATUS value, and flag below is cited inline to that specification. Items the spec leaves to the ABI/ platform (vtable byte offsets, struct field packing/alignment) are marked "// INFERRED:" for the OVMF validation step to confirm.

Dependency discipline. go-tpm2 must remain free of any UEFI/TamaGo dependency. This package therefore never imports an EFI runtime, never dereferences a protocol pointer, and never uses package unsafe: it takes an INJECTED firmware-call mechanism (a Caller) that the loader implements. The loader owns the protocol pointer and the architecture-specific EFI calling convention; efitcg2 only marshals buffers, interprets results, and satisfies common.Transport. This mirrors how go-tpm2/tis and go-tpm2/crb take an injected common.Regs rather than mapping MMIO themselves.

Conventions: pure Go, CGO_ENABLED=0, no architecture-specific assembly, BSD-3-Clause on every file, 100% statement coverage, and GOWORK=off.

Index

Constants

View Source
const (
	MethodGetCapability                = 0
	MethodGetEventLog                  = 1
	MethodHashLogExtendEvent           = 2
	MethodSubmitCommand                = 3
	MethodGetActivePcrBanks            = 4
	MethodSetActivePcrBanks            = 5
	MethodGetResultOfSetActivePcrBanks = 6
)

Method indices into the EFI_TCG2_PROTOCOL function table, in declaration order. They are exported only as a reference for a loader that implements Caller as a single low-level Call(method, args...) dispatcher rather than the high-level two-method interface; efitcg2 itself never indexes the vtable (it has no protocol pointer). TCG "EFI Protocol Specification", clause "EFI_TCG2_PROTOCOL", the EFI_TCG2_PROTOCOL structure (member order).

INFERRED: that these ordinals map to fixed pointer-width vtable byte offsets (ordinal*sizeof(void*)) in the firmware's protocol structure. The declaration ORDER is fixed by the specification; the byte OFFSETS depend on the EFI ABI (pointer width, no padding between members) and must be confirmed against OVMF. efitcg2 does not rely on the offsets — only the loader's Caller does — but they are documented here for that loader.

View Source
const (
	// ErrInvalidParameter maps EFI_INVALID_PARAMETER.
	ErrInvalidParameter = common.Error("efitcg2: EFI_INVALID_PARAMETER")
	// ErrBufferTooSmall maps EFI_BUFFER_TOO_SMALL. From SubmitCommand it
	// means the response did not fit OutputParameterBlockSize.
	ErrBufferTooSmall = common.Error("efitcg2: EFI_BUFFER_TOO_SMALL")
	// ErrDeviceError maps EFI_DEVICE_ERROR.
	ErrDeviceError = common.Error("efitcg2: EFI_DEVICE_ERROR")
	// ErrNotFound maps EFI_NOT_FOUND.
	ErrNotFound = common.Error("efitcg2: EFI_NOT_FOUND")
	// ErrStatus is returned for any other non-success EFI_STATUS.
	ErrStatus = common.Error("efitcg2: firmware returned a non-success EFI_STATUS")
	// ErrShortResponse is returned when the firmware reports success but the
	// response buffer is smaller than a TPM 2.0 header.
	ErrShortResponse = common.Error("efitcg2: response shorter than TPM header")
	// ErrResponseTooLarge is returned when the response's declared
	// responseSize exceeds the output buffer the firmware was given.
	ErrResponseTooLarge = common.Error("efitcg2: response larger than output buffer")
)

Error sentinels, typed as common.Error so callers may compare with ==.

View Source
const (
	// FlagNone requests the default behaviour: hash dataToHash, extend the
	// PCR, and append the event-log record.
	FlagNone uint64 = 0x0000000000000000
	// FlagPECOFFImage marks dataToHash as a loaded PE/COFF image so the
	// firmware applies the Authenticode-style measurement. TCG "EFI
	// Protocol Specification", "PE_COFF_IMAGE".
	FlagPECOFFImage uint64 = 0x0000000000000001
)

HashLogExtendEvent flags. TCG "EFI Protocol Specification", "EFI_TCG2_PROTOCOL.HashLogExtendEvent()", the Flags parameter (EFI_TCG2_EVENT_LOG_FORMAT / PE_COFF_IMAGE bits).

View Source
const (
	// EventLogFormatTCG_1_2 is EFI_TCG2_EVENT_LOG_FORMAT_TCG_1_2 (0x1): the
	// legacy SHA-1-only TCG 1.2 log (TCG_PCR_EVENT records). Defined for
	// completeness; this stack does not parse it.
	EventLogFormatTCG_1_2 uint32 = 0x00000001
	// EventLogFormatTCG_2 is EFI_TCG2_EVENT_LOG_FORMAT_TCG_2 (0x2): the
	// crypto-agile log (a legacy TCG_PCR_EVENT spec-ID header followed by
	// TCG_PCR_EVENT2 records). This is the format attest.ParseEventLog reads,
	// so it is the format GetEventLog requests.
	EventLogFormatTCG_2 uint32 = 0x00000002
)

EFI_TCG2_EVENT_LOG_FORMAT values, the EventLogFormat argument to EFI_TCG2_PROTOCOL.GetEventLog. TCG "EFI Protocol Specification", "EFI_TCG2_EVENT_LOG_FORMAT" (the EFI_TCG2_EVENT_LOG_FORMAT_TCG_* #defines).

View Source
const (
	// ErrEventLogUnsupported is returned by (*TCG2).GetEventLog when the injected
	// Caller does NOT implement the optional EventLogCaller extension, i.e. the
	// loader did not wire up firmware event-log retrieval. It is distinct from a
	// firmware EFI_STATUS error: the firmware was never asked.
	ErrEventLogUnsupported = common.Error("efitcg2: Caller does not implement EventLogCaller")
	// ErrEventLogTruncated is returned by (*TCG2).GetEventLog ALONGSIDE the log
	// bytes when the firmware set EFI_TCG2_PROTOCOL.GetEventLog's
	// EventLogTruncated out-parameter: the firmware's event-log area overflowed
	// and the returned bytes are incomplete. The bytes are still returned (a
	// truncated crypto-agile log may still parse up to the truncation point) so
	// the caller can decide; replaying a truncated log will not reproduce the
	// firmware PCRs, so attestation MUST treat this as a failure. Callers that
	// only want a complete log check errors.Is(err, ErrEventLogTruncated).
	ErrEventLogTruncated = common.Error("efitcg2: firmware reports the event log was truncated")
)

Event-log error/warning sentinels, typed as common.Error so callers may compare with ==.

View Source
const DefaultOutputSize = 3968

DefaultOutputSize is the OutputParameterBlock size efitcg2 allocates for a SubmitCommand when no explicit ceiling is configured and the Caller does not advertise an EFI_TCG2_BOOT_SERVICE_CAPABILITY.MaxResponseSize (see CapabilityCaller). It is 0x1000-0x80 = 3968: the realistic CRB/TIS ceiling a firmware TPM exposes through SubmitCommand. TCG "EFI Protocol Specification", "EFI_TCG2_PROTOCOL.SubmitCommand()" (the caller sizes the output block).

INFERRED, NOW CONFIRMED ON OVMF: the original 4096 was too LARGE, not too small. OVMF's CRB-backed EFI_TCG2_PROTOCOL advertises MaxResponseSize = 0xF80 = 3968 and rejects any SubmitCommand whose OutputParameterBlockSize exceeds it with EFI_INVALID_PARAMETER — before it ever forwards the command — so a 4096-byte block made every readback (e.g. PCRRead after a HashLogExtendEvent) fail. 3968 is the firmware-proven maximum (an output block <= 3968 succeeds); when the Caller implements CapabilityCaller, Send uses min(requested, MaxResponseSize) instead and this default is only the fallback for Callers that cannot report it.

Variables

View Source
var TCG2ProtocolGUID = GUID{
	Data1: 0x607f766c,
	Data2: 0x7455,
	Data3: 0x42be,
	Data4: [8]byte{0x93, 0x0b, 0xe4, 0xd7, 0x6d, 0xb2, 0x72, 0x0f},
}

TCG2ProtocolGUID is EFI_TCG2_PROTOCOL_GUID, 607f766c-7455-42be-930b-e4d76db2720f. The loader passes this to EFI Boot Services LocateProtocol to obtain the EFI_TCG2_PROTOCOL interface pointer it then wires into a Caller. TCG "EFI Protocol Specification", clause "EFI_TCG2_PROTOCOL", "#define EFI_TCG2_PROTOCOL_GUID".

Functions

This section is empty.

Types

type Caller

type Caller interface {
	// SubmitCommand passes one fully-marshaled TPM 2.0 command buffer to
	// the firmware TPM and receives the response into output, returning the
	// firmware's EFI_STATUS.
	SubmitCommand(inputBlock []byte, output []byte) (status uintptr, err error)
	// HashLogExtendEvent performs a measured-boot extend+log, returning the
	// firmware's EFI_STATUS.
	HashLogExtendEvent(flags uint64, dataToHash []byte, event []byte) (status uintptr, err error)
}

Caller is the INJECTED firmware-call mechanism the loader must implement. It is the entire UEFI-facing surface of efitcg2: the loader, which holds the EFI_TCG2_PROTOCOL pointer and the platform's EFI calling convention (efiCall), performs the actual firmware invocation; efitcg2 hands it already-marshaled buffers and interprets the returned EFI_STATUS.

Contract. Each method invokes the correspondingly named EFI_TCG2_PROTOCOL member with This set to the located protocol pointer, and returns the raw EFI_STATUS as a uintptr (so the platform's native word width carries the high "error" bit unchanged; see statusError). A non-nil err reports a failure to perform the call itself (a marshaling/trap/transport problem on the loader side) and is distinct from a non-success status: when err is nil, status alone decides success. efitcg2 treats (status, err) as (EFI_STATUS, callError) and never inspects firmware memory directly.

  • SubmitCommand(inputBlock, output): calls EFI_TCG2_PROTOCOL.SubmitCommand(This, InputParameterBlockSize, InputParameterBlock, OutputParameterBlockSize, OutputParameterBlock) with InputParameterBlock = inputBlock and OutputParameterBlock = the caller-allocated output buffer (length = OutputParameterBlockSize). The firmware writes the TPM response into output in place. TCG "EFI Protocol Specification", "EFI_TCG2_PROTOCOL.SubmitCommand()".

  • HashLogExtendEvent(flags, dataToHash, event): calls EFI_TCG2_PROTOCOL.HashLogExtendEvent(This, Flags, DataToHash, DataToHashLen, EfiTcg2Event) with DataToHashLen = len(dataToHash) and EfiTcg2Event = the serialized EFI_TCG2_EVENT in event (its leading Size field already states its own length). TCG "EFI Protocol Specification", "EFI_TCG2_PROTOCOL.HashLogExtendEvent()".

The loader is free to implement Caller over a single low-level Call(method int, args ...uintptr) uintptr closure (using the Method* ordinals above) — that is an implementation detail efitcg2 does not see.

type CapabilityCaller added in v0.1.1

type CapabilityCaller interface {
	// GetCapability reports the firmware's
	// EFI_TCG2_BOOT_SERVICE_CAPABILITY.MaxResponseSize (in bytes). A return
	// of (0, nil) means "not reported"; a non-nil err means the GetCapability
	// call itself failed — both cause Send to keep its requested size.
	GetCapability() (maxResponseSize uint32, err error)
}

CapabilityCaller is an OPTIONAL extension a Caller may also implement to report the firmware's EFI_TCG2_BOOT_SERVICE_CAPABILITY.MaxResponseSize. It is queried via EFI_TCG2_PROTOCOL.GetCapability (vtable index 0).

Why it matters. SubmitCommand's OutputParameterBlockSize must not exceed the firmware's MaxResponseSize: a CRB/TIS-backed EFI_TCG2_PROTOCOL (e.g. OVMF) rejects an over-large output block with EFI_INVALID_PARAMETER before forwarding the command, so the whole readback fails. efitcg2 type-asserts a Caller to CapabilityCaller; when present and it returns a non-zero MaxResponseSize with a nil error, Send clamps its output block to min(requested, MaxResponseSize). A zero MaxResponseSize, an error, or a Caller that does not implement this interface leaves the requested size unchanged (the DefaultOutputSize fallback already fits a CRB ceiling).

TCG "EFI Protocol Specification", "EFI_TCG2_PROTOCOL.GetCapability()" and "EFI_TCG2_BOOT_SERVICE_CAPABILITY" (its MaxResponseSize member).

type EventLogCaller added in v0.2.0

type EventLogCaller interface {
	// GetEventLog fetches the firmware event log in the requested
	// EFI_TCG2_EVENT_LOG_FORMAT, returning the assembled bytes, the firmware's
	// truncation flag, and any call/read error.
	GetEventLog(format uint32) (log []byte, truncated bool, err error)
}

EventLogCaller is an OPTIONAL extension a Caller may also implement to fetch the firmware-maintained TCG event log. It is queried via EFI_TCG2_PROTOCOL.GetEventLog (vtable index 1, see MethodGetEventLog).

Why it lives in the Caller. GetEventLog returns firmware-memory ADDRESSES (EventLogLocation/EventLogLastEntry), not bytes; assembling the log means reading [location, lastEntry + sizeof(last entry)) out of firmware memory, which needs the loader's identity-mapped access and is outside efitcg2's UEFI/TamaGo-free remit. The loader therefore performs the whole firmware operation — call GetEventLog, take the out-params, parse the last TCG_PCR_EVENT2 header to size the final entry, read the exact byte range, and return the assembled bytes plus the firmware's EventLogTruncated flag.

Contract. GetEventLog(format) requests the log in the given EFI_TCG2_EVENT_LOG_FORMAT and returns:

  • log: the assembled event-log bytes in that format (a complete crypto-agile log when format == EventLogFormatTCG_2: a legacy TCG_PCR_EVENT spec-ID header followed by TCG_PCR_EVENT2 records). These bytes are returned to efitcg2's caller unchanged and are intended to be passed verbatim to attest.ParseEventLog. An empty log (no measurements yet) is a valid (possibly nil/header-only) byte slice with a nil err.
  • truncated: the firmware's EventLogTruncated out-parameter (the event-log memory area overflowed). efitcg2 surfaces this as ErrEventLogTruncated.
  • err: a failure to perform the firmware call or read its memory (a marshaling/trap/transport problem on the loader side, or a non-success EFI_STATUS the loader chose to map). A non-nil err means the log bytes are not usable.

TCG "EFI Protocol Specification", "EFI_TCG2_PROTOCOL.GetEventLog()" and "EFI_TCG2_EVENT_LOG_FORMAT".

type GUID

type GUID struct {
	Data1 uint32
	Data2 uint16
	Data3 uint16
	Data4 [8]byte
}

GUID is a UEFI GUID: an EFI_GUID. UEFI represents it as a 32-bit Data1, two 16-bit Data2/Data3, and an 8-byte Data4, stored in memory MIXED- ENDIAN (Data1..Data3 little-endian, Data4 as-is). This Go value is the canonical field decomposition; the loader is responsible for laying it out in guest memory in the EFI_GUID byte order when it calls LocateProtocol. UEFI specification, "EFI_GUID" / appendix "GUID and Time Formats".

type TCG2

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

TCG2 is a TPM 2.0 transport over EFI_TCG2_PROTOCOL. It holds only the injected Caller and the output-buffer size; it satisfies common.Transport.

func New

func New(c Caller) *TCG2

New binds a TCG2 transport to the loader-provided Caller, allocating DefaultOutputSize bytes for each SubmitCommand response buffer.

func NewWithOutputSize

func NewWithOutputSize(c Caller, outputSize int) *TCG2

NewWithOutputSize is New with an explicit OutputParameterBlock size (the ceiling on a single response). A non-positive size falls back to DefaultOutputSize.

func (*TCG2) GetEventLog added in v0.2.0

func (t *TCG2) GetEventLog() ([]byte, error)

GetEventLog fetches the FIRMWARE-maintained crypto-agile TCG event log (EFI_TCG2_EVENT_LOG_FORMAT_TCG_2) and returns its bytes, ready to be parsed by github.com/go-tpm2/attest's ParseEventLog and replayed with ReplayPCRs.

It requires the injected Caller to implement the optional EventLogCaller extension (the loader-side firmware-memory read). When the Caller does NOT implement it, GetEventLog returns (nil, ErrEventLogUnsupported) — the firmware is never asked. When the firmware reports the log was truncated, GetEventLog returns the (incomplete) bytes ALONGSIDE ErrEventLogTruncated, so a caller can distinguish "no log" from "partial log": a truncated log will not replay to the firmware PCRs and MUST be rejected for attestation, but the bytes are surfaced rather than dropped. Any Caller call/read error is returned with nil bytes.

The returned format is always EventLogFormatTCG_2 — the crypto-agile log attest parses; the legacy EventLogFormatTCG_1_2 (SHA-1 only) is not requested.

TCG "EFI Protocol Specification", "EFI_TCG2_PROTOCOL.GetEventLog()"; TCG "PC Client Platform Firmware Profile", "Event Logging" (the crypto-agile log layout attest replays).

func (*TCG2) MeasureToPCR

func (t *TCG2) MeasureToPCR(pcr uint32, eventType uint32, data []byte, eventDesc []byte) error

MeasureToPCR performs a measured-boot extend-and-log: it hashes data into the firmware's active PCR banks for PCR pcr, appends a TCG event-log entry of type eventType carrying eventDesc, and returns any firmware error.

Unlike a raw TPM2_PCR_Extend (which only mutates the PCR), this drives EFI_TCG2_PROTOCOL.HashLogExtendEvent, so the event is also recorded in the firmware's TCG event log for later attestation — the correct measured-boot primitive while in Boot Services. The flags select default vs PE/COFF hashing (see FlagNone / FlagPECOFFImage). TCG "EFI Protocol Specification", "EFI_TCG2_PROTOCOL.HashLogExtendEvent()".

func (*TCG2) MeasureToPCRWithFlags

func (t *TCG2) MeasureToPCRWithFlags(flags uint64, pcr uint32, eventType uint32, data []byte, eventDesc []byte) error

MeasureToPCRWithFlags is MeasureToPCR with an explicit HashLogExtendEvent Flags value.

func (*TCG2) Send

func (t *TCG2) Send(cmd []byte) (rsp []byte, err error)

Send transmits one fully-marshaled TPM 2.0 command buffer through EFI_TCG2_PROTOCOL.SubmitCommand and returns the full response buffer (header + params), trimmed to the TPM response's declared responseSize. It satisfies common.Transport.

cmd becomes the InputParameterBlock; a freshly allocated OutputParameter- Block the firmware writes into is sized to t.outputSize, but never larger than the firmware's EFI_TCG2_BOOT_SERVICE_CAPABILITY.MaxResponseSize when the Caller advertises one via the optional CapabilityCaller extension: an over-large output block is rejected with EFI_INVALID_PARAMETER by CRB/TIS- backed firmware (e.g. OVMF) before the command is forwarded. So the block length is min(t.outputSize, MaxResponseSize) when MaxResponseSize is non-zero, else t.outputSize.

On EFI_SUCCESS, Send parses the 10-byte TPM 2.0 response header (common.GetU32 of responseSize at offset 2), bounds-checks it against the header length and the output buffer, and returns the response sliced to that size. TCG "EFI Protocol Specification", "EFI_TCG2_PROTOCOL.SubmitCommand()" and "EFI_TCG2_PROTOCOL.GetCapability()"; TCG "TPM 2.0 Part 1: Architecture", response header layout.

Jump to

Keyboard shortcuts

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