secboot

package
v0.0.0-...-32f6457 Latest Latest
Warning

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

Go to latest
Published: Jan 20, 2026 License: GPL-3.0 Imports: 42 Imported by: 69

Documentation

Overview

* Copyright (C) 2025 Canonical Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 3 as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. *

Index

Constants

View Source
const (
	// The range 0x01880005-0x0188000F
	//
	// TODO:FDEM: we should apply for a subrange from UAPI group once
	// they got a range assigned by TCG.  See
	// https://github.com/uapi-group/specifications/pull/118
	// For now we use a sub range on the unassigned owner handles
	PCRPolicyCounterHandleStart = uint32(0x01880005)
	PCRPolicyCounterHandleRange = uint32(0x01880010 - 0x01880005)

	// These handles are legacy, do not use them in new code.
	//
	// Handles are in the block reserved for TPM owner objects (0x01800000 - 0x01bfffff).
	//
	// Handles are rotated during factory reset, depending on the PCR handle
	// thet was used when sealing key objects during installation (or a
	// previous factory reset).
	RunObjectPCRPolicyCounterHandle         = uint32(0x01880001)
	FallbackObjectPCRPolicyCounterHandle    = uint32(0x01880002)
	AltRunObjectPCRPolicyCounterHandle      = uint32(0x01880003)
	AltFallbackObjectPCRPolicyCounterHandle = uint32(0x01880004)
)
View Source
const (
	PlatformTpm2       = "tpm2"
	PlatformTpm2Legacy = "tpm2-legacy"
	PlatformPlainkey   = "plainkey"
	PlatformFdeHookV2  = "fde-hook-v2"
	PlatformFdeHooksV3 = "fde-hooks-v3"
)

Variables

View Source
var CreateBootstrappedContainer = createBootstrappedContainerMockImpl
View Source
var ErrKernelKeyNotFound = errors.New("kernel key not found")
View Source
var ErrNoKeyProtector = errors.New("cannot find supported FDE key protector")
View Source
var WithSecbootSupport = false

WithSecbootSupport is true if this package was built with githbu.com/snapcore/secboot.

Functions

func ActivateVolumeWithKey

func ActivateVolumeWithKey(volumeName, sourceDevicePath string, key []byte, options *ActivateVolumeOptions) error

ActivateVolumeWithKey is a wrapper for secboot.ActivateVolumeWithKey

func AddBootstrapKeyOnExistingDisk

func AddBootstrapKeyOnExistingDisk(node string, newKey keys.EncryptionKey) error

AddBootstrapKeyOnExistingDisk will add a new bootstrap key to on an existing encrypted disk. The disk is expected to be unlocked and they key is available on the keyring. The bootstrap key is temporary and is expected to be used with a BootstrappedContainer, and removed by calling RemoveBootstrapKey.

func AddContainerRecoveryKey

func AddContainerRecoveryKey(devicePath string, slotName string, rkey keys.RecoveryKey) error

AddContainerRecoveryKey adds a new recovery key to specified device.

Note: The unlock key is implicitly obtained from the kernel keyring.

func AddContainerTPMProtectedKey

func AddContainerTPMProtectedKey(devicePath, slotName string, params *ProtectKeyParams) (err error)

AddContainerRecoveryKey adds a new TPM protected key to specified device.

Note: The unlock and primary keys are implicitly obtained from the kernel keyring so this will not work if the disk was unlocked with a recovery key during boot.

func AddRecoveryKey

func AddRecoveryKey(key keys.EncryptionKey, rkey keys.RecoveryKey, node string) error

AddRecoveryKey adds a fallback recovery key rkey to the existing encrypted volume created with FormatEncryptedDevice on the block device given by node. The existing key to the encrypted volume is provided in the key argument.

func CheckRecoveryKey

func CheckRecoveryKey(devicePath string, rkey keys.RecoveryKey) error

CheckRecoveryKey tests that the specified recovery key unlocks the device at the specified path.

func CheckTPMKeySealingSupported

func CheckTPMKeySealingSupported(mode TPMProvisionMode) error

func DeactivateVolume

func DeactivateVolume(volumeName string) error

DeactivateVolume is a wrapper for secboot.DeactivateVolume

func DeleteContainerKey

func DeleteContainerKey(devicePath, slotName string) error

DeleteContainerKey deletes a key slot on a LUKS2 container.

func DeleteKeys

func DeleteKeys(node string, matches map[string]bool) error

DeleteKeys delete key slots on a LUKS2 container. Slots that do not exist are ignored.

XXX: s/DeleteKey/DeleteContainerKey

func DeleteOldKeys

func DeleteOldKeys(devicePath string) error

DeleteOldKeys removes key slots from an old installation that had names created by TemporaryNameOldKeys.

func EncryptedPartitionName

func EncryptedPartitionName(name string) string

EncryptedPartitionName returns the name/label used by an encrypted partition corresponding to a given name.

func EnsureRecoveryKey

func EnsureRecoveryKey(keyFile string, rkeyDevs []RecoveryKeyDevice) (keys.RecoveryKey, error)

EnsureRecoveryKey makes sure the encrypted block devices have a recovery key. It takes the path where to store the key and encrypted devices to operate on.

func FDEOpteeTAPresent

func FDEOpteeTAPresent() bool

FDEOpteeTAPresent returns true if we detect that the expected OPTEE TA that enables FDE is present.

func FindFreeHandle

func FindFreeHandle() (uint32, error)

FindFreeHandle finds and unused handle on the TPM. The handle will be arbitrary in range 0x01880005-0x0188000F.

func FormatEncryptedDevice

func FormatEncryptedDevice(key []byte, encType device.EncryptionType, label, node string) error

FormatEncryptedDevice initializes an encrypted volume on the block device given by node, setting the specified label. The key used to unlock the volume is provided using the key argument.

func GetPCRHandle

func GetPCRHandle(node, keySlot, keyFile string, hintExpectFDEHook bool) (uint32, error)

GetPCRHandle returns the handle used by a key. The key will be searched on the token of the keySlot from the node. If that keySlot has no KeyData, then the key will be loaded at path keyFile.

func GetPrimaryKey

func GetPrimaryKey(devices []string, fallbackKeyFiles []string) ([]byte, error)

GetPrimaryKey finds the primary from the keyring based on the path of encrypted devices. If it does not find any primary in the keyring, it then tries to read the key from a fallback key file.

func GetPrimaryKeyDigest

func GetPrimaryKeyDigest(devicePath string, alg crypto.Hash) (salt []byte, digest []byte, err error)

GetPrimaryKeyDigest retrieve the primary key for a disk from the keyring and returns its digest. If the path given does not match the keyring, then it will look for symlink in /dev/disk/by-partuuid for that device.

func HijackAndRunArgon2OutOfProcessHandlerOnArg

func HijackAndRunArgon2OutOfProcessHandlerOnArg(args []string)

HijackAndRunArgon2OutOfProcessHandlerOnArg is supposed to be called from the main() of binaries involved with sealing/unsealing of keys (i.e. snapd and snap-bootstrap).

This switches the binary to a special argon2 mode when the matching args are detected where it hijacks the process and acts as an argon2 out-of-process helper command and exits when its work is done, otherwise (in normal mode) it sets the default argon2 kdf implementation to be self-invoking into the special argon2 mode of the calling binary.

For more context, check docs for sb.WaitForAndRunArgon2OutOfProcessRequest and sb.NewOutOfProcessArgon2KDF for details on how the flow works in secboot.

func ListContainerRecoveryKeyNames

func ListContainerRecoveryKeyNames(devicePath string) ([]string, error)

ListContainerRecoveryKeyNames lists the names of key slots on the specified device configured as recovery slots.

Note: This only supports LUKS2 containers.

func ListContainerUnlockKeyNames

func ListContainerUnlockKeyNames(devicePath string) ([]string, error)

ListContainerUnlockKeyNames lists the names of key slots on the specified device configured as normal unlock slots (the keys associated with these should be protected by the platform's secure device).

Note: This only supports LUKS2 containers.

func LockSealedKeys

func LockSealedKeys() error

LockSealedKeys manually locks access to the sealed keys. Meant to be called in place of passing lockKeysOnFinish as true to UnlockVolumeUsingSealedKeyIfEncrypted for cases where we don't know if a given call is the last one to unlock a volume like in degraded recover mode.

func MarkSuccessful

func MarkSuccessful() error

MarkSuccessful marks the secure boot parts of the boot as successful.

This means that the dictionary attack (DA) lockout counter is reset.

func MeasureSnapModelWhenPossible

func MeasureSnapModelWhenPossible(findModel func() (*asserts.Model, error)) error

MeasureSnapModelWhenPossible measures the snap model only if the TPM device is available. If there's no TPM device success is returned.

func MeasureSnapSystemEpochWhenPossible

func MeasureSnapSystemEpochWhenPossible() error

MeasureSnapSystemEpochWhenPossible measures the snap system epoch only if the TPM device is available. If there's no TPM device success is returned.

func MockCreateBootstrappedContainer

func MockCreateBootstrappedContainer(f func(key DiskUnlockKey, devicePath string) BootstrappedContainer) func()

func NewSystemdAuthRequestor

func NewSystemdAuthRequestor() sb.AuthRequestor

NewSystemdAuthRequestor creates an AuthRequestor which calls systemd-ask-password with credential parameter.

func PreinstallCheck

func PreinstallCheck(ctx context.Context, bootImagePaths []string) (*PreinstallCheckContext, []PreinstallErrorDetails, error)

PreinstallCheck runs preinstall checks using default check configuration and TCG-compliant PCR profile generation options to evaluate whether the host environment is an EFI system suitable for TPM-based Full Disk Encryption. The caller must supply the current boot images in boot order via bootImagePaths. On success, it returns the preinstall check context required for follow-up preinstall checks with actions, and a list with details on all errors identified by secboot (or nil if no errors were found). Any warnings contained in the secboot result are logged. On failure, it returns the error encountered while interpreting the secboot error.

To support testing, when the system is running in a Virtual Machine, the check configuration is modified to permit this to avoid an error.

func ProvisionForCVM

func ProvisionForCVM(initramfsUbuntuSeedDir string) error

ProvisionForCVM provisions the default TPM using a custom SRK template that is created by the encrypt tool prior to first boot of Azure CVM instances. It takes UbuntuSeedDir (ESP) and expects "tpm2-srk.tmpl" there which is deleted after successful provision.

Key differences with ProvisionTPM() - lack of TPM or if TPM is disabled is ignored. - it is fatal if TPM Provisioning requires a Lockout file - Custom SRK file is required in InitramfsUbuntuSeedDir

func ProvisionTPM

func ProvisionTPM(mode TPMProvisionMode, lockoutAuthFile string) error

ProvisionTPM provisions the default TPM and saves the lockout authorization key to the specified file.

func RemoveOldCounterHandles

func RemoveOldCounterHandles(device string, possibleOldKeys map[string]bool, possibleKeyFiles []string, hintExpectFDEHook bool) error

RemoveOldCounterHandles releases TPM2 handles used by some keys. The keys for which handles are released are:

  • in the keyslots of the given device, with names matching possibleOldKeys.
  • in key files at paths given by possibleKeyFiles.

All TPM2 handles found in any key found will be removed. If keyslots or key files are not found, they are just ignored. hintExpectFDEHook helps reading old key object files. If not TPM2 key is found, nothing happens.

func RemoveRecoveryKeys

func RemoveRecoveryKeys(rkeyDevToKey map[RecoveryKeyDevice]string) error

RemoveRecoveryKeys removes any recovery key from all encrypted block devices. It takes a map from the recovery key device to where their recovery key is stored, mount points might share the latter.

func RenameContainerKey

func RenameContainerKey(devicePath, oldName, newName string) error

RenameContainerKey renames a key slot on LUKS2 container. An error is returned if cryptsetup does not support --token-replace option.

func RenameKeysForFactoryReset

func RenameKeysForFactoryReset(node string, renames map[string]string) error

Rename key slots on LUKS2 container. If the key slot does not exist, it is ignored. If cryptsetup does not support renaming, then the key slots are instead removed. WARNING: this function is not always atomic. If cryptsetup is too old, it will try to copy and delete keys instead. Please avoid using this function in new code.

func SealKeys

func SealKeys(keys []SealKeyRequest, params *SealKeysParams) ([]byte, error)

SealKeys seals the encryption keys according to the specified parameters. The TPM must have already been provisioned. If sealed key already exists at the PCR handle, SealKeys will fail and return an error.

func SealKeysWithProtector

func SealKeysWithProtector(kpf KeyProtectorFactory, keys []SealKeyRequest, params *SealKeysWithFDESetupHookParams) error

func StageEncryptionKeyChange

func StageEncryptionKeyChange(node string, key keys.EncryptionKey) error

StageEncryptionKeyChange stages a new encryption key for a given encrypted device. The new key is added into a temporary slot. To complete the encryption key change process, a call to TransitionEncryptionKeyChange is needed.

func TemporaryNameOldKeys

func TemporaryNameOldKeys(devicePath string) error

TemporaryNameOldKeys takes a disk using legacy keyslots 0, 1, 2 and adds names to those keyslots. This is needed to convert the save disk during a factory reset. This is a no-operation if all keyslots are already named.

func TransitionEncryptionKeyChange

func TransitionEncryptionKeyChange(mountpoint string, key keys.EncryptionKey) error

TransitionEncryptionKeyChange transitions the encryption key on an encrypted device corresponding to the given mount point. The change is authorized using the new key, thus a prior call to StageEncryptionKeyChange must be done.

func VerifyPrimaryKeyDigest

func VerifyPrimaryKeyDigest(devicePath string, alg crypto.Hash, salt []byte, digest []byte) (bool, error)

VerifyPrimaryKeyDigest retrieve the primary key for a disk from the keyring and verifies its digest. If the path given does not match the keyring, then it will look for symlink in /dev/disk/by-partuuid for that device.

Types

type ActivateContext

type ActivateContext interface {
	ActivateContainer(ctx context.Context, container sb.StorageContainer, opts ...sb.ActivateOption) error
	State() *ActivateState
}

func NewActivateContext

func NewActivateContext(ctx context.Context) (ActivateContext, error)

type ActivateState

type ActivateState = sb.ActivateState

type ActivateVolumeOptions

type ActivateVolumeOptions sb.ActivateVolumeOptions

type BootstrappedContainer

type BootstrappedContainer interface {
	// AddKey adds a key "newKey" to "slotName".
	AddKey(slotName string, newKey []byte) error
	// AddRecoveryKey adds a recovery key "rkey" to "slotName".
	AddRecoveryKey(slotName string, rkey keys.RecoveryKey) error
	// GetTokenWriter returns a keydata writer that writes to the token.
	GetTokenWriter(slotName string) (KeyDataWriter, error)
	// RemoveBootstrapKey removes the bootstrap key.
	RemoveBootstrapKey() error
	// RegisterKeyAsUsed registers an unlock key and its primary key in the kernel keyring.
	RegisterKeyAsUsed(primaryKey []byte, unlockKey []byte)
}

BootstrappedContainer is an abstraction for an encrypted container along with a key that is able to enroll other keys. This key is meant to be an initial key that is removed after all required keys are enrolled, by calling RemoveBootstrapKey.

type DiskUnlockKey

type DiskUnlockKey sb.DiskUnlockKey

type HashAlg

type HashAlg = sb.HashAlg

type KeyData

type KeyData interface {
	PlatformName() string
	Roles() []string
	AuthMode() device.AuthMode
	// ChangePassphrase changes passphrase given old passphrase.
	// AuthMode must be device.AuthModePassphrase.
	ChangePassphrase(oldPassphrase, newPassphrase string) error
	// ChangePIN changes pin given old pin.
	// AuthMode must be device.AuthModePIN.
	ChangePIN(oldPIN, newPIN string) error
	// WriteTokenAtomic saves this key data to the specified LUKS2 token.
	WriteTokenAtomic(devicePath, slotName string) error
}

KeyData represents a disk unlock key protected by a platform's secure device.

func ReadContainerKeyData

func ReadContainerKeyData(devicePath, slotName string) (KeyData, error)

ReadContainerKeyData reads key slot key data for the specified device and slot name.

Note: This only supports key datas stored in LUKS2 tokens.

type KeyDataLocation

type KeyDataLocation struct {
	// KeyFile is the path to the file that contains either the key data or sealed key object.
	KeyFile string
	// DevicePath is the LUKS2 device which contains a token with they key data
	DevicePath string
	// SlotName is the name of the token that contains the key data
	SlotName string
}

KeyDataLocation represents the possible places where key data might be saved.

This is used for resealing keys in key data. The resealing will be responsible of finding which one is in use. The basic strategy is if a key data is found in the token, then this will be used and the key file will be ignored.

type KeyDataWriter

type KeyDataWriter interface {
	io.Writer
	Commit() error
}

KeyDataWriter is an interface used by KeyData to write the data to persistent storage in an atomic way. The interface is compatible with identically named interface from github.com/canonical/secboot.

type KeyProtector

type KeyProtector sb_hooks.KeyProtector

KeyProtector is an abstraction for an externally supplied key setup hook.

type KeyProtectorFactory

type KeyProtectorFactory interface {
	// ForKeyName returns a new [KeyProtector].
	ForKeyName(name string) KeyProtector
}

KeyProtectorFactory enables creating a KeyProtector implementation.

func FDESetupHookKeyProtectorFactory

func FDESetupHookKeyProtectorFactory(runHook fde.RunSetupHookFunc) KeyProtectorFactory

FDESetupHookKeyProtectorFactory returns a KeyProtectorFactory that will use the kernel's fde-setup hook to protect the key, invoked via the given runHook.

func OPTEEKeyProtectorFactory

func OPTEEKeyProtectorFactory() KeyProtectorFactory

OPTEEKeyProtectorFactory returns a KeyProtectorFactory that will use the system's OPTEE trusted application to protect the key.

type LegacyKeyFile

type LegacyKeyFile struct {
	// Name is the value that will be reported as used keyslot
	Name string
	// Path is the absolute path to the key file
	Path string
}

LegacyKeyFile represents a legacy key file

type LoadChain

type LoadChain struct {
	*bootloader.BootFile
	// Next is a list of alternative chains that can be loaded
	// following the boot file.
	Next []*LoadChain
}

func NewLoadChain

func NewLoadChain(bf bootloader.BootFile, next ...*LoadChain) *LoadChain

NewLoadChain returns a LoadChain corresponding to loading the given BootFile before any of the given next chains.

type MaybeSealedKeyData

type MaybeSealedKeyData interface {
	// Unwrap returns the sealed key data contained in this wrapper
	Unwrap() *sb_tpm2.SealedKeyData
}

MaybeSealedKeyData interface wraps a sb_tpm2.SealedKeyData This is mainly used to be able to mock sb_tpm2.SealedKeyData

type MockBootstrappedContainer

type MockBootstrappedContainer struct {
	BootstrapKeyRemoved bool
	Slots               map[string][]byte
	Tokens              map[string][]byte
}

func CreateMockBootstrappedContainer

func CreateMockBootstrappedContainer() *MockBootstrappedContainer

func (*MockBootstrappedContainer) AddKey

func (m *MockBootstrappedContainer) AddKey(slotName string, newKey []byte) error

func (*MockBootstrappedContainer) AddRecoveryKey

func (m *MockBootstrappedContainer) AddRecoveryKey(slotName string, rkey keys.RecoveryKey) error

func (*MockBootstrappedContainer) GetTokenWriter

func (m *MockBootstrappedContainer) GetTokenWriter(slotName string) (KeyDataWriter, error)

func (*MockBootstrappedContainer) RegisterKeyAsUsed

func (l *MockBootstrappedContainer) RegisterKeyAsUsed(primaryKey []byte, unlockKey []byte)

func (*MockBootstrappedContainer) RemoveBootstrapKey

func (l *MockBootstrappedContainer) RemoveBootstrapKey() error

type ModelForSealing

type ModelForSealing interface {
	Series() string
	BrandID() string
	Model() string
	Classic() bool
	Grade() asserts.ModelGrade
	SignKeyID() string
}

ModelForSealing provides information about the model for use in the context of (re)sealing the encryption keys.

type PreinstallAction

type PreinstallAction struct {
	Action string                     `json:"action"`
	Args   map[string]json.RawMessage `json:"args,omitempty"`
}

PreinstallAction describes an action with optional arguments that may be requested to resolve a preinstall check error.

type PreinstallCheckContext

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

PreinstallCheckContext wraps RunChecksContext to control access and avoid exposing the secboot dependency to external packages.

func (*PreinstallCheckContext) CheckResult

func (cc *PreinstallCheckContext) CheckResult() (*PreinstallCheckResult, error)

CheckResult retrieves the preinstall check result from the preinstall check context. On success, it returns the preinstall check result required post install for optimum PCR configuration and resealing. On failure, it returns the error encountered while retrieving the result.

func (*PreinstallCheckContext) PreinstallCheckAction

func (cc *PreinstallCheckContext) PreinstallCheckAction(ctx context.Context, action *PreinstallAction) ([]PreinstallErrorDetails, error)

PreinstallCheckAction runs a follow-up preinstall check using the specified action to evaluate whether a previously reported issue can be resolved. It reuses the check configuration and boot image state from the preinstall check context. On success, it returns a list with details on all remaining errors identified by secboot or nil if no errors were found. Any warnings contained in the secboot result are logged. On failure, it returns the error encountered while interpreting the secboot error.

func (*PreinstallCheckContext) SaveCheckResult

func (cc *PreinstallCheckContext) SaveCheckResult(filename string) error

SaveCheckResult writes the serialized preinstall check result in the location specified by the filename.

type PreinstallCheckResult

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

PreinstallCheckResult contains information required during and post install for optimum PCR configuration and resealing. Contents are opaque outside of secboot to ensure that only secboot interprets them.

func LoadCheckResult

func LoadCheckResult(filename string) (*PreinstallCheckResult, error)

LoadCheckResult reads and returns the preinstall check result.

func (*PreinstallCheckResult) MarshalJSON

func (cr *PreinstallCheckResult) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface for PreinstallCheckResult.

func (*PreinstallCheckResult) UnmarshalJSON

func (cr *PreinstallCheckResult) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json.Unmarshaler interface for PreinstallCheckResult.

type PreinstallCheckResultJSON

type PreinstallCheckResultJSON struct {
	Result         *sb_preinstall.CheckResult           `json:"result"`
	PCRProfileOpts sb_preinstall.PCRProfileOptionsFlags `json:"pcr-profile-opts"`
}

PreinstallCheckResultJSON is an auxiliary type for JSON marshalling of PreinstallCheckResult. It is for internal use and testing only.

type PreinstallErrorDetails

type PreinstallErrorDetails struct {
	Kind    string                     `json:"kind"`
	Message string                     `json:"message"`
	Args    map[string]json.RawMessage `json:"args,omitempty"`
	Actions []string                   `json:"actions,omitempty"`
}

PreinstallErrorDetails describes an individual error detected during a preinstall check. It includes the error kind, a human-readable message, and optional structured arguments and suggested recovery actions.

type ProtectKeyParams

type ProtectKeyParams struct {
	// The serialized PCR profile
	PCRProfile SerializedPCRProfile
	// The handle at which to create a NV index for dynamic authorization policy revocation support
	PCRPolicyCounterHandle uint32
	// The key role (run, run+recover, recover)
	KeyRole string
	// Optional volume authentication options
	VolumesAuth *device.VolumesAuthOptions
}

type RecoveryKeyDevice

type RecoveryKeyDevice struct {
	// Mountpoint of the device
	Mountpoint string
	// AuthorizingKeyFile is the path to the key to authorize the
	// operation, if empty, then it is assumed that the authorization key is
	// present in the user session keyring
	AuthorizingKeyFile string
}

type ResealKeyParams

type ResealKeyParams struct {
	// PrimaryKeyDevices is the list of all devices that might
	// have been unlocked and provides a primary key.
	PrimaryKeyDevices []string
	// FallbackPrimaryKeyFiles is the list of files that might contain
	// the primary key.
	FallbackPrimaryKeyFiles []string
	// VerifyPrimaryKey is called if the primary key was read
	VerifyPrimaryKey func([]byte)
	// The allowed boot modes (run, recover, factory-reset)
	BootModes []string
	// The allowed models
	Models []ModelForSealing
	// Function that returns TPM policy profile. It is only called when resealing TPM keys.
	GetTpmPCRProfile func() ([]byte, error)
	// Whether a incremented value of the counter is allowed
	// (before a revocation)
	NewPCRPolicyVersion bool
	// Whether old ambiguous key formats interpreted as FDE hook keys.
	HintExpectFDEHook bool
}

type SealKeyModelParams

type SealKeyModelParams struct {
	// The snap model
	Model ModelForSealing
	// The set of EFI binary load chains for the current device
	// configuration
	EFILoadChains []*LoadChain
	// The kernel command line
	KernelCmdlines []string
	// TODO:FDEM: move this somewhere else?
	// The content of an update to EFI DBX
	EFISignatureDbxUpdate []byte
}

TODO:FDEM: rename and drop Model from the name?

type SealKeyRequest

type SealKeyRequest struct {
	// The installation key to enroll a new key slot
	BootstrappedContainer BootstrappedContainer
	// The key name; identical keys should have identical names
	KeyName string
	// The name of the slot where they key will be saved.
	SlotName string
	// The file to store the key data. If empty, the key data will
	// be saved to the token.
	KeyFile string
	// The boot modes allowed (i.e. snapd_recovery_mode kernel parameter)
	BootModes []string
}

type SealKeysParams

type SealKeysParams struct {
	// The parameters we're sealing the key to
	ModelParams []*SealKeyModelParams
	// The primary key to use, nil if needs to be generated
	PrimaryKey []byte
	// The handle at which to create a NV index for dynamic authorization policy revocation support
	PCRPolicyCounterHandle uint32
	// The path to the authorization policy update key file (only relevant for TPM,
	// if empty the key will not be saved)
	TPMPolicyAuthKeyFile string
	// Optional volume authentication options
	VolumesAuth *device.VolumesAuthOptions
	// Optional preinstall check result for optimum PCR configuration
	CheckResult *PreinstallCheckResult
	// The key role (run, run+recover, recover)
	KeyRole string
	// Whether to allow disabled DMA protection
	AllowInsufficientDmaProtection bool
}

type SealKeysWithFDESetupHookParams

type SealKeysWithFDESetupHookParams struct {
	// Initial model to bind sealed keys to.
	Model ModelForSealing
	// The path to the aux key file (if empty the key will not be
	// saved)
	AuxKeyFile string
	// The primary key to use, nil if needs to be generated
	PrimaryKey []byte
}

type SerializedPCRProfile

type SerializedPCRProfile []byte

SerializedPCRProfile wraps a serialized PCR profile which is treated as an opaque binary blob outside of secboot package.

func BuildPCRProtectionProfile

func BuildPCRProtectionProfile(modelParams []*SealKeyModelParams, checkResult *PreinstallCheckResult, allowInsufficientDmaProtection bool) (SerializedPCRProfile, error)

BuildPCRProtectionProfile builds and serializes a PCR profile from a list of SealKeyModelParams.

If checkResult is non-nil, it provides the PCR configuration recommended by the pre-install check. In this mode, allowInsufficientDmaProtection is ignored, because all relevant information is carried by checkResult.

If checkResult is nil, the function falls back to the legacy profile-generation path, which relies on static assumptions about the system’s boot configuration. In this legacy mode, allowInsufficientDmaProtection determines whether systems lacking sufficient DMA protection are still permitted.

type TPMProvisionMode

type TPMProvisionMode int
const (
	TPMProvisionNone TPMProvisionMode = iota
	// TPMProvisionFull indicates a full provisioning of the TPM
	TPMProvisionFull
	// TPMPartialReprovision indicates a partial reprovisioning of the TPM
	// which was previously already provisioned by secboot. Existing lockout
	// authorization data from TPMLockoutAuthFile will be used to authorize
	// provisioning and will get overwritten in the process.
	TPMPartialReprovision
	// TPMProvisionFullWithoutLockout indicates full provisioning
	// without using lockout authorization data, as currently used
	// by Azure CVM
	TPMProvisionFullWithoutLockout
)

type UnlockMethod

type UnlockMethod int

UnlockMethod is the method that was used to unlock a volume.

const (
	// NotUnlocked indicates that the device was either not unlocked or is not
	// an encrypted device.
	NotUnlocked UnlockMethod = iota
	// UnlockedWithSealedKey indicates that the device was unlocked with the
	// provided sealed key object.
	UnlockedWithSealedKey
	// UnlockedWithRecoveryKey indicates that the device was unlocked by the
	// user providing the recovery key at the prompt.
	UnlockedWithRecoveryKey
	// UnlockedWithKey indicates that the device was unlocked with the provided
	// key, which is not sealed.
	UnlockedWithKey
	// UnlockStatusUnknown indicates that the unlock status of the device is not clear.
	UnlockStatusUnknown
)

type UnlockResult

type UnlockResult struct {
	// FsDevice is the device with filesystem ready to mount.
	// It is the activated device if encrypted or just
	// the underlying device (same as PartDevice) if non-encrypted.
	// FsDevice can be empty when none was found.
	FsDevice string
	// PartDevice is the underlying partition device.
	// PartDevice can be empty when no device was found.
	PartDevice string
	// IsEncrypted indicates that PartDevice is encrypted.
	IsEncrypted bool
	// UnlockMethod is the method used to unlock the device. Valid values are
	// - NotUnlocked
	// - UnlockedWithRecoveryKey
	// - UnlockedWithSealedKey
	// - UnlockedWithKey
	UnlockMethod UnlockMethod
	// Keyslot is the name of the keyslot used or the name of the
	// associated keyfile used.
	Keyslot string
}

UnlockResult is the result of trying to unlock a volume.

func UnlockEncryptedVolumeUsingProtectorKey

func UnlockEncryptedVolumeUsingProtectorKey(activation ActivateContext, disk disks.Disk, name string, key []byte) (UnlockResult, error)

UnlockEncryptedVolumeUsingProtectorKey unlocks the provided device with a given plain key. Depending on how then encrypted device was set up, the key is either used to unlock the device directly, or it is used to decrypt the encrypted unlock key stored in LUKS2 tokens in the device.

func UnlockVolumeUsingSealedKeyIfEncrypted

func UnlockVolumeUsingSealedKeyIfEncrypted(activation ActivateContext, disk disks.Disk, name string, sealedEncryptionKeyFiles []*LegacyKeyFile, opts *UnlockVolumeUsingSealedKeyOptions) (UnlockResult, error)

UnlockVolumeUsingSealedKeyIfEncrypted verifies whether an encrypted volume with the specified name exists and unlocks it using a sealed key in a file with a corresponding name. The options control activation with the recovery key will be attempted if a prior activation attempt with the sealed key fails.

Note that if the function proceeds to the point where it knows definitely whether there is an encrypted device or not, IsEncrypted on the return value will be true, even if error is non-nil. This is so that callers can be robust and try unlocking using another method for example.

type UnlockVolumeUsingSealedKeyOptions

type UnlockVolumeUsingSealedKeyOptions struct {
	// AllowRecoveryKey when true indicates activation with the recovery key
	// will be attempted if activation with the sealed key failed.
	AllowRecoveryKey bool
	// WhichModel if invoked should return the device model
	// assertion for which the disk is being unlocked.
	WhichModel func() (*asserts.Model, error)
	// BootMode is the current boot mode (i.e. snapd_recovery_mode kernel parameter)
	BootMode string
}

UnlockVolumeUsingSealedKeyOptions contains options for unlocking encrypted volumes using keys sealed to the TPM.

type UpdatedKeys

type UpdatedKeys []MaybeSealedKeyData

UpdatedKeys is a collection of updated sealed key that can be used to revoke older keys. Sealed keys *may* use different policy counter, though in practice they all share the same counter. This is why we need a collection.

func ResealKey

func ResealKey(key KeyDataLocation, params *ResealKeyParams) (UpdatedKeys, error)

ResealKey reads a key and dispatch the reseal depending on the platform used by the key.

func (*UpdatedKeys) PCRPolicyCounterHandles

func (uk *UpdatedKeys) PCRPolicyCounterHandles() []uint32

PCRPolicyCounterHandles returns the set of handles used by keys in the UpdatedKeys. Handles will appear only once, even if multiple keys use the same one.

func (*UpdatedKeys) RevokeOldKeys

func (uk *UpdatedKeys) RevokeOldKeys(primaryKey []byte) error

RevokeOldKeys goes through all of the updated keys and make sure to increase all the policy counters used by those keys to the value those keys use.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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