From c94e195124ba3dccfd9026f1cbf728dab18d5045 Mon Sep 17 00:00:00 2001 From: Spyros Seimenis Date: Thu, 14 Mar 2024 17:46:39 +0200 Subject: [PATCH 1/4] multiple: replace xerrors.Errorf instances with fmt.Errorf as of Go 1.13, Errorf's %w verb has been incorporated into fmt.Errorf. --- argon2.go | 5 +-- auth_requestor_systemd.go | 15 ++++---- bootscope/keydata.go | 5 +-- bootscope/keydata_test.go | 5 +-- bootscope/snap.go | 7 ++-- crypt.go | 42 ++++++++++----------- efi/env.go | 4 +- efi/fw_load_handler.go | 25 ++++++------- efi/grub_load_handler.go | 6 +-- efi/image_load_handler.go | 5 +-- efi/image_rules.go | 8 ++-- efi/pcr_images_measurer.go | 12 +++--- efi/pcr_profile.go | 8 ++-- efi/pe.go | 12 +++--- efi/secureboot.go | 16 ++++---- efi/secureboot_namespace_rules.go | 6 +-- efi/shim.go | 13 +++---- efi/shim_load_handler.go | 30 +++++++-------- internal/argon2/argon2.go | 4 +- internal/keyring/keyring.go | 11 +++--- internal/luks2/cryptsetup.go | 4 +- internal/luks2/metadata.go | 58 ++++++++++++++--------------- internal/luksview/tokens.go | 3 +- internal/tpm2test/ekcert.go | 25 ++++++------- keydata.go | 40 ++++++++++---------- keydata_file.go | 13 +++---- keydata_legacy.go | 13 +++---- keydata_luks.go | 7 ++-- snap.go | 7 ++-- tools/gen-compattest-data/main.go | 10 ++--- tools/make-efi-testdata/apps.go | 24 ++++++------ tools/make-efi-testdata/buildenv.go | 17 ++++----- tools/make-efi-testdata/certs.go | 16 ++++---- tools/make-efi-testdata/main.go | 14 +++---- tpm2/key_sealer.go | 10 ++--- tpm2/keydata.go | 8 ++-- tpm2/keydata_v0.go | 18 ++++----- tpm2/keydata_v1.go | 7 ++-- tpm2/keydata_v3.go | 13 +++---- tpm2/pcr_profile.go | 8 ++-- tpm2/platform.go | 18 ++++----- tpm2/platform_legacy.go | 6 +-- tpm2/policy.go | 5 ++- tpm2/policy_v0.go | 36 +++++++++--------- tpm2/policy_v1.go | 22 +++++------ tpm2/policy_v3.go | 23 ++++++------ tpm2/provisioning.go | 48 ++++++++++++------------ tpm2/seal.go | 27 +++++++------- tpm2/seal_legacy.go | 32 ++++++++-------- tpm2/snapmodel_policy.go | 13 +++---- tpm2/tpm.go | 56 ++++++++++++++-------------- tpm2/tpm2_test.go | 6 +-- tpm2/unseal.go | 16 ++++---- tpm2/update.go | 30 +++++++-------- tpm2/update_legacy.go | 10 ++--- tpm2/utils.go | 2 +- 56 files changed, 428 insertions(+), 476 deletions(-) diff --git a/argon2.go b/argon2.go index aca7c9f7..5d714521 100644 --- a/argon2.go +++ b/argon2.go @@ -21,12 +21,11 @@ package secboot import ( "errors" + "fmt" "runtime" "sync" "time" - "golang.org/x/xerrors" - "github.com/snapcore/secboot/internal/argon2" ) @@ -136,7 +135,7 @@ func (o *Argon2Options) deriveCostParams(keyLen int) (*Argon2CostParams, error) Threads: params.Threads}) }) if err != nil { - return nil, xerrors.Errorf("cannot benchmark KDF: %w", err) + return nil, fmt.Errorf("cannot benchmark KDF: %w", err) } return &Argon2CostParams{ diff --git a/auth_requestor_systemd.go b/auth_requestor_systemd.go index 596a0ebb..82971071 100644 --- a/auth_requestor_systemd.go +++ b/auth_requestor_systemd.go @@ -22,13 +22,12 @@ package secboot import ( "bytes" "errors" + "fmt" "os" "os/exec" "path/filepath" "strings" "text/template" - - "golang.org/x/xerrors" ) type askPasswordMsgParams struct { @@ -53,7 +52,7 @@ func (r *systemdAuthRequestor) askPassword(sourceDevicePath, msg string) (string cmd.Stdout = out cmd.Stdin = os.Stdin if err := cmd.Run(); err != nil { - return "", xerrors.Errorf("cannot execute systemd-ask-password: %v", err) + return "", fmt.Errorf("cannot execute systemd-ask-password: %v", err) } result, err := out.ReadString('\n') if err != nil { @@ -70,7 +69,7 @@ func (r *systemdAuthRequestor) RequestPassphrase(volumeName, sourceDevicePath st msg := new(bytes.Buffer) if err := r.passphraseTmpl.Execute(msg, params); err != nil { - return "", xerrors.Errorf("cannot execute message template: %w", err) + return "", fmt.Errorf("cannot execute message template: %w", err) } return r.askPassword(sourceDevicePath, msg.String()) @@ -83,7 +82,7 @@ func (r *systemdAuthRequestor) RequestRecoveryKey(volumeName, sourceDevicePath s msg := new(bytes.Buffer) if err := r.recoveryKeyTmpl.Execute(msg, params); err != nil { - return RecoveryKey{}, xerrors.Errorf("cannot execute message template: %w", err) + return RecoveryKey{}, fmt.Errorf("cannot execute message template: %w", err) } passphrase, err := r.askPassword(sourceDevicePath, msg.String()) @@ -93,7 +92,7 @@ func (r *systemdAuthRequestor) RequestRecoveryKey(volumeName, sourceDevicePath s key, err := ParseRecoveryKey(passphrase) if err != nil { - return RecoveryKey{}, xerrors.Errorf("cannot parse recovery key: %w", err) + return RecoveryKey{}, fmt.Errorf("cannot parse recovery key: %w", err) } return key, nil @@ -108,12 +107,12 @@ func (r *systemdAuthRequestor) RequestRecoveryKey(volumeName, sourceDevicePath s func NewSystemdAuthRequestor(passphraseTmpl, recoveryKeyTmpl string) (AuthRequestor, error) { pt, err := template.New("passphraseMsg").Parse(passphraseTmpl) if err != nil { - return nil, xerrors.Errorf("cannot parse passphrase message template: %w", err) + return nil, fmt.Errorf("cannot parse passphrase message template: %w", err) } rkt, err := template.New("recoveryKeyMsg").Parse(recoveryKeyTmpl) if err != nil { - return nil, xerrors.Errorf("cannot parse recovery key message template: %w", err) + return nil, fmt.Errorf("cannot parse recovery key message template: %w", err) } return &systemdAuthRequestor{ diff --git a/bootscope/keydata.go b/bootscope/keydata.go index f5448a2e..b83a8aae 100644 --- a/bootscope/keydata.go +++ b/bootscope/keydata.go @@ -37,7 +37,6 @@ import ( "golang.org/x/crypto/cryptobyte" cryptobyte_asn1 "golang.org/x/crypto/cryptobyte/asn1" "golang.org/x/crypto/hkdf" - "golang.org/x/xerrors" ) const ( @@ -254,7 +253,7 @@ func (d *KeyDataScope) authorize(key secboot.PrimaryKey, role string) error { d.data.Params.marshalASN1(builder) scope, err := builder.Bytes() if err != nil { - return xerrors.Errorf("cannot serialize scope: %w", err) + return fmt.Errorf("cannot serialize scope: %w", err) } alg := d.data.MDAlg @@ -419,7 +418,7 @@ func (d *KeyDataScope) MakeAEADAdditionalData(generation int, kdfAlg crypto.Hash der, err := x509.MarshalPKIXPublicKey(d.data.PublicKey.PublicKey) if err != nil { - return nil, xerrors.Errorf("cannot marshal public key: %w", err) + return nil, fmt.Errorf("cannot marshal public key: %w", err) } h := alg.New() diff --git a/bootscope/keydata_test.go b/bootscope/keydata_test.go index 17b61e54..2dcac01c 100644 --- a/bootscope/keydata_test.go +++ b/bootscope/keydata_test.go @@ -33,7 +33,6 @@ import ( "fmt" "hash" - "golang.org/x/xerrors" . "gopkg.in/check.v1" "github.com/snapcore/secboot" @@ -897,7 +896,7 @@ func (h *mockPlatformKeyDataHandler) checkState() error { func (h *mockPlatformKeyDataHandler) unmarshalHandle(data *PlatformKeyData) (*mockPlatformKeyDataHandle, error) { var handle mockPlatformKeyDataHandle if err := json.Unmarshal(data.EncodedHandle, &handle); err != nil { - return nil, &PlatformHandlerError{Type: PlatformHandlerErrorInvalidData, Err: xerrors.Errorf("JSON decode error: %w", err)} + return nil, &PlatformHandlerError{Type: PlatformHandlerErrorInvalidData, Err: fmt.Errorf("JSON decode error: %w", err)} } return &handle, nil } @@ -929,7 +928,7 @@ func (h *mockPlatformKeyDataHandler) recoverKeys(handle *mockPlatformKeyDataHand b, err := aes.NewCipher(handle.Key) if err != nil { - return nil, xerrors.Errorf("cannot create cipher: %w", err) + return nil, fmt.Errorf("cannot create cipher: %w", err) } s := cipher.NewCFBDecrypter(b, handle.IV) diff --git a/bootscope/snap.go b/bootscope/snap.go index 489fc9e9..fe6aac42 100644 --- a/bootscope/snap.go +++ b/bootscope/snap.go @@ -23,11 +23,11 @@ import ( "crypto" "encoding/asn1" "encoding/base64" + "fmt" "github.com/snapcore/secboot" "golang.org/x/crypto/cryptobyte" cryptobyte_asn1 "golang.org/x/crypto/cryptobyte/asn1" - "golang.org/x/xerrors" ) var sha3_384oid = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 2, 9} @@ -35,7 +35,7 @@ var sha3_384oid = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 2, 9} func computeSnapModelHash(alg crypto.Hash, model secboot.SnapModel) ([]byte, error) { signKeyId, err := base64.RawURLEncoding.DecodeString(model.SignKeyID()) if err != nil { - return nil, xerrors.Errorf("cannot decode signing key ID: %w", err) + return nil, fmt.Errorf("cannot decode signing key ID: %w", err) } builder := cryptobyte.NewBuilder(nil) @@ -62,9 +62,8 @@ func computeSnapModelHash(alg crypto.Hash, model secboot.SnapModel) ([]byte, err b, err := builder.Bytes() if err != nil { - return nil, xerrors.Errorf("cannot serialize model properties: %w", err) + return nil, fmt.Errorf("cannot serialize model properties: %w", err) } - h := alg.New() h.Write(b) return h.Sum(nil), nil diff --git a/crypt.go b/crypt.go index bd27ba88..84cd7e13 100755 --- a/crypt.go +++ b/crypt.go @@ -87,7 +87,7 @@ func ParseRecoveryKey(s string) (out RecoveryKey, err error) { } x, err := strconv.ParseUint(s[0:5], 10, 16) if err != nil { - return RecoveryKey{}, xerrors.Errorf("incorrectly formatted: %w", err) + return RecoveryKey{}, fmt.Errorf("incorrectly formatted: %w", err) } binary.LittleEndian.PutUint16(out[i*2:], uint16(x)) @@ -167,14 +167,14 @@ func (s *activateWithKeyDataState) tryActivateWithRecoveredKey(key DiskUnlockKey authorized, err := keyData.IsSnapModelAuthorized(auxKey, model) switch { case err != nil: - return xerrors.Errorf("cannot check if snap model is authorized: %w", err) + return fmt.Errorf("cannot check if snap model is authorized: %w", err) case !authorized: return errors.New("snap model is not authorized") } } if err := luks2Activate(s.volumeName, s.sourceDevicePath, key, slot); err != nil { - return xerrors.Errorf("cannot activate volume: %w", err) + return fmt.Errorf("cannot activate volume: %w", err) } if err := keyring.AddKeyToUserKeyring(key, s.sourceDevicePath, keyringPurposeDiskUnlock, s.keyringPrefix); err != nil { @@ -191,7 +191,7 @@ func (s *activateWithKeyDataState) tryActivateWithRecoveredKey(key DiskUnlockKey func (s *activateWithKeyDataState) tryKeyDataAuthModeNone(k *KeyData, slot int) error { key, auxKey, err := k.RecoverKeys() if err != nil { - return xerrors.Errorf("cannot recover key: %w", err) + return fmt.Errorf("cannot recover key: %w", err) } return s.tryActivateWithRecoveredKey(key, slot, k, auxKey) @@ -200,7 +200,7 @@ func (s *activateWithKeyDataState) tryKeyDataAuthModeNone(k *KeyData, slot int) func (s *activateWithKeyDataState) tryKeyDataAuthModePassphrase(k *KeyData, slot int, passphrase string) error { key, auxKey, err := k.RecoverKeysWithPassphrase(passphrase) if err != nil { - return xerrors.Errorf("cannot recover key: %w", err) + return fmt.Errorf("cannot recover key: %w", err) } return s.tryActivateWithRecoveredKey(key, slot, k, auxKey) @@ -244,7 +244,7 @@ func (s *activateWithKeyDataState) run() (success bool, err error) { // ubuntu-data). passphrase, err := s.authRequestor.RequestPassphrase(s.volumeName, s.sourceDevicePath) if err != nil { - passphraseErr = xerrors.Errorf("cannot obtain passphrase: %w", err) + passphraseErr = fmt.Errorf("cannot obtain passphrase: %w", err) continue } @@ -297,12 +297,12 @@ func activateWithRecoveryKey(volumeName, sourceDevicePath string, authRequestor key, err := authRequestor.RequestRecoveryKey(volumeName, sourceDevicePath) if err != nil { - lastErr = xerrors.Errorf("cannot obtain recovery key: %w", err) + lastErr = fmt.Errorf("cannot obtain recovery key: %w", err) continue } if err := luks2Activate(volumeName, sourceDevicePath, key[:], luks2.AnySlot); err != nil { - lastErr = xerrors.Errorf("cannot activate volume: %w", err) + lastErr = fmt.Errorf("cannot activate volume: %w", err) continue } @@ -629,7 +629,7 @@ func InitializeLUKS2Container(devicePath, label string, key DiskUnlockKey, optio } if err := luks2Format(devicePath, label, key, options.formatOpts()); err != nil { - return xerrors.Errorf("cannot format: %w", err) + return fmt.Errorf("cannot format: %w", err) } token := luksview.KeyDataToken{ @@ -637,11 +637,11 @@ func InitializeLUKS2Container(devicePath, label string, key DiskUnlockKey, optio TokenKeyslot: 0, TokenName: initialKeyslotName}} if err := luks2ImportToken(devicePath, &token, nil); err != nil { - return xerrors.Errorf("cannot import token: %w", err) + return fmt.Errorf("cannot import token: %w", err) } if err := luks2SetSlotPriority(devicePath, 0, luks2.SlotPriorityHigh); err != nil { - return xerrors.Errorf("cannot change keyslot priority: %w", err) + return fmt.Errorf("cannot change keyslot priority: %w", err) } return nil @@ -657,7 +657,7 @@ func addLUKS2ContainerKey(devicePath, keyslotName string, existingKey, newKey Di newToken func(base *luksview.TokenBase) luks2.Token, priority luks2.SlotPriority) error { view, err := newLUKSView(devicePath, luks2.LockModeBlocking) if err != nil { - return xerrors.Errorf("cannot obtain LUKS header view: %w", err) + return fmt.Errorf("cannot obtain LUKS header view: %w", err) } if _, _, exists := view.TokenByName(keyslotName); exists { @@ -675,7 +675,7 @@ func addLUKS2ContainerKey(devicePath, keyslotName string, existingKey, newKey Di } if err := luks2AddKey(devicePath, existingKey, newKey, &luks2.AddKeyOptions{KDFOptions: *options, Slot: freeSlot}); err != nil { - return xerrors.Errorf("cannot add key: %w", err) + return fmt.Errorf("cannot add key: %w", err) } // XXX: If we fail between AddKey and ImportToken, then we end up with a @@ -713,11 +713,11 @@ func addLUKS2ContainerKey(devicePath, keyslotName string, existingKey, newKey Di TokenName: keyslotName, TokenKeyslot: freeSlot} if err := luks2ImportToken(devicePath, newToken(&tokenBase), nil); err != nil { - return xerrors.Errorf("cannot import token: %w", err) + return fmt.Errorf("cannot import token: %w", err) } if err := luks2SetSlotPriority(devicePath, freeSlot, priority); err != nil { - return xerrors.Errorf("cannot change keyslot priority: %w", err) + return fmt.Errorf("cannot change keyslot priority: %w", err) } return nil @@ -726,7 +726,7 @@ func addLUKS2ContainerKey(devicePath, keyslotName string, existingKey, newKey Di func listLUKS2ContainerKeyNames(devicePath string, tokenType luks2.TokenType) ([]string, error) { view, err := newLUKSView(devicePath, luks2.LockModeBlocking) if err != nil { - return nil, xerrors.Errorf("cannot obtain LUKS header view: %w", err) + return nil, fmt.Errorf("cannot obtain LUKS header view: %w", err) } var names []string @@ -844,7 +844,7 @@ func ListLUKS2ContainerRecoveryKeyNames(devicePath string) ([]string, error) { func DeleteLUKS2ContainerKey(devicePath, keyslotName string) error { view, err := newLUKSView(devicePath, luks2.LockModeBlocking) if err != nil { - return xerrors.Errorf("cannot obtain LUKS header view: %w", err) + return fmt.Errorf("cannot obtain LUKS header view: %w", err) } token, id, exists := view.TokenByName(keyslotName) @@ -864,7 +864,7 @@ func DeleteLUKS2ContainerKey(devicePath, keyslotName string) error { slot := token.Keyslots()[0] if err := luks2KillSlot(devicePath, slot); err != nil { - return xerrors.Errorf("cannot kill existing slot %d: %w", slot, err) + return fmt.Errorf("cannot kill existing slot %d: %w", slot, err) } // KillSlot will clear the keyslot field from the associated token so @@ -872,7 +872,7 @@ func DeleteLUKS2ContainerKey(devicePath, keyslotName string) error { // the future if we are interrupted between KillSlot and RemoveToken. if err := luks2RemoveToken(devicePath, id); err != nil { - return xerrors.Errorf("cannot remove existing token %d: %w", id, err) + return fmt.Errorf("cannot remove existing token %d: %w", id, err) } return nil @@ -883,7 +883,7 @@ func DeleteLUKS2ContainerKey(devicePath, keyslotName string) error { func RenameLUKS2ContainerKey(devicePath, oldName, newName string) error { view, err := newLUKSView(devicePath, luks2.LockModeBlocking) if err != nil { - return xerrors.Errorf("cannot obtain LUKS header view: %w", err) + return fmt.Errorf("cannot obtain LUKS header view: %w", err) } removeOrphanedTokens(devicePath, view) @@ -917,7 +917,7 @@ func RenameLUKS2ContainerKey(devicePath, oldName, newName string) error { } if err := luks2ImportToken(devicePath, newToken, &luks2.ImportTokenOptions{Id: id, Replace: true}); err != nil { - return xerrors.Errorf("cannot import new token: %w", err) + return fmt.Errorf("cannot import new token: %w", err) } return nil diff --git a/efi/env.go b/efi/env.go index 306bdcde..724c3045 100644 --- a/efi/env.go +++ b/efi/env.go @@ -24,12 +24,12 @@ import ( "crypto" "crypto/sha1" "encoding/binary" + "fmt" "io" "sort" efi "github.com/canonical/go-efilib" "github.com/canonical/tcglog-parser" - "golang.org/x/xerrors" ) // HostEnvironment is an interface that abstracts out an EFI environment, so that @@ -261,7 +261,7 @@ func newRootVarsCollector(vars varReader) *rootVarsCollector { func (c *rootVarsCollector) registerUpdatesFor(initial *rootVarReader, updates *varUpdate) error { newRoot := initial.Copy() if err := newRoot.ApplyUpdates(updates); err != nil { - return xerrors.Errorf("cannot compute updated starting state: %w", err) + return fmt.Errorf("cannot compute updated starting state: %w", err) } key := newRoot.Key() diff --git a/efi/fw_load_handler.go b/efi/fw_load_handler.go index ffc8e200..3b90695d 100644 --- a/efi/fw_load_handler.go +++ b/efi/fw_load_handler.go @@ -27,7 +27,6 @@ import ( efi "github.com/canonical/go-efilib" "github.com/canonical/go-tpm2" "github.com/canonical/tcglog-parser" - "golang.org/x/xerrors" ) const ( @@ -47,7 +46,7 @@ var newFwLoadHandler = func(log *tcglog.Log) imageLoadHandler { func (h *fwLoadHandler) readAndMeasureSignatureDb(ctx pcrBranchContext, name efi.VariableDescriptor) ([]byte, error) { db, _, err := ctx.Vars().ReadVar(name.Name, name.GUID) if err != nil && err != efi.ErrVarNotExist { - return nil, xerrors.Errorf("cannot read current variable: %w", err) + return nil, fmt.Errorf("cannot read current variable: %w", err) } ctx.MeasureVariable(secureBootPCR, name.GUID, name.Name, db) @@ -62,7 +61,7 @@ func (h *fwLoadHandler) measureAuthorizedSignatureDb(ctx pcrBranchContext) error db, err := efi.ReadSignatureDatabase(bytes.NewReader(data)) if err != nil { - return xerrors.Errorf("cannot decode signatures: %w", err) + return fmt.Errorf("cannot decode signatures: %w", err) } ctx.FwContext().Db = &secureBootDB{Name: Db, Contents: db} return nil @@ -76,16 +75,16 @@ func (h *fwLoadHandler) measureSecureBootPolicyPreOS(ctx pcrBranchContext) error // measure events in the correct order. ctx.MeasureVariable(secureBootPCR, efi.GlobalVariable, sbStateName, []byte{1}) if _, err := h.readAndMeasureSignatureDb(ctx, PK); err != nil { - return xerrors.Errorf("cannot measure PK: %w", err) + return fmt.Errorf("cannot measure PK: %w", err) } if _, err := h.readAndMeasureSignatureDb(ctx, KEK); err != nil { - return xerrors.Errorf("cannot measure KEK: %w", err) + return fmt.Errorf("cannot measure KEK: %w", err) } if err := h.measureAuthorizedSignatureDb(ctx); err != nil { - return xerrors.Errorf("cannot measure db: %w", err) + return fmt.Errorf("cannot measure db: %w", err) } if _, err := h.readAndMeasureSignatureDb(ctx, Dbx); err != nil { - return xerrors.Errorf("cannot measure dbx: %w", err) + return fmt.Errorf("cannot measure dbx: %w", err) } // TODO: Support optional dbt/dbr databases @@ -191,7 +190,7 @@ func (h *fwLoadHandler) MeasureImageStart(ctx pcrBranchContext) error { if ctx.Flags()&secureBootPolicyProfile > 0 { if err := h.measureSecureBootPolicyPreOS(ctx); err != nil { - return xerrors.Errorf("cannot measure secure boot policy: %w", err) + return fmt.Errorf("cannot measure secure boot policy: %w", err) } } if ctx.Flags()&bootManagerCodeProfile > 0 { @@ -205,7 +204,7 @@ func (h *fwLoadHandler) MeasureImageStart(ctx pcrBranchContext) error { func (h *fwLoadHandler) MeasureImageLoad(ctx pcrBranchContext, image peImageHandle) (imageLoadHandler, error) { m := newFwImageLoadMeasurer(ctx, image) if err := m.measure(); err != nil { - return nil, xerrors.Errorf("cannot measure image: %w", err) + return nil, fmt.Errorf("cannot measure image: %w", err) } return lookupImageLoadHandler(ctx, image) } @@ -231,7 +230,7 @@ func (m *fwImageLoadMeasurer) measureVerification() error { // Firmware always measures the entire EFI_SIGNATURE_DATA including the SignatureOwner varData := new(bytes.Buffer) if err := authority.Signature.Write(varData); err != nil { - return xerrors.Errorf("cannot encode authority EFI_SIGNATURE_DATA: %w", err) + return fmt.Errorf("cannot encode authority EFI_SIGNATURE_DATA: %w", err) } digest := tcglog.ComputeEFIVariableDataDigest( @@ -252,7 +251,7 @@ func (m *fwImageLoadMeasurer) measureVerification() error { func (m *fwImageLoadMeasurer) measurePEImageDigest() error { digest, err := m.image.ImageDigest(m.PCRAlg().GetHash()) if err != nil { - return xerrors.Errorf("cannot compute PE digest: %w", err) + return fmt.Errorf("cannot compute PE digest: %w", err) } m.ExtendPCR(bootManagerCodePCR, digest) return nil @@ -261,13 +260,13 @@ func (m *fwImageLoadMeasurer) measurePEImageDigest() error { func (m *fwImageLoadMeasurer) measure() error { if m.Flags()&secureBootPolicyProfile > 0 { if err := m.measureVerification(); err != nil { - return xerrors.Errorf("cannot measure secure boot event: %w", err) + return fmt.Errorf("cannot measure secure boot event: %w", err) } } if m.Flags()&bootManagerCodeProfile > 0 { if err := m.measurePEImageDigest(); err != nil { - return xerrors.Errorf("cannot measure boot manager code event: %w", err) + return fmt.Errorf("cannot measure boot manager code event: %w", err) } } diff --git a/efi/grub_load_handler.go b/efi/grub_load_handler.go index f525baec..43316ea8 100644 --- a/efi/grub_load_handler.go +++ b/efi/grub_load_handler.go @@ -19,9 +19,7 @@ package efi -import ( - "golang.org/x/xerrors" -) +import "fmt" type grubFlags int @@ -64,7 +62,7 @@ func (h *grubLoadHandler) MeasureImageLoad(ctx pcrBranchContext, image peImageHa err = m.measure() } if err != nil { - return nil, xerrors.Errorf("cannot measure image: %w", err) + return nil, fmt.Errorf("cannot measure image: %w", err) } return lookupImageLoadHandler(ctx, image) diff --git a/efi/image_load_handler.go b/efi/image_load_handler.go index bfc35adb..2253a027 100644 --- a/efi/image_load_handler.go +++ b/efi/image_load_handler.go @@ -21,8 +21,7 @@ package efi import ( "errors" - - "golang.org/x/xerrors" + "fmt" ) // imageLoadHandler is an abstraction for measuring boot events @@ -82,7 +81,7 @@ func (m *imageLoadHandlerLazyMap) LookupHandler(image peImageHandle) (imageLoadH case err == errNoHandler: // skip case err != nil: - return nil, xerrors.Errorf("cannot create image load handler using %v: %w", c, err) + return nil, fmt.Errorf("cannot create image load handler using %v: %w", c, err) default: m.handlers[image.Source()] = handler return handler, nil diff --git a/efi/image_rules.go b/efi/image_rules.go index 637832e8..7c741872 100644 --- a/efi/image_rules.go +++ b/efi/image_rules.go @@ -23,8 +23,6 @@ import ( "bytes" "crypto" "fmt" - - "golang.org/x/xerrors" ) type ( @@ -110,12 +108,12 @@ func (r *imageRules) NewImageLoadHandler(image peImageHandle) (imageLoadHandler, for _, rule := range r.rules { matches, err := rule.match.Matches(image) if err != nil { - return nil, xerrors.Errorf("cannot run \"%s\" image rule: %w", rule.name, err) + return nil, fmt.Errorf("cannot run \"%s\" image rule: %w", rule.name, err) } if matches { handler, err := rule.create(image) if err != nil { - return nil, xerrors.Errorf("cannot create using \"%s\" image rule: %w", rule.name, err) + return nil, fmt.Errorf("cannot create using \"%s\" image rule: %w", rule.name, err) } return handler, nil } @@ -218,7 +216,7 @@ func (p *shimVersionPredicate) Matches(image peImageHandle) (bool, error) { shim := newShimImageHandle(image) x, err := shim.Version() if err != nil { - return false, xerrors.Errorf("cannot obtain shim version: %w", err) + return false, fmt.Errorf("cannot obtain shim version: %w", err) } y := mustParseShimVersion(p.version) diff --git a/efi/pcr_images_measurer.go b/efi/pcr_images_measurer.go index dd2934c4..00872013 100644 --- a/efi/pcr_images_measurer.go +++ b/efi/pcr_images_measurer.go @@ -19,9 +19,7 @@ package efi -import ( - "golang.org/x/xerrors" -) +import "fmt" // pcrImagesMeasurer binds a branch context, load handler and a set of images // that can be loaded. @@ -55,7 +53,7 @@ func (m *pcrImagesMeasurer) measureOneImage(bp *pcrBranchPointCtx, image ImageLo handle, err := openPeImage(image.source()) if err != nil { - return xerrors.Errorf("cannot open image: %w", err) + return fmt.Errorf("cannot open image: %w", err) } defer handle.Close() @@ -66,12 +64,12 @@ func (m *pcrImagesMeasurer) measureOneImage(bp *pcrBranchPointCtx, image ImageLo // Measure the verification and loading if the new image with the previous image's handler. handler, err := m.loadHandler.MeasureImageLoad(context, handle) if err != nil { - return xerrors.Errorf("cannot measure image load: %w", err) + return fmt.Errorf("cannot measure image load: %w", err) } // Measure the execution of the new image using its own handler. if err := handler.MeasureImageStart(context); err != nil { - return xerrors.Errorf("cannot measure image start for params %#v: %w", p, err) + return fmt.Errorf("cannot measure image start for params %#v: %w", p, err) } next := image.next() @@ -89,7 +87,7 @@ func (m *pcrImagesMeasurer) Measure() ([]*pcrImagesMeasurer, error) { for _, image := range m.images { if err := m.measureOneImage(bp, image); err != nil { - return nil, xerrors.Errorf("cannot measure image %v: %w", image.source(), err) + return nil, fmt.Errorf("cannot measure image %v: %w", image.source(), err) } } diff --git a/efi/pcr_profile.go b/efi/pcr_profile.go index 10f77c16..d17b3b8c 100644 --- a/efi/pcr_profile.go +++ b/efi/pcr_profile.go @@ -21,11 +21,11 @@ package efi import ( "errors" + "fmt" "github.com/canonical/go-tpm2" "github.com/canonical/tcglog-parser" secboot_tpm2 "github.com/snapcore/secboot/tpm2" - "golang.org/x/xerrors" ) // PCRProfileOption is an option for AddPCRProfile @@ -206,7 +206,7 @@ func (g *pcrProfileGenerator) addPCRProfile(branch *secboot_tpm2.PCRProtectionPr log, err := g.env.ReadEventLog() if err != nil { - return xerrors.Errorf("cannot read TCG event log: %w", err) + return fmt.Errorf("cannot read TCG event log: %w", err) } g.log = log @@ -217,7 +217,7 @@ func (g *pcrProfileGenerator) addPCRProfile(branch *secboot_tpm2.PCRProtectionPr // Collect the starting EFI variable states from the supplied options for i, mod := range g.varModifiers { if err := mod(collector); err != nil { - return xerrors.Errorf("cannot process host variable modifier %d: %w", i, err) + return fmt.Errorf("cannot process host variable modifier %d: %w", i, err) } } @@ -249,7 +249,7 @@ func (g *pcrProfileGenerator) addOnePCRProfileBranch(bp *secboot_tpm2.PCRProtect handler := newFwLoadHandler(g.log) if err := handler.MeasureImageStart(rootBranch); err != nil { - return xerrors.Errorf("cannot measure pre-OS: %w", err) + return fmt.Errorf("cannot measure pre-OS: %w", err) } todo := []*pcrImagesMeasurer{newPcrImagesMeasurer(rootBranch, handler, g.loadSequences.images...)} diff --git a/efi/pe.go b/efi/pe.go index 6091bc45..d1b3703e 100644 --- a/efi/pe.go +++ b/efi/pe.go @@ -92,13 +92,13 @@ type peImageHandleImpl struct { var openPeImage = func(image Image) (peImageHandle, error) { r, err := image.Open() if err != nil { - return nil, xerrors.Errorf("cannot open image: %w", err) + return nil, fmt.Errorf("cannot open image: %w", err) } pefile, err := pe.NewFile(r) if err != nil { r.Close() - return nil, xerrors.Errorf("cannot decode image: %w", err) + return nil, fmt.Errorf("cannot decode image: %w", err) } return &peImageHandleImpl{source: image, pefile: pefile, r: r}, nil @@ -151,12 +151,12 @@ func (h *peImageHandleImpl) SbatComponents() ([]sbatComponent, error) { break } if err != nil { - return nil, xerrors.Errorf("invalid SBAT record: %w", err) + return nil, fmt.Errorf("invalid SBAT record: %w", err) } gen, err := strconv.Atoi(record[1]) if err != nil { - return nil, xerrors.Errorf("invalid SBAT component generation: %w", err) + return nil, fmt.Errorf("invalid SBAT component generation: %w", err) } component := sbatComponent{ Name: record[0], @@ -168,7 +168,7 @@ func (h *peImageHandleImpl) SbatComponents() ([]sbatComponent, error) { if component.Name == "sbat" { if component.Generation != 1 { - return nil, xerrors.Errorf("invalid .sbat section version") + return nil, fmt.Errorf("invalid .sbat section version") } continue } @@ -228,7 +228,7 @@ SignatureLoop: case xerrors.Is(err, io.EOF): break SignatureLoop case err != nil: - return nil, xerrors.Errorf("cannot decode WIN_CERTIFICATE from security directory entry %d: %w", i, err) + return nil, fmt.Errorf("cannot decode WIN_CERTIFICATE from security directory entry %d: %w", i, err) } sig, ok := c.(*efi.WinCertificateAuthenticode) diff --git a/efi/secureboot.go b/efi/secureboot.go index 334438ce..142eacbc 100644 --- a/efi/secureboot.go +++ b/efi/secureboot.go @@ -23,10 +23,10 @@ import ( "bytes" "crypto/x509" "errors" + "fmt" "io/ioutil" efi "github.com/canonical/go-efilib" - "golang.org/x/xerrors" ) var ( @@ -63,7 +63,7 @@ func (u signatureDBUpdatesOption) applyOptionTo(gen *pcrProfileGenerator) { // This creates a root variable instance for each intermediate state. for i, update := range u { if err := applySignatureDBUpdate(&branch, update, quirk); err != nil { - return xerrors.Errorf("cannot compute signature database update %d: %w", i, err) + return fmt.Errorf("cannot compute signature database update %d: %w", i, err) } } } @@ -116,7 +116,7 @@ type secureBootPolicyMixin struct{} func (m secureBootPolicyMixin) DetermineAuthority(dbs []*secureBootDB, image peImageHandle) (*secureBootAuthority, error) { sigs, err := image.SecureBootSignatures() if err != nil { - return nil, xerrors.Errorf("cannot obtain secure boot signatures: %w", err) + return nil, fmt.Errorf("cannot obtain secure boot signatures: %w", err) } if len(sigs) == 0 { @@ -183,7 +183,7 @@ func applySignatureDBUpdate(vars varReadWriter, update *SignatureDBUpdate, quirk // Skip over authentication header _, err := efi.ReadTimeBasedVariableAuthentication(updateReader) if err != nil { - return xerrors.Errorf("cannot decode EFI_VARIABLE_AUTHENTICATION_2 structure of update: %w", err) + return fmt.Errorf("cannot decode EFI_VARIABLE_AUTHENTICATION_2 structure of update: %w", err) } if update.Name != PK { @@ -194,19 +194,19 @@ func applySignatureDBUpdate(vars varReadWriter, update *SignatureDBUpdate, quirk case err == efi.ErrVarNotExist: // nothing to do case err != nil: - return xerrors.Errorf("cannot read original signature database: %w", err) + return fmt.Errorf("cannot read original signature database: %w", err) } base := bytes.NewReader(data) baseDb, err := efi.ReadSignatureDatabase(base) if err != nil { - return xerrors.Errorf("cannot decode base signature database: %w", err) + return fmt.Errorf("cannot decode base signature database: %w", err) } updateDb, err := efi.ReadSignatureDatabase(updateReader) if err != nil { - return xerrors.Errorf("cannot decode signature database update: %w", err) + return fmt.Errorf("cannot decode signature database update: %w", err) } var filtered efi.SignatureDatabase @@ -261,7 +261,7 @@ func applySignatureDBUpdate(vars varReadWriter, update *SignatureDBUpdate, quirk // Serialize the filtered list of ESLs var buf bytes.Buffer if err := filtered.Write(&buf); err != nil { - return xerrors.Errorf("cannot encode filtered signature database update: %w", err) + return fmt.Errorf("cannot encode filtered signature database update: %w", err) } updateData = buf.Bytes() } else { diff --git a/efi/secureboot_namespace_rules.go b/efi/secureboot_namespace_rules.go index 6d0322a8..981a0258 100644 --- a/efi/secureboot_namespace_rules.go +++ b/efi/secureboot_namespace_rules.go @@ -22,9 +22,9 @@ package efi import ( "bytes" "crypto/x509" + "fmt" "github.com/snapcore/snapd/snapdenv" - "golang.org/x/xerrors" ) var ( @@ -159,7 +159,7 @@ func (r *secureBootNamespaceRules) NewImageLoadHandler(image peImageHandle) (ima sigs, err := image.SecureBootSignatures() if err != nil { // Reject any image with a badly formed security directory entry - return nil, xerrors.Errorf("cannot obtain secure boot signatures: %w", err) + return nil, fmt.Errorf("cannot obtain secure boot signatures: %w", err) } for _, authority := range r.authorities { @@ -183,7 +183,7 @@ func (r *secureBootNamespaceRules) NewImageLoadHandler(image peImageHandle) (ima if v, ok := handler.(vendorAuthorityGetter); ok { certs, err := v.VendorAuthorities() if err != nil { - return nil, xerrors.Errorf("cannot obtain vendor authorities: %w", err) + return nil, fmt.Errorf("cannot obtain vendor authorities: %w", err) } r.AddAuthorities(certs...) } diff --git a/efi/shim.go b/efi/shim.go index fcf7d9eb..e1371504 100644 --- a/efi/shim.go +++ b/efi/shim.go @@ -34,7 +34,6 @@ import ( efi "github.com/canonical/go-efilib" "golang.org/x/crypto/cryptobyte" cryptobyte_asn1 "golang.org/x/crypto/cryptobyte/asn1" - "golang.org/x/xerrors" ) const ( @@ -127,7 +126,7 @@ func newestSbatLevel(levels ...[]byte) ([]byte, error) { for i, level := range levels { record, err := csv.NewReader(bytes.NewReader(level)).Read() if err != nil { - return nil, xerrors.Errorf("cannot parse SBAT level %d: %w", i, err) + return nil, fmt.Errorf("cannot parse SBAT level %d: %w", i, err) } if len(record) < 3 { return nil, fmt.Errorf("invalid SBAT level at %d", i) @@ -205,7 +204,7 @@ func parseShimVersionDataIdent(r io.Reader) (shimVersion, error) { } } if scanner.Err() != nil { - return shimVersion{}, xerrors.Errorf("cannot decode .data.ident section contents: %w", scanner.Err()) + return shimVersion{}, fmt.Errorf("cannot decode .data.ident section contents: %w", scanner.Err()) } return shimVersion{}, errors.New("cannot determine version - missing from .data.ident section") } @@ -313,7 +312,7 @@ func (h *shimImageHandleImpl) ReadVendorDB() (efi.SignatureDatabase, shimVendorC // shim source) var table shimVendorCertTable if err := binary.Read(section, binary.LittleEndian, &table); err != nil { - return nil, 0, xerrors.Errorf("cannot read vendor certs table: %w", err) + return nil, 0, fmt.Errorf("cannot read vendor certs table: %w", err) } // A size of zero is valid @@ -324,7 +323,7 @@ func (h *shimImageHandleImpl) ReadVendorDB() (efi.SignatureDatabase, shimVendorC sr := io.NewSectionReader(section, int64(table.DbOffset), int64(table.DbSize)) dbData, err := ioutil.ReadAll(sr) if err != nil { - return nil, 0, xerrors.Errorf("cannot read vendor db data: %w", err) + return nil, 0, fmt.Errorf("cannot read vendor db data: %w", err) } elem := cryptobyte.String(dbData) @@ -365,7 +364,7 @@ func (h *shimImageHandleImpl) ReadSbatLevel() (shimSbatLevel, error) { // containing 2 offsets to each/ NULL terminated SBAT revocation policy. var version uint32 if err := binary.Read(section, binary.LittleEndian, &version); err != nil { - return shimSbatLevel{}, xerrors.Errorf("cannot read .sbatlevel version: %w", err) + return shimSbatLevel{}, fmt.Errorf("cannot read .sbatlevel version: %w", err) } if version != 0 { return shimSbatLevel{}, errors.New("invalid .sbatlevel version") @@ -375,7 +374,7 @@ func (h *shimImageHandleImpl) ReadSbatLevel() (shimSbatLevel, error) { var table shimSbatLevelTable if err := binary.Read(io.NewSectionReader(sr, 0, int64(binary.Size(table))), binary.LittleEndian, &table); err != nil { - return shimSbatLevel{}, xerrors.Errorf("cannot read .sbatlevel table: %w", err) + return shimSbatLevel{}, fmt.Errorf("cannot read .sbatlevel table: %w", err) } var out shimSbatLevel diff --git a/efi/shim_load_handler.go b/efi/shim_load_handler.go index a224561d..fa6f8c30 100644 --- a/efi/shim_load_handler.go +++ b/efi/shim_load_handler.go @@ -23,10 +23,10 @@ import ( "bytes" "crypto/x509" "errors" + "fmt" efi "github.com/canonical/go-efilib" "github.com/canonical/tcglog-parser" - "golang.org/x/xerrors" ) // shimLoadHandler is an implementation of imageLoadHandler for shim. @@ -67,7 +67,7 @@ func (c *shimLoadHandlerConstructor) New(image peImageHandle) (imageLoadHandler, var err error ver, err = shim.Version() if err != nil { - return nil, xerrors.Errorf("cannot obtain shim version: %w", err) + return nil, fmt.Errorf("cannot obtain shim version: %w", err) } } @@ -95,7 +95,7 @@ func (c *shimLoadHandlerConstructor) New(image peImageHandle) (imageLoadHandler, // Read the built in vendor cert vendorDb, format, err := shim.ReadVendorDB() if err != nil { - return nil, xerrors.Errorf("cannot read vendor DB: %w", err) + return nil, fmt.Errorf("cannot read vendor DB: %w", err) } vendorDbName := efi.VariableDescriptor{Name: shimName, GUID: shimGuid} @@ -133,7 +133,7 @@ func (c *shimLoadHandlerConstructor) New(image peImageHandle) (imageLoadHandler, } else if shim.HasSbatLevelSection() { sbatLevel, err = shim.ReadSbatLevel() if err != nil { - return nil, xerrors.Errorf("cannot read SbatLevel from shim: %w", err) + return nil, fmt.Errorf("cannot read SbatLevel from shim: %w", err) } } @@ -163,7 +163,7 @@ func (h *shimLoadHandler) VendorAuthorities() ([]*x509.Certificate, error) { cert, err := x509.ParseCertificate(esl.Signatures[0].Data) if err != nil { - return nil, xerrors.Errorf("cannot parse vendor cert at %d: %w", i, err) + return nil, fmt.Errorf("cannot parse vendor cert at %d: %w", i, err) } vendorCerts = append(vendorCerts, cert) } @@ -199,7 +199,7 @@ func (h *shimLoadHandler) MeasureImageStart(ctx pcrBranchContext) error { policy, err = readShimSbatPolicy(ctx.Vars()) switch { case err != nil: - return xerrors.Errorf("cannot read shim SbatPolicy: %w", err) + return fmt.Errorf("cannot read shim SbatPolicy: %w", err) case policy == shimSbatPolicyReset: return errors.New("cannot handle SbatPolicy == reset") } @@ -210,7 +210,7 @@ func (h *shimLoadHandler) MeasureImageStart(ctx pcrBranchContext) error { shimSbatPolicyName, shimGuid, efi.AttributeNonVolatile|efi.AttributeBootserviceAccess|efi.AttributeRuntimeAccess, []byte{uint8(shimSbatPolicyPrevious)}); err != nil { - return xerrors.Errorf("cannot clear SbatPolicy: %w", err) + return fmt.Errorf("cannot clear SbatPolicy: %w", err) } } } @@ -224,12 +224,12 @@ func (h *shimLoadHandler) MeasureImageStart(ctx pcrBranchContext) error { // shim will program and measure one of its built in values. sbatLevel = h.SbatLevel.ForPolicy(policy) case err != nil: - return xerrors.Errorf("cannot obtain current SbatLevel: %w", err) + return fmt.Errorf("cannot obtain current SbatLevel: %w", err) default: // Determine which is the newest sbatLevel, err = newestSbatLevel(hostSbatLevel, h.SbatLevel.ForPolicy(policy)) if err != nil { - return xerrors.Errorf("cannot determine newest SbatLevel payload: %w", err) + return fmt.Errorf("cannot determine newest SbatLevel payload: %w", err) } } @@ -242,7 +242,7 @@ func (h *shimLoadHandler) MeasureImageStart(ctx pcrBranchContext) error { shimSbatLevelRTName, shimGuid, efi.AttributeBootserviceAccess|efi.AttributeRuntimeAccess, sbatLevel); err != nil { - return xerrors.Errorf("cannot update SbatLevel: %w", err) + return fmt.Errorf("cannot update SbatLevel: %w", err) } } @@ -253,7 +253,7 @@ func (h *shimLoadHandler) MeasureImageStart(ctx pcrBranchContext) error { func (h *shimLoadHandler) MeasureImageLoad(ctx pcrBranchContext, image peImageHandle) (imageLoadHandler, error) { m := newShimImageLoadMeasurer(ctx, image) if err := m.measure(); err != nil { - return nil, xerrors.Errorf("cannot measure image: %w", err) + return nil, fmt.Errorf("cannot measure image: %w", err) } return lookupImageLoadHandler(ctx, image) } @@ -273,7 +273,7 @@ func newShimImageLoadMeasurer(bc pcrBranchContext, image peImageHandle) *shimIma func (m *shimImageLoadMeasurer) measurePEImageDigest() error { digest, err := m.image.ImageDigest(m.PCRAlg().GetHash()) if err != nil { - return xerrors.Errorf("cannot compute PE digest: %w", err) + return fmt.Errorf("cannot compute PE digest: %w", err) } m.ExtendPCR(bootManagerCodePCR, digest) return nil @@ -303,7 +303,7 @@ func (m *shimImageLoadMeasurer) measureVerification() error { } else { data = new(bytes.Buffer) if err := authority.Signature.Write(data); err != nil { - return xerrors.Errorf("cannot encode authority EFI_SIGNATURE_DATA: %w", err) + return fmt.Errorf("cannot encode authority EFI_SIGNATURE_DATA: %w", err) } } @@ -325,13 +325,13 @@ func (m *shimImageLoadMeasurer) measureVerification() error { func (m *shimImageLoadMeasurer) measure() error { if m.Flags()&secureBootPolicyProfile > 0 { if err := m.measureVerification(); err != nil { - return xerrors.Errorf("cannot measure secure boot event: %w", err) + return fmt.Errorf("cannot measure secure boot event: %w", err) } } if m.Flags()&bootManagerCodeProfile > 0 { if err := m.measurePEImageDigest(); err != nil { - return xerrors.Errorf("cannot measure boot manager code event: %w", err) + return fmt.Errorf("cannot measure boot manager code event: %w", err) } } diff --git a/internal/argon2/argon2.go b/internal/argon2/argon2.go index 98969191..b560ad5f 100644 --- a/internal/argon2/argon2.go +++ b/internal/argon2/argon2.go @@ -21,12 +21,12 @@ package argon2 import ( "errors" + "fmt" "math" "time" "golang.org/x/crypto/argon2" "golang.org/x/sys/unix" - "golang.org/x/xerrors" ) const ( @@ -312,7 +312,7 @@ type KeyDurationFunc func(params *CostParams) (time.Duration, error) func Benchmark(params *BenchmarkParams, keyFn KeyDurationFunc) (*CostParams, error) { var sysInfo unix.Sysinfo_t if err := unixSysinfo(&sysInfo); err != nil { - return nil, xerrors.Errorf("cannot determine available memory: %w", err) + return nil, fmt.Errorf("cannot determine available memory: %w", err) } context := new(benchmarkContext) diff --git a/internal/keyring/keyring.go b/internal/keyring/keyring.go index 238c7f15..cb6afa34 100644 --- a/internal/keyring/keyring.go +++ b/internal/keyring/keyring.go @@ -20,8 +20,9 @@ package keyring import ( + "fmt" + "golang.org/x/sys/unix" - "golang.org/x/xerrors" ) const ( @@ -41,17 +42,17 @@ func AddKeyToUserKeyring(key []byte, devicePath, purpose, prefix string) error { func GetKeyFromUserKeyring(devicePath, purpose, prefix string) ([]byte, error) { id, err := unix.KeyctlSearch(userKeyring, userKeyType, formatDesc(devicePath, purpose, prefix), 0) if err != nil { - return nil, xerrors.Errorf("cannot find key: %w", err) + return nil, fmt.Errorf("cannot find key: %w", err) } sz, err := unix.KeyctlBuffer(unix.KEYCTL_READ, id, nil, 0) if err != nil { - return nil, xerrors.Errorf("cannot determine size of key payload: %w", err) + return nil, fmt.Errorf("cannot determine size of key payload: %w", err) } key := make([]byte, sz) if _, err = unix.KeyctlBuffer(unix.KEYCTL_READ, id, key, 0); err != nil { - return nil, xerrors.Errorf("cannot read key payload: %w", err) + return nil, fmt.Errorf("cannot read key payload: %w", err) } return key, nil @@ -60,7 +61,7 @@ func GetKeyFromUserKeyring(devicePath, purpose, prefix string) ([]byte, error) { func RemoveKeyFromUserKeyring(devicePath, purpose, prefix string) error { id, err := unix.KeyctlSearch(userKeyring, userKeyType, formatDesc(devicePath, purpose, prefix), 0) if err != nil { - return xerrors.Errorf("cannot find key: %w", err) + return fmt.Errorf("cannot find key: %w", err) } _, err = unix.KeyctlInt(unix.KEYCTL_UNLINK, id, userKeyring, 0, 0) diff --git a/internal/luks2/cryptsetup.go b/internal/luks2/cryptsetup.go index 777727b8..1e306363 100755 --- a/internal/luks2/cryptsetup.go +++ b/internal/luks2/cryptsetup.go @@ -32,8 +32,6 @@ import ( "time" "github.com/snapcore/snapd/osutil" - - "golang.org/x/xerrors" ) const ( @@ -467,7 +465,7 @@ func ImportToken(devicePath string, token Token, options *ImportTokenOptions) er tokenJSON, err := json.Marshal(token) if err != nil { - return xerrors.Errorf("cannot serialize token: %w", err) + return fmt.Errorf("cannot serialize token: %w", err) } args := []string{"token", "import"} diff --git a/internal/luks2/metadata.go b/internal/luks2/metadata.go index 964bc2a6..f37e0739 100644 --- a/internal/luks2/metadata.go +++ b/internal/luks2/metadata.go @@ -40,7 +40,6 @@ import ( "github.com/snapcore/secboot/internal/paths" "golang.org/x/sys/unix" - "golang.org/x/xerrors" ) var ( @@ -81,7 +80,7 @@ func acquireSharedLock(path string, mode LockMode) (release func(), err error) { // Initially open the device or file for reading f, err := os.Open(path) if err != nil { - return nil, xerrors.Errorf("cannot open device: %w", err) + return nil, fmt.Errorf("cannot open device: %w", err) } defer f.Close() @@ -93,7 +92,7 @@ func acquireSharedLock(path string, mode LockMode) (release func(), err error) { // Obtain information about the opened device or file fi, err := f.Stat() if err != nil { - return nil, xerrors.Errorf("cannot obtain file info: %w", err) + return nil, fmt.Errorf("cannot obtain file info: %w", err) } var lockPath string @@ -106,14 +105,13 @@ func acquireSharedLock(path string, mode LockMode) (release func(), err error) { // Don't assume that the lock directory exists. if err := os.Mkdir(cryptsetupLockDir(), 0700); err != nil && !os.IsExist(err) { - return nil, xerrors.Errorf("cannot create lock directory: %w", err) + return nil, fmt.Errorf("cannot create lock directory: %w", err) } - // Obtain information about the opened block device using the fstat syscall, // where we get more information. var st unix.Stat_t if err := dataDeviceFstat(int(f.Fd()), &st); err != nil { - return nil, xerrors.Errorf("cannot obtain device info: %w", err) + return nil, fmt.Errorf("cannot obtain device info: %w", err) } lockPath = filepath.Join(cryptsetupLockDir(), fmt.Sprintf("L_%d:%d", unix.Major(st.Rdev), unix.Minor(st.Rdev))) openFlags = os.O_RDWR | os.O_CREATE @@ -208,19 +206,19 @@ func acquireSharedLock(path string, mode LockMode) (release func(), err error) { // Attempt to open the lock file for writing. lockFile, err = os.OpenFile(lockPath, openFlags, 0600) if err != nil { - return nil, xerrors.Errorf("cannot open lock file for writing: %w", err) + return nil, fmt.Errorf("cannot open lock file for writing: %w", err) } // Obtain and save information about the opened lock file. if err := unix.Fstat(int(lockFile.Fd()), &origSt); err != nil { lockFile.Close() - return nil, xerrors.Errorf("cannot obtain lock file info: %w", err) + return nil, fmt.Errorf("cannot obtain lock file info: %w", err) } // Attempt to acquire the requested lock. if err := unix.Flock(int(lockFile.Fd()), how); err != nil { release() - return nil, xerrors.Errorf("cannot obtain lock: %w", err) + return nil, fmt.Errorf("cannot obtain lock: %w", err) } if isBlockDevice(fi.Mode()) { @@ -384,13 +382,13 @@ func (c *Config) UnmarshalJSON(data []byte) error { Requirements: d.Requirements} jsonSize, err := d.JSONSize.Uint64() if err != nil { - return xerrors.Errorf("invalid json_size value: %w", err) + return fmt.Errorf("invalid json_size value: %w", err) } c.JSONSize = jsonSize keyslotsSize, err := d.KeyslotsSize.Uint64() if err != nil { - return xerrors.Errorf("invalid keyslots_size value: %w", err) + return fmt.Errorf("invalid keyslots_size value: %w", err) } c.KeyslotsSize = keyslotsSize @@ -475,7 +473,7 @@ func (t *GenericToken) UnmarshalJSON(data []byte) error { for _, v := range d.Keyslots { s, err := v.Int() if err != nil { - return xerrors.Errorf("invalid keyslot id: %w", err) + return fmt.Errorf("invalid keyslot id: %w", err) } t.TokenKeyslots = append(t.TokenKeyslots, s) } @@ -527,7 +525,7 @@ func (d *Digest) UnmarshalJSON(data []byte) error { for _, v := range t.Keyslots { s, err := v.Int() if err != nil { - return xerrors.Errorf("invalid keyslot id: %w", err) + return fmt.Errorf("invalid keyslot id: %w", err) } d.Keyslots = append(d.Keyslots, s) } @@ -535,7 +533,7 @@ func (d *Digest) UnmarshalJSON(data []byte) error { for _, v := range t.Segments { s, err := v.Int() if err != nil { - return xerrors.Errorf("invalid segment id: %w", err) + return fmt.Errorf("invalid segment id: %w", err) } d.Segments = append(d.Segments, s) } @@ -589,7 +587,7 @@ func (s *Segment) UnmarshalJSON(data []byte) error { offset, err := d.Offset.Uint64() if err != nil { - return xerrors.Errorf("invalid offset value: %w", err) + return fmt.Errorf("invalid offset value: %w", err) } s.Offset = offset @@ -599,14 +597,14 @@ func (s *Segment) UnmarshalJSON(data []byte) error { default: sz, err := d.Size.Uint64() if err != nil { - return xerrors.Errorf("invalid size value: %w", err) + return fmt.Errorf("invalid size value: %w", err) } s.Size = sz } ivTweak, err := d.IVTweak.Uint64() if err != nil { - return xerrors.Errorf("invalid iv_tweak value: %w", err) + return fmt.Errorf("invalid iv_tweak value: %w", err) } s.IVTweak = ivTweak @@ -643,13 +641,13 @@ func (a *Area) UnmarshalJSON(data []byte) error { offset, err := d.Offset.Uint64() if err != nil { - return xerrors.Errorf("invalid offset value: %w", err) + return fmt.Errorf("invalid offset value: %w", err) } a.Offset = offset sz, err := d.Size.Uint64() if err != nil { - return xerrors.Errorf("invalid size value: %w", err) + return fmt.Errorf("invalid size value: %w", err) } a.Size = sz @@ -739,7 +737,7 @@ func (m *Metadata) UnmarshalJSON(data []byte) error { for k, v := range d.Keyslots { id, err := k.Int() if err != nil { - return xerrors.Errorf("invalid keyslot index: %w", err) + return fmt.Errorf("invalid keyslot index: %w", err) } m.Keyslots[id] = v } @@ -748,7 +746,7 @@ func (m *Metadata) UnmarshalJSON(data []byte) error { for k, v := range d.Segments { id, err := k.Int() if err != nil { - return xerrors.Errorf("invalid segment index: %w", err) + return fmt.Errorf("invalid segment index: %w", err) } m.Segments[id] = v } @@ -757,7 +755,7 @@ func (m *Metadata) UnmarshalJSON(data []byte) error { for k, v := range d.Digests { id, err := k.Int() if err != nil { - return xerrors.Errorf("invalid digest index: %w", err) + return fmt.Errorf("invalid digest index: %w", err) } m.Digests[id] = v } @@ -766,7 +764,7 @@ func (m *Metadata) UnmarshalJSON(data []byte) error { for k, v := range d.Tokens { id, err := k.Int() if err != nil { - return xerrors.Errorf("invalid token index: %w", err) + return fmt.Errorf("invalid token index: %w", err) } var token Token if decoder, ok := tokenDecoders[v.typ]; ok { @@ -802,7 +800,7 @@ func decodeAndCheckHeader(r io.ReadSeeker, offset int64, primary bool) (*binaryH var hdr binaryHdr if err := binary.Read(r, binary.BigEndian, &hdr); err != nil { - return nil, nil, xerrors.Errorf("cannot read header: %w", err) + return nil, nil, fmt.Errorf("cannot read header: %w", err) } switch { case primary && bytes.Equal(hdr.Magic[:], []byte("LUKS\xba\xbe")): @@ -835,14 +833,14 @@ func decodeAndCheckHeader(r io.ReadSeeker, offset int64, primary bool) (*binaryH hdrTmp := hdr hdrTmp.Csum = [64]byte{} if err := binary.Write(h, binary.BigEndian, &hdrTmp); err != nil { - return nil, nil, xerrors.Errorf("cannot calculate checksum, error serializing header: %w", err) + return nil, nil, fmt.Errorf("cannot calculate checksum, error serializing header: %w", err) } // Hash the JSON metadata area, keeping a copy of the hashed metadata in memory jsonBuffer := new(bytes.Buffer) tr := io.TeeReader(r, jsonBuffer) if _, err := io.CopyN(h, tr, int64(hdr.HdrSize)-int64(binary.Size(hdr))); err != nil { - return nil, nil, xerrors.Errorf("cannot calculate checksum, error reading JSON metadata: %w", err) + return nil, nil, fmt.Errorf("cannot calculate checksum, error reading JSON metadata: %w", err) } if !bytes.Equal(h.Sum(nil), hdr.Csum[0:csumHash.Size()]) { @@ -882,7 +880,7 @@ func decodeAndCheckHeader(r io.ReadSeeker, offset int64, primary bool) (*binaryH func ReadHeader(path string, lockMode LockMode) (*HeaderInfo, error) { releaseLock, err := acquireSharedLock(path, lockMode) if err != nil { - return nil, xerrors.Errorf("cannot acquire shared lock: %w", err) + return nil, fmt.Errorf("cannot acquire shared lock: %w", err) } defer releaseLock() @@ -897,7 +895,7 @@ func ReadHeader(path string, lockMode LockMode) (*HeaderInfo, error) { var primaryMetadata Metadata if primaryErr == nil { if err := json.NewDecoder(primaryJSONData).Decode(&primaryMetadata); err != nil { - primaryErr = xerrors.Errorf("cannot decode JSON metadata area: %w", err) + primaryErr = fmt.Errorf("cannot decode JSON metadata area: %w", err) } } @@ -921,7 +919,7 @@ func ReadHeader(path string, lockMode LockMode) (*HeaderInfo, error) { var secondaryMetadata Metadata if secondaryErr == nil { if err := json.NewDecoder(secondaryJSONData).Decode(&secondaryMetadata); err != nil { - secondaryErr = xerrors.Errorf("cannot decode JSON metadata area: %w", err) + secondaryErr = fmt.Errorf("cannot decode JSON metadata area: %w", err) } } @@ -956,7 +954,7 @@ func ReadHeader(path string, lockMode LockMode) (*HeaderInfo, error) { fmt.Fprintf(stderr, "luks2.ReadHeader: primary header for %s is invalid: %v\n", path, primaryErr) default: // No valid headers :( - return nil, xerrors.Errorf("no valid header found, error from decoding primary header: %w", primaryErr) + return nil, fmt.Errorf("no valid header found, error from decoding primary header: %w", primaryErr) } return &HeaderInfo{ diff --git a/internal/luksview/tokens.go b/internal/luksview/tokens.go index dd9a0bb5..b2c523a8 100644 --- a/internal/luksview/tokens.go +++ b/internal/luksview/tokens.go @@ -22,6 +22,7 @@ package luksview import ( "encoding/json" "errors" + "fmt" "strconv" "golang.org/x/xerrors" @@ -110,7 +111,7 @@ func (k *tokenKeyslots) UnmarshalJSON(data []byte) error { for _, v := range rawslots { slot, err := v.Int() if err != nil { - return xerrors.Errorf("invalid keyslot ID: %w", err) + return fmt.Errorf("invalid keyslot ID: %w", err) } keyslots = append(keyslots, slot) } diff --git a/internal/tpm2test/ekcert.go b/internal/tpm2test/ekcert.go index 7501d5fa..51cab265 100644 --- a/internal/tpm2test/ekcert.go +++ b/internal/tpm2test/ekcert.go @@ -25,14 +25,13 @@ import ( "crypto/x509" "crypto/x509/pkix" "encoding/asn1" + "fmt" "math/big" "math/rand" "time" "github.com/canonical/go-tpm2" - "golang.org/x/xerrors" - "github.com/snapcore/secboot/internal/tcg" "github.com/snapcore/secboot/internal/testutil" "github.com/snapcore/secboot/internal/truststore" @@ -44,12 +43,12 @@ func CreateTestCA() ([]byte, crypto.PrivateKey, error) { keyId := make([]byte, 32) if _, err := rand.Read(keyId); err != nil { - return nil, nil, xerrors.Errorf("cannot obtain random key ID: %w", err) + return nil, nil, fmt.Errorf("cannot obtain random key ID: %w", err) } key, err := rsa.GenerateKey(testutil.RandReader, 768) if err != nil { - return nil, nil, xerrors.Errorf("cannot generate RSA key: %w", err) + return nil, nil, fmt.Errorf("cannot generate RSA key: %w", err) } t := time.Now() @@ -70,7 +69,7 @@ func CreateTestCA() ([]byte, crypto.PrivateKey, error) { cert, err := x509.CreateCertificate(testutil.RandReader, &template, &template, &key.PublicKey, key) if err != nil { - return nil, nil, xerrors.Errorf("cannot create certificate: %w", err) + return nil, nil, fmt.Errorf("cannot create certificate: %w", err) } return cert, key, nil @@ -80,7 +79,7 @@ func CreateTestCA() ([]byte, crypto.PrivateKey, error) { func CreateTestEKCert(tpm *tpm2.TPMContext, caCert []byte, caKey crypto.PrivateKey) ([]byte, error) { ek, pub, _, _, _, err := tpm.CreatePrimary(tpm.EndorsementHandleContext(), nil, tcg.EKTemplate, nil, nil, nil) if err != nil { - return nil, xerrors.Errorf("cannot create EK: %w", err) + return nil, fmt.Errorf("cannot create EK: %w", err) } defer tpm.FlushContext(ek) @@ -92,7 +91,7 @@ func CreateTestEKCert(tpm *tpm2.TPMContext, caCert []byte, caKey crypto.PrivateK keyId := make([]byte, 32) if _, err := rand.Read(keyId); err != nil { - return nil, xerrors.Errorf("cannot obtain random key ID for EK cert: %w", err) + return nil, fmt.Errorf("cannot obtain random key ID for EK cert: %w", err) } t := time.Now() @@ -104,12 +103,12 @@ func CreateTestEKCert(tpm *tpm2.TPMContext, caCert []byte, caKey crypto.PrivateK pkix.AttributeTypeAndValue{Type: tcg.OIDTcgAttributeTpmVersion, Value: "id:00010002"}}} tpmDeviceAttrData, err := asn1.Marshal(tpmDeviceAttrValues) if err != nil { - return nil, xerrors.Errorf("cannot marshal SAN value: %2", err) + return nil, fmt.Errorf("cannot marshal SAN value: %2", err) } sanData, err := asn1.Marshal([]asn1.RawValue{ asn1.RawValue{Class: asn1.ClassContextSpecific, Tag: tcg.SANDirectoryNameTag, IsCompound: true, Bytes: tpmDeviceAttrData}}) if err != nil { - return nil, xerrors.Errorf("cannot marshal SAN value: %w", err) + return nil, fmt.Errorf("cannot marshal SAN value: %w", err) } sanExtension := pkix.Extension{ Id: tcg.OIDExtensionSubjectAltName, @@ -130,12 +129,12 @@ func CreateTestEKCert(tpm *tpm2.TPMContext, caCert []byte, caKey crypto.PrivateK root, err := x509.ParseCertificate(caCert) if err != nil { - return nil, xerrors.Errorf("cannot parse CA certificate: %w", err) + return nil, fmt.Errorf("cannot parse CA certificate: %w", err) } cert, err := x509.CreateCertificate(testutil.RandReader, &template, root, &key, caKey) if err != nil { - return nil, xerrors.Errorf("cannot create EK certificate: %w", err) + return nil, fmt.Errorf("cannot create EK certificate: %w", err) } return cert, nil @@ -150,10 +149,10 @@ func CertifyTPM(tpm *tpm2.TPMContext, ekCert []byte) error { Size: uint16(len(ekCert))} index, err := tpm.NVDefineSpace(tpm.PlatformHandleContext(), nil, &nvPub, nil) if err != nil { - return xerrors.Errorf("cannot define NV index for EK certificate: %w", err) + return fmt.Errorf("cannot define NV index for EK certificate: %w", err) } if err := tpm.NVWrite(tpm.PlatformHandleContext(), index, tpm2.MaxNVBuffer(ekCert), 0, nil); err != nil { - return xerrors.Errorf("cannot write EK certificate to NV index: %w", err) + return fmt.Errorf("cannot write EK certificate to NV index: %w", err) } return nil } diff --git a/keydata.go b/keydata.go index 19b0a992..78087309 100644 --- a/keydata.go +++ b/keydata.go @@ -358,7 +358,7 @@ func processPlatformHandlerError(err error) error { } } - return xerrors.Errorf("cannot perform action because of an unexpected error: %w", err) + return fmt.Errorf("cannot perform action because of an unexpected error: %w", err) } // KeyData represents a disk unlock key and auxiliary key protected by a platform's @@ -407,7 +407,7 @@ func (d *KeyData) derivePassphraseKeys(passphrase string) (key, iv, auth []byte, }) salt, err := builder.Bytes() if err != nil { - return nil, nil, nil, xerrors.Errorf("cannot serialize salt: %w", err) + return nil, nil, nil, fmt.Errorf("cannot serialize salt: %w", err) } costParams := &Argon2CostParams{ @@ -416,7 +416,7 @@ func (d *KeyData) derivePassphraseKeys(passphrase string) (key, iv, auth []byte, Threads: uint8(params.KDF.CPUs)} derived, err := argon2KDF().Derive(passphrase, salt, costParams, uint32(params.DerivedKeySize)) if err != nil { - return nil, nil, nil, xerrors.Errorf("cannot derive key from passphrase: %w", err) + return nil, nil, nil, fmt.Errorf("cannot derive key from passphrase: %w", err) } if len(derived) != params.DerivedKeySize { return nil, nil, nil, errors.New("KDF returned unexpected key length") @@ -425,19 +425,19 @@ func (d *KeyData) derivePassphraseKeys(passphrase string) (key, iv, auth []byte, key = make([]byte, params.EncryptionKeySize) r := hkdf.Expand(func() hash.Hash { return kdfAlg.New() }, derived, []byte("PASSPHRASE-ENC")) if _, err := io.ReadFull(r, key); err != nil { - return nil, nil, nil, xerrors.Errorf("cannot derive encryption key: %w", err) + return nil, nil, nil, fmt.Errorf("cannot derive encryption key: %w", err) } iv = make([]byte, aes.BlockSize) r = hkdf.Expand(func() hash.Hash { return kdfAlg.New() }, derived, []byte("PASSPHRASE-IV")) if _, err := io.ReadFull(r, iv); err != nil { - return nil, nil, nil, xerrors.Errorf("cannot derive IV: %w", err) + return nil, nil, nil, fmt.Errorf("cannot derive IV: %w", err) } auth = make([]byte, params.AuthKeySize) r = hkdf.Expand(func() hash.Hash { return kdfAlg.New() }, derived, []byte("PASSPHRASE-AUTH")) if _, err := io.ReadFull(r, auth); err != nil { - return nil, nil, nil, xerrors.Errorf("cannot derive auth key: %w", err) + return nil, nil, nil, fmt.Errorf("cannot derive auth key: %w", err) } return key, iv, auth, nil @@ -466,7 +466,7 @@ func (d *KeyData) updatePassphrase(payload, oldAuthKey []byte, passphrase string c, err := aes.NewCipher(key) if err != nil { - return xerrors.Errorf("cannot create cipher: %w", err) + return fmt.Errorf("cannot create cipher: %w", err) } d.data.PlatformHandle = handle @@ -493,7 +493,7 @@ func (d *KeyData) openWithPassphrase(passphrase string) (payload []byte, authKey c, err := aes.NewCipher(key) if err != nil { - return nil, nil, xerrors.Errorf("cannot create cipher: %w", err) + return nil, nil, fmt.Errorf("cannot create cipher: %w", err) } stream := cipher.NewCFBDecrypter(c, iv) stream.XORKeyStream(payload, d.data.EncryptedPayload) @@ -515,7 +515,7 @@ func (d *KeyData) recoverKeysCommon(data []byte) (DiskUnlockKey, PrimaryKey, err case 1: unlockKey, primaryKey, err := unmarshalV1KeyPayload(data) if err != nil { - return nil, nil, &InvalidKeyDataError{xerrors.Errorf("cannot unmarshal cleartext key payload: %w", err)} + return nil, nil, &InvalidKeyDataError{fmt.Errorf("cannot unmarshal cleartext key payload: %w", err)} } return unlockKey, primaryKey, nil case 2: @@ -524,7 +524,7 @@ func (d *KeyData) recoverKeysCommon(data []byte) (DiskUnlockKey, PrimaryKey, err } pk, err := unmarshalProtectedKeys(data) if err != nil { - return nil, nil, &InvalidKeyDataError{xerrors.Errorf("cannot unmarshal cleartext key payload: %w", err)} + return nil, nil, &InvalidKeyDataError{fmt.Errorf("cannot unmarshal cleartext key payload: %w", err)} } return pk.unlockKey(crypto.Hash(d.data.KDFAlg)), pk.Primary, nil default: @@ -560,7 +560,7 @@ func (d *KeyData) UniqueID() (KeyID, error) { h := crypto.SHA256.New() enc := json.NewEncoder(h) if err := enc.Encode(&d.data); err != nil { - return nil, xerrors.Errorf("cannot compute ID: %w", err) + return nil, fmt.Errorf("cannot compute ID: %w", err) } return KeyID(h.Sum(nil)), nil } @@ -685,11 +685,11 @@ func (d *KeyData) ChangePassphrase(oldPassphrase, newPassphrase string) error { func (d *KeyData) WriteAtomic(w KeyDataWriter) error { enc := json.NewEncoder(w) if err := enc.Encode(d.data); err != nil { - return xerrors.Errorf("cannot encode keydata: %w", err) + return fmt.Errorf("cannot encode keydata: %w", err) } if err := w.Commit(); err != nil { - return xerrors.Errorf("cannot commit keydata: %w", err) + return fmt.Errorf("cannot commit keydata: %w", err) } return nil @@ -701,7 +701,7 @@ func ReadKeyData(r KeyDataReader) (*KeyData, error) { d := &KeyData{readableName: r.ReadableName()} dec := json.NewDecoder(r) if err := dec.Decode(&d.data); err != nil { - return nil, xerrors.Errorf("cannot decode key data: %w", err) + return nil, fmt.Errorf("cannot decode key data: %w", err) } return d, nil @@ -714,7 +714,7 @@ func ReadKeyData(r KeyDataReader) (*KeyData, error) { func NewKeyData(params *KeyParams) (*KeyData, error) { encodedHandle, err := json.Marshal(params.Handle) if err != nil { - return nil, xerrors.Errorf("cannot encode platform handle: %w", err) + return nil, fmt.Errorf("cannot encode platform handle: %w", err) } kd := &KeyData{ @@ -749,12 +749,12 @@ func NewKeyDataWithPassphrase(params *KeyWithPassphraseParams, passphrase string costParams, err := kdfOptions.deriveCostParams(passphraseEncryptionKeyLen + aes.BlockSize) if err != nil { - return nil, xerrors.Errorf("cannot derive KDF cost parameters: %w", err) + return nil, fmt.Errorf("cannot derive KDF cost parameters: %w", err) } var salt [16]byte if _, err := rand.Read(salt[:]); err != nil { - return nil, xerrors.Errorf("cannot read salt: %w", err) + return nil, fmt.Errorf("cannot read salt: %w", err) } kd.data.PassphraseParams = &passphraseParams{ @@ -772,7 +772,7 @@ func NewKeyDataWithPassphrase(params *KeyWithPassphraseParams, passphrase string } if err := kd.updatePassphrase(kd.data.EncryptedPayload, make([]byte, params.AuthKeySize), passphrase); err != nil { - return nil, xerrors.Errorf("cannot set passphrase: %w", err) + return nil, fmt.Errorf("cannot set passphrase: %w", err) } return kd, nil @@ -831,7 +831,7 @@ func (k *protectedKeys) marshalASN1(builder *cryptobyte.Builder) { func MakeDiskUnlockKey(rand io.Reader, alg crypto.Hash, primaryKey PrimaryKey) (unlockKey DiskUnlockKey, cleartextPayload []byte, err error) { unique := make([]byte, len(primaryKey)) if _, err := io.ReadFull(rand, unique); err != nil { - return nil, nil, xerrors.Errorf("cannot make unique ID: %w", err) + return nil, nil, fmt.Errorf("cannot make unique ID: %w", err) } pk := &protectedKeys{ @@ -843,7 +843,7 @@ func MakeDiskUnlockKey(rand io.Reader, alg crypto.Hash, primaryKey PrimaryKey) ( pk.marshalASN1(builder) cleartextPayload, err = builder.Bytes() if err != nil { - return nil, nil, xerrors.Errorf("cannot marshal cleartext payload: %w", err) + return nil, nil, fmt.Errorf("cannot marshal cleartext payload: %w", err) } return pk.unlockKey(alg), cleartextPayload, nil diff --git a/keydata_file.go b/keydata_file.go index 5becd05f..e02a89a0 100644 --- a/keydata_file.go +++ b/keydata_file.go @@ -21,14 +21,13 @@ package secboot import ( "bytes" + "fmt" "io" "io/ioutil" "os" "github.com/snapcore/snapd/osutil" "github.com/snapcore/snapd/osutil/sys" - - "golang.org/x/xerrors" ) // FileKeyDataReader provides a mechanism to read a KeyData from a file. @@ -45,13 +44,13 @@ func (r *FileKeyDataReader) ReadableName() string { func NewFileKeyDataReader(path string) (*FileKeyDataReader, error) { f, err := os.Open(path) if err != nil { - return nil, xerrors.Errorf("cannot open file: %w", err) + return nil, fmt.Errorf("cannot open file: %w", err) } defer f.Close() d, err := ioutil.ReadAll(f) if err != nil { - return nil, xerrors.Errorf("cannot read file: %w", err) + return nil, fmt.Errorf("cannot read file: %w", err) } return &FileKeyDataReader{path, bytes.NewReader(d)}, nil @@ -66,16 +65,16 @@ type FileKeyDataWriter struct { func (w *FileKeyDataWriter) Commit() error { f, err := osutil.NewAtomicFile(w.path, 0600, 0, sys.UserID(osutil.NoChown), sys.GroupID(osutil.NoChown)) if err != nil { - return xerrors.Errorf("cannot create new atomic file: %w", err) + return fmt.Errorf("cannot create new atomic file: %w", err) } defer f.Cancel() if _, err := io.Copy(f, w); err != nil { - return xerrors.Errorf("cannot write file key data: %w", err) + return fmt.Errorf("cannot write file key data: %w", err) } if err := f.Commit(); err != nil { - return xerrors.Errorf("cannot commit update: %w", err) + return fmt.Errorf("cannot commit update: %w", err) } return nil diff --git a/keydata_legacy.go b/keydata_legacy.go index 0feebd9c..9cf17aa0 100644 --- a/keydata_legacy.go +++ b/keydata_legacy.go @@ -31,7 +31,6 @@ import ( drbg "github.com/canonical/go-sp800.90a-drbg" "golang.org/x/crypto/hkdf" - "golang.org/x/xerrors" ) var ( @@ -190,12 +189,12 @@ func (d *KeyData) snapModelHMACKeyLegacy(key PrimaryKey) ([]byte, error) { rng, err := drbg.NewCTRWithExternalEntropy(32, key, nil, snapModelHMACKDFLabel, nil) if err != nil { - return nil, xerrors.Errorf("cannot instantiate DRBG: %w", err) + return nil, fmt.Errorf("cannot instantiate DRBG: %w", err) } hmacKey := make([]byte, alg.Size()) if _, err := rng.Read(hmacKey); err != nil { - return nil, xerrors.Errorf("cannot derive key: %w", err) + return nil, fmt.Errorf("cannot derive key: %w", err) } return hmacKey, nil @@ -243,7 +242,7 @@ func (d *KeyData) IsSnapModelAuthorized(key PrimaryKey, model SnapModel) (bool, case 1: hmacKey, err := d.snapModelHMACKey(key) if err != nil { - return false, xerrors.Errorf("cannot obtain auth key: %w", err) + return false, fmt.Errorf("cannot obtain auth key: %w", err) } alg := d.data.AuthorizedSnapModels.alg @@ -253,7 +252,7 @@ func (d *KeyData) IsSnapModelAuthorized(key PrimaryKey, model SnapModel) (bool, h, err := computeSnapModelHMAC(crypto.Hash(alg), hmacKey, model) if err != nil { - return false, xerrors.Errorf("cannot compute HMAC of model: %w", err) + return false, fmt.Errorf("cannot compute HMAC of model: %w", err) } return d.data.AuthorizedSnapModels.hmacs.contains(h), nil @@ -280,7 +279,7 @@ func (d *KeyData) SetAuthorizedSnapModels(key PrimaryKey, models ...SnapModel) ( case 1: hmacKey, err := d.snapModelHMACKey(key) if err != nil { - return xerrors.Errorf("cannot obtain auth key: %w", err) + return fmt.Errorf("cannot obtain auth key: %w", err) } alg := d.data.AuthorizedSnapModels.keyDigest.Alg @@ -305,7 +304,7 @@ func (d *KeyData) SetAuthorizedSnapModels(key PrimaryKey, models ...SnapModel) ( for _, model := range models { h, err := computeSnapModelHMAC(crypto.Hash(alg), hmacKey, model) if err != nil { - return xerrors.Errorf("cannot compute HMAC of model: %w", err) + return fmt.Errorf("cannot compute HMAC of model: %w", err) } modelHMACs = append(modelHMACs, h) diff --git a/keydata_luks.go b/keydata_luks.go index 57630c6c..772454d9 100644 --- a/keydata_luks.go +++ b/keydata_luks.go @@ -22,8 +22,7 @@ package secboot import ( "bytes" "errors" - - "golang.org/x/xerrors" + "fmt" "github.com/snapcore/secboot/internal/luks2" "github.com/snapcore/secboot/internal/luksview" @@ -42,7 +41,7 @@ type LUKS2KeyDataReader struct { func NewLUKS2KeyDataReader(devicePath, name string) (*LUKS2KeyDataReader, error) { view, err := newLUKSView(devicePath, luks2.LockModeBlocking) if err != nil { - return nil, xerrors.Errorf("cannot obtain LUKS2 header view: %w", err) + return nil, fmt.Errorf("cannot obtain LUKS2 header view: %w", err) } token, _, exists := view.TokenByName(name) @@ -103,7 +102,7 @@ type LUKS2KeyDataWriter struct { func NewLUKS2KeyDataWriter(devicePath, name string) (*LUKS2KeyDataWriter, error) { view, err := newLUKSView(devicePath, luks2.LockModeBlocking) if err != nil { - return nil, xerrors.Errorf("cannot obtain LUKS2 header view: %w", err) + return nil, fmt.Errorf("cannot obtain LUKS2 header view: %w", err) } token, id, exists := view.TokenByName(name) diff --git a/snap.go b/snap.go index d5efe887..70956d82 100644 --- a/snap.go +++ b/snap.go @@ -26,11 +26,10 @@ import ( "encoding/asn1" "encoding/base64" "encoding/binary" + "fmt" "hash" "github.com/snapcore/snapd/asserts" - - "golang.org/x/xerrors" ) var sha3_384oid = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 2, 9} @@ -57,12 +56,12 @@ func computeSnapModelHMAC(alg crypto.Hash, key []byte, model SnapModel) (snapMod // changes to one with a different length. signKeyHashAlg, err := asn1.Marshal(sha3_384oid) if err != nil { - return nil, xerrors.Errorf("cannot marshal sign key hash algorithm: %w", err) + return nil, fmt.Errorf("cannot marshal sign key hash algorithm: %w", err) } signKeyId, err := base64.RawURLEncoding.DecodeString(model.SignKeyID()) if err != nil { - return nil, xerrors.Errorf("cannot decode signing key ID: %w", err) + return nil, fmt.Errorf("cannot decode signing key ID: %w", err) } h := hmac.New(func() hash.Hash { return alg.New() }, key) diff --git a/tools/gen-compattest-data/main.go b/tools/gen-compattest-data/main.go index 3e4705c1..25b836a6 100644 --- a/tools/gen-compattest-data/main.go +++ b/tools/gen-compattest-data/main.go @@ -87,7 +87,7 @@ func computePCRProtectionProfile(env secboot_efi.HostEnvironment) (*secboot_tpm2 } if err := secboot_efi.AddSecureBootPolicyProfile(profile, &sbpParams); err != nil { - return nil, xerrors.Errorf("cannot add secureboot policy profile: %w", err) + return nil, fmt.Errorf("cannot add secureboot policy profile: %w", err) } sdefisParams := secboot_efi.SystemdStubProfileParams{ @@ -100,19 +100,19 @@ func computePCRProtectionProfile(env secboot_efi.HostEnvironment) (*secboot_tpm2 } if err := secboot_efi.AddSystemdStubProfile(profile.RootBranch(), &sdefisParams); err != nil { - return nil, xerrors.Errorf("cannot add systemd EFI stub profile: %w", err) + return nil, fmt.Errorf("cannot add systemd EFI stub profile: %w", err) } modelData, err := ioutil.ReadFile("tools/gen-compattest-data/data/fake-model") if err != nil { - return nil, xerrors.Errorf("cannot read model assertion: %w", err) + return nil, fmt.Errorf("cannot read model assertion: %w", err) } model, err := asserts.Decode(modelData) if err != nil { - return nil, xerrors.Errorf("cannot decode model assertion: %w", err) + return nil, fmt.Errorf("cannot decode model assertion: %w", err) } smParams := secboot_tpm2.SnapModelProfileParams{ @@ -122,7 +122,7 @@ func computePCRProtectionProfile(env secboot_efi.HostEnvironment) (*secboot_tpm2 } if err := secboot_tpm2.AddSnapModelProfile(profile.RootBranch(), &smParams); err != nil { - return nil, xerrors.Errorf("cannot add snap model profile: %w", err) + return nil, fmt.Errorf("cannot add snap model profile: %w", err) } return profile, nil diff --git a/tools/make-efi-testdata/apps.go b/tools/make-efi-testdata/apps.go index 13991e0e..ec9379d5 100644 --- a/tools/make-efi-testdata/apps.go +++ b/tools/make-efi-testdata/apps.go @@ -10,8 +10,6 @@ import ( "path/filepath" "runtime" - "golang.org/x/xerrors" - efi "github.com/canonical/go-efilib" "github.com/snapcore/secboot/internal/testutil" ) @@ -157,7 +155,7 @@ func newMockAppDataAMD64(srcDir, vendorCertDir string, certs map[string][]byte) func makeOneMockApp(tmpDir, dstDir string, data *mockAppData, arch string) error { dir, err := ioutil.TempDir(tmpDir, "mockapp.") if err != nil { - return xerrors.Errorf("cannot create build directory: %w", err) + return fmt.Errorf("cannot create build directory: %w", err) } efiName := data.name + ".efi" @@ -188,19 +186,19 @@ func makeOneMockApp(tmpDir, dstDir string, data *mockAppData, arch string) error cmd.Stderr = os.Stderr if err := cmd.Run(); err != nil { - return xerrors.Errorf("make failed: %w", err) + return fmt.Errorf("make failed: %w", err) } for i, key := range data.signKeys { cert, err := ioutil.TempFile(tmpDir, "cert.") if err != nil { - return xerrors.Errorf("cannot create cert: %w", err) + return fmt.Errorf("cannot create cert: %w", err) } defer cert.Close() b := pem.Block{Type: "CERTIFICATE", Bytes: data.signCerts[i]} if _, err := cert.Write(pem.EncodeToMemory(&b)); err != nil { - return xerrors.Errorf("cannot write cert: %w", err) + return fmt.Errorf("cannot write cert: %w", err) } cert.Close() @@ -210,7 +208,7 @@ func makeOneMockApp(tmpDir, dstDir string, data *mockAppData, arch string) error cmd.Stderr = os.Stderr if err := cmd.Run(); err != nil { - return xerrors.Errorf("cannot sign app: %w", err) + return fmt.Errorf("cannot sign app: %w", err) } } @@ -224,7 +222,7 @@ func makeOneMockApp(tmpDir, dstDir string, data *mockAppData, arch string) error func writeShimVendorCertificates(certs map[string][]byte, dir string) error { for _, c := range []string{"TestShimVendorCA"} { if err := ioutil.WriteFile(filepath.Join(dir, c+".cer"), certs[c], 0644); err != nil { - return xerrors.Errorf("cannot write %s: %w", c, err) + return fmt.Errorf("cannot write %s: %w", c, err) } } @@ -244,7 +242,7 @@ func writeShimVendorCertificates(certs map[string][]byte, dir string) error { db.Write(buf) if err := ioutil.WriteFile(filepath.Join(dir, "TestShimVendorCA.esl"), buf.Bytes(), 0644); err != nil { - return xerrors.Errorf("cannot write TestShimVendorCA.esl: %w", err) + return fmt.Errorf("cannot write TestShimVendorCA.esl: %w", err) } return nil @@ -263,21 +261,21 @@ func makeMockApps(srcDir, dstDir string) error { certs, err := makeCertificates(srcDir) if err != nil { - return xerrors.Errorf("cannot make certificates: %w", err) + return fmt.Errorf("cannot make certificates: %w", err) } if err := writeShimVendorCertificates(certs, tmpDir); err != nil { - return xerrors.Errorf("cannot write certificates to tmpdir: %w", err) + return fmt.Errorf("cannot write certificates to tmpdir: %w", err) } for _, data := range newMockAppDataAMD64(srcDir, tmpDir, certs) { if err := makeOneMockApp(tmpDir, dstDir, &data, "amd64"); err != nil { - return xerrors.Errorf("cannot create %s: %w", data.name, err) + return fmt.Errorf("cannot create %s: %w", data.name, err) } } for _, data := range newMockAppData386(srcDir, tmpDir, certs) { if err := makeOneMockApp(tmpDir, dstDir, &data, "386"); err != nil { - return xerrors.Errorf("cannot create %s: %w", data.name, err) + return fmt.Errorf("cannot create %s: %w", data.name, err) } } diff --git a/tools/make-efi-testdata/buildenv.go b/tools/make-efi-testdata/buildenv.go index 2ae04066..afd22dc0 100644 --- a/tools/make-efi-testdata/buildenv.go +++ b/tools/make-efi-testdata/buildenv.go @@ -3,6 +3,7 @@ package main import ( "bufio" "bytes" + "fmt" "io/ioutil" "os/exec" "path/filepath" @@ -10,8 +11,6 @@ import ( "runtime" "strings" - "golang.org/x/xerrors" - "gopkg.in/yaml.v2" ) @@ -65,17 +64,17 @@ func addPackageAndDependenciesRecursively(env *buildEnv, name string) error { version, err := getCurrentPackageVersion(name) if err != nil { - return xerrors.Errorf("cannot determine version: %w", err) + return fmt.Errorf("cannot determine version: %w", err) } env.Packages[name] = version depends, err := getPackageDependencies(name) if err != nil { - return xerrors.Errorf("cannot determine dependencies: %w", err) + return fmt.Errorf("cannot determine dependencies: %w", err) } for _, depend := range depends { if err := addPackageAndDependenciesRecursively(env, depend); err != nil { - return xerrors.Errorf("cannot add package %s and its dependencies: %w", depend, err) + return fmt.Errorf("cannot add package %s and its dependencies: %w", depend, err) } } @@ -92,7 +91,7 @@ func addEssentialPackages(env *buildEnv) error { scanner := bufio.NewScanner(bytes.NewReader(output)) for scanner.Scan() { if err := addPackageAndDependenciesRecursively(env, scanner.Text()); err != nil { - return xerrors.Errorf("cannot add package %s: %w", scanner.Text(), err) + return fmt.Errorf("cannot add package %s: %w", scanner.Text(), err) } } @@ -122,15 +121,15 @@ func makeBuildEnvFromCurrent() (*buildEnv, error) { env.OsRelease[s[0]] = s[1] } if scanner.Err() != nil { - return nil, xerrors.Errorf("cannot scan /etc/os-release: %w", err) + return nil, fmt.Errorf("cannot scan /etc/os-release: %w", err) } if err := addEssentialPackages(env); err != nil { - return nil, xerrors.Errorf("cannot add essential packages: %w", err) + return nil, fmt.Errorf("cannot add essential packages: %w", err) } for _, dep := range packageDeps { if err := addPackageAndDependenciesRecursively(env, dep); err != nil { - return nil, xerrors.Errorf("cannot add package %s: %w", dep, err) + return nil, fmt.Errorf("cannot add package %s: %w", dep, err) } } diff --git a/tools/make-efi-testdata/certs.go b/tools/make-efi-testdata/certs.go index 8e102239..250c0582 100644 --- a/tools/make-efi-testdata/certs.go +++ b/tools/make-efi-testdata/certs.go @@ -13,8 +13,6 @@ import ( "path/filepath" "strings" "time" - - "golang.org/x/xerrors" ) type certData struct { @@ -191,7 +189,7 @@ func makeCertificate(srcDir string, certs map[string][]byte, data *certData) err for _, data := range certDatas { if data.name == data.issuer { if err := makeCertificate(srcDir, certs, &data); err != nil { - return xerrors.Errorf("cannot create issuer %s: %w", data.issuer, err) + return fmt.Errorf("cannot create issuer %s: %w", data.issuer, err) } issuerBytes = certs[data.issuer] break @@ -207,7 +205,7 @@ func makeCertificate(srcDir string, certs map[string][]byte, data *certData) err key, err := readRSAPrivateKey(filepath.Join(srcDir, "keys", data.name+".key")) if err != nil { - return xerrors.Errorf("cannot read key: %w", err) + return fmt.Errorf("cannot read key: %w", err) } pubKey := &key.PublicKey @@ -215,7 +213,7 @@ func makeCertificate(srcDir string, certs map[string][]byte, data *certData) err var err error key, err = readRSAPrivateKey(filepath.Join(srcDir, "keys", data.issuer+".key")) if err != nil { - return xerrors.Errorf("cannot read key: %w", err) + return fmt.Errorf("cannot read key: %w", err) } } @@ -242,7 +240,7 @@ func makeCertificates(srcDir string) (out map[string][]byte, err error) { for _, data := range certDatas { if err := makeCertificate(srcDir, out, &data); err != nil { - return nil, xerrors.Errorf("cannot make certificate: %s: %w", data.name, err) + return nil, fmt.Errorf("cannot make certificate: %s: %w", data.name, err) } } return out, nil @@ -256,10 +254,10 @@ func writeCertificates(srcDir, dstDir string) error { continue } if err := makeCertificate(srcDir, out, &data); err != nil { - return xerrors.Errorf("cannot make certificate %s: %w", data.name, err) + return fmt.Errorf("cannot make certificate %s: %w", data.name, err) } if err := ioutil.WriteFile(filepath.Join(dstDir, data.name+".cer"), out[data.name], 0644); err != nil { - return xerrors.Errorf("cannot write certificate %s: %w", data.name, err) + return fmt.Errorf("cannot write certificate %s: %w", data.name, err) } } @@ -271,7 +269,7 @@ func readSrcCertificates(srcDir string, certs map[string][]byte) error { for _, p := range paths { data, err := decodePEM(p, "CERTIFICATE") if err != nil { - return xerrors.Errorf("cannot decode %s: %w", p, err) + return fmt.Errorf("cannot decode %s: %w", p, err) } name := filepath.Base(strings.TrimSuffix(p, filepath.Ext(p))) diff --git a/tools/make-efi-testdata/main.go b/tools/make-efi-testdata/main.go index 3b5e8155..5479b1ee 100644 --- a/tools/make-efi-testdata/main.go +++ b/tools/make-efi-testdata/main.go @@ -6,8 +6,6 @@ import ( "path/filepath" drbg "github.com/canonical/go-sp800.90a-drbg" - - "golang.org/x/xerrors" ) var rngSeed = []byte{0x45, 0xef, 0xa4, 0xe4, 0x6a, 0xb7, 0x55, 0x14, 0xcd, 0xce, 0xc2, 0x17, 0x59, 0x77, 0x1a, 0x95, @@ -32,28 +30,28 @@ func run() error { srcDir, err := filepath.Abs(srcDir) if err != nil { - return xerrors.Errorf("cannot determine absolute srcdir: %w", err) + return fmt.Errorf("cannot determine absolute srcdir: %w", err) } if err := os.MkdirAll(dstDir, 0755); err != nil { - return xerrors.Errorf("cannot create destination directory: %w", err) + return fmt.Errorf("cannot create destination directory: %w", err) } // Avoid the host environment influencing the creation of the test data. if err := cleanEnv(); err != nil { - return xerrors.Errorf("cannot clean environment: %w", err) + return fmt.Errorf("cannot clean environment: %w", err) } if err := makeMockApps(srcDir, dstDir); err != nil { - return xerrors.Errorf("cannot create mock EFI apps: %w", err) + return fmt.Errorf("cannot create mock EFI apps: %w", err) } if err := writeCertificates(srcDir, dstDir); err != nil { - return xerrors.Errorf("cannot write certificates: %w", err) + return fmt.Errorf("cannot write certificates: %w", err) } if err := recordBuildEnv(dstDir); err != nil { - return xerrors.Errorf("cannot record build environment: %w", err) + return fmt.Errorf("cannot record build environment: %w", err) } return nil diff --git a/tpm2/key_sealer.go b/tpm2/key_sealer.go index 70e31af4..45e20fa3 100644 --- a/tpm2/key_sealer.go +++ b/tpm2/key_sealer.go @@ -20,11 +20,11 @@ package tpm2 import ( + "fmt" + "github.com/canonical/go-tpm2" "github.com/canonical/go-tpm2/templates" "github.com/canonical/go-tpm2/util" - - "golang.org/x/xerrors" ) // keySealer is an abstraction for creating a sealed key object @@ -57,7 +57,7 @@ func (s *sealedObjectKeySealer) CreateSealedObject(data []byte, nameAlg tpm2.Has case isAuthFailError(err, tpm2.AnyCommandCode, 1): return nil, nil, nil, AuthFailError{tpm2.HandleOwner} case err != nil: - return nil, nil, nil, xerrors.Errorf("cannot provision storage root key: %w", err) + return nil, nil, nil, fmt.Errorf("cannot provision storage root key: %w", err) } } @@ -76,7 +76,7 @@ func (s *sealedObjectKeySealer) CreateSealedObject(data []byte, nameAlg tpm2.Has priv, pub, _, _, _, err := s.tpm.Create(srk, &sensitive, template, nil, nil, s.tpm.HmacSession().IncludeAttrs(tpm2.AttrCommandEncrypt)) if err != nil { - return nil, nil, nil, xerrors.Errorf("cannot create sealed object: %w", err) + return nil, nil, nil, fmt.Errorf("cannot create sealed object: %w", err) } return priv, pub, nil, err } @@ -98,7 +98,7 @@ func (s *importableObjectKeySealer) CreateSealedObject(data []byte, nameAlg tpm2 // Now create the importable sealed key object (duplication object). _, priv, importSymSeed, err := util.CreateDuplicationObject(sensitive, pub, s.tpmKey, nil, nil) if err != nil { - return nil, nil, nil, xerrors.Errorf("cannot create duplication object: %w", err) + return nil, nil, nil, fmt.Errorf("cannot create duplication object: %w", err) } return priv, pub, importSymSeed, nil } diff --git a/tpm2/keydata.go b/tpm2/keydata.go index f5b35d1c..fed6a2e6 100644 --- a/tpm2/keydata.go +++ b/tpm2/keydata.go @@ -175,16 +175,16 @@ func (k *sealedKeyDataBase) validateData(tpm *tpm2.TPMContext, role string, sess srk, err := tpm.CreateResourceContextFromTPM(tcg.SRKHandle) if err != nil { - return nil, xerrors.Errorf("cannot create context for SRK: %w", err) + return nil, fmt.Errorf("cannot create context for SRK: %w", err) } // Load the sealed data object in to the TPM for integrity checking keyContext, err := k.load(tpm, srk, session) switch { case isLoadInvalidParamError(err) || isImportInvalidParamError(err): - return nil, keyDataError{xerrors.Errorf("cannot load sealed key object into TPM (sealed key object is bad or TPM owner has changed): %w", err)} + return nil, keyDataError{fmt.Errorf("cannot load sealed key object into TPM (sealed key object is bad or TPM owner has changed): %w", err)} case err != nil: - return nil, xerrors.Errorf("cannot load sealed key object into TPM: %w", err) + return nil, fmt.Errorf("cannot load sealed key object into TPM: %w", err) } // It's loaded ok, so we know that the private and public parts are consistent. tpm.FlushContext(keyContext) @@ -202,7 +202,7 @@ func (k *sealedKeyDataBase) validateData(tpm *tpm2.TPMContext, role string, sess // Read the public area of the PCR policy counter. pcrPolicyCounterPub, name, err := tpm.NVReadPublic(pcrPolicyCounter) if err != nil { - return nil, xerrors.Errorf("cannot read public area of PCR policy counter: %w", err) + return nil, fmt.Errorf("cannot read public area of PCR policy counter: %w", err) } if !bytes.Equal(name, pcrPolicyCounter.Name()) { return nil, errors.New("invalid PCR policy counter public area") diff --git a/tpm2/keydata_v0.go b/tpm2/keydata_v0.go index e21bb853..9ab3d5d0 100644 --- a/tpm2/keydata_v0.go +++ b/tpm2/keydata_v0.go @@ -29,8 +29,6 @@ import ( "github.com/canonical/go-tpm2/mu" "github.com/canonical/go-tpm2/util" "github.com/snapcore/secboot" - - "golang.org/x/xerrors" ) const keyPolicyUpdateDataHeader uint32 = 0x55534b50 @@ -48,7 +46,7 @@ func decodeKeyPolicyUpdateData(r io.Reader) (*keyPolicyUpdateData_v0, error) { var header uint32 var version uint32 if _, err := mu.UnmarshalFromReader(r, &header, &version); err != nil { - return nil, xerrors.Errorf("cannot unmarshal header: %w", err) + return nil, fmt.Errorf("cannot unmarshal header: %w", err) } if header != keyPolicyUpdateDataHeader { return nil, fmt.Errorf("unexpected header (%d)", header) @@ -59,7 +57,7 @@ func decodeKeyPolicyUpdateData(r io.Reader) (*keyPolicyUpdateData_v0, error) { var d keyPolicyUpdateData_v0 if _, err := mu.UnmarshalFromReader(r, &d); err != nil { - return nil, xerrors.Errorf("cannot unmarshal data: %w", err) + return nil, fmt.Errorf("cannot unmarshal data: %w", err) } return &d, nil @@ -112,23 +110,23 @@ func (d *keyData_v0) ValidateData(tpm *tpm2.TPMContext, role []byte, session tpm if tpm2.IsResourceUnavailableError(err, lockNVHandle) { return nil, keyDataError{errors.New("lock NV index is unavailable")} } - return nil, xerrors.Errorf("cannot create context for lock NV index: %w", err) + return nil, fmt.Errorf("cannot create context for lock NV index: %w", err) } lockNVPub, _, err := tpm.NVReadPublic(lockNV, session.IncludeAttrs(tpm2.AttrAudit)) if err != nil { - return nil, xerrors.Errorf("cannot read public area of lock NV index: %w", err) + return nil, fmt.Errorf("cannot read public area of lock NV index: %w", err) } lockNVPub.Attrs &^= tpm2.AttrNVReadLocked lockNVName, err := lockNVPub.ComputeName() if err != nil { - return nil, xerrors.Errorf("cannot compute name of lock NV index: %w", err) + return nil, fmt.Errorf("cannot compute name of lock NV index: %w", err) } // Validate the type and scheme of the dynamic authorization policy signing key. authPublicKey := d.PolicyData.StaticData.AuthPublicKey authKeyName, err := authPublicKey.ComputeName() if err != nil { - return nil, keyDataError{xerrors.Errorf("cannot compute name of dynamic authorization policy key: %w", err)} + return nil, keyDataError{fmt.Errorf("cannot compute name of dynamic authorization policy key: %w", err)} } if authPublicKey.Type != tpm2.ObjectTypeRSA { return nil, keyDataError{errors.New("public area of dynamic authorization policy signing key has the wrong type")} @@ -153,7 +151,7 @@ func (d *keyData_v0) ValidateData(tpm *tpm2.TPMContext, role []byte, session tpm if tpm2.IsResourceUnavailableError(err, pcrPolicyCounterHandle) { return nil, keyDataError{errors.New("PCR policy counter is unavailable")} } - return nil, xerrors.Errorf("cannot create context for PCR policy counter: %w", err) + return nil, fmt.Errorf("cannot create context for PCR policy counter: %w", err) } // Make sure that the static authorization policy data is consistent with the sealed key object's policy. @@ -172,7 +170,7 @@ func (d *keyData_v0) ValidateData(tpm *tpm2.TPMContext, role []byte, session tpm // Validate that the OR policy digests for the PCR policy counter match the public area of the index. pcrPolicyCounterPub, _, err := tpm.NVReadPublic(pcrPolicyCounter, session.IncludeAttrs(tpm2.AttrAudit)) if err != nil { - return nil, xerrors.Errorf("cannot read public area of PCR policy counter: %w", err) + return nil, fmt.Errorf("cannot read public area of PCR policy counter: %w", err) } if !pcrPolicyCounterPub.NameAlg.Available() { return nil, keyDataError{errors.New("cannot determine if PCR policy counter has a valid authorization policy: algorithm unavailable")} diff --git a/tpm2/keydata_v1.go b/tpm2/keydata_v1.go index 1dab191a..accfd61a 100644 --- a/tpm2/keydata_v1.go +++ b/tpm2/keydata_v1.go @@ -22,14 +22,13 @@ package tpm2 import ( "bytes" "errors" + "fmt" "io" "github.com/canonical/go-tpm2" "github.com/canonical/go-tpm2/mu" "github.com/canonical/go-tpm2/util" "github.com/snapcore/secboot" - - "golang.org/x/xerrors" ) // keyData_v1 represents version 1 of keyData. @@ -77,7 +76,7 @@ func (d *keyData_v1) ValidateData(tpm *tpm2.TPMContext, role []byte, session tpm authPublicKey := d.PolicyData.StaticData.AuthPublicKey authKeyName, err := authPublicKey.ComputeName() if err != nil { - return nil, keyDataError{xerrors.Errorf("cannot compute name of dynamic authorization policy key: %w", err)} + return nil, keyDataError{fmt.Errorf("cannot compute name of dynamic authorization policy key: %w", err)} } if authPublicKey.Type != tpm2.ObjectTypeECC { return nil, keyDataError{errors.New("public area of dynamic authorization policy signing key has the wrong type")} @@ -104,7 +103,7 @@ func (d *keyData_v1) ValidateData(tpm *tpm2.TPMContext, role []byte, session tpm if tpm2.IsResourceUnavailableError(err, pcrPolicyCounterHandle) { return nil, keyDataError{errors.New("PCR policy counter is unavailable")} } - return nil, xerrors.Errorf("cannot create context for PCR policy counter: %w", err) + return nil, fmt.Errorf("cannot create context for PCR policy counter: %w", err) } } diff --git a/tpm2/keydata_v3.go b/tpm2/keydata_v3.go index 4a8517df..46f0e46f 100644 --- a/tpm2/keydata_v3.go +++ b/tpm2/keydata_v3.go @@ -24,14 +24,13 @@ import ( "crypto/aes" "crypto/cipher" "errors" + "fmt" "io" "github.com/canonical/go-tpm2" "github.com/canonical/go-tpm2/mu" "github.com/canonical/go-tpm2/util" "github.com/snapcore/secboot" - - "golang.org/x/xerrors" ) type additionalData_v3 struct { @@ -104,7 +103,7 @@ func (d *keyData_v3) ValidateData(tpm *tpm2.TPMContext, role []byte, session tpm authPublicKey := d.PolicyData.StaticData.AuthPublicKey authKeyName, err := authPublicKey.ComputeName() if err != nil { - return nil, keyDataError{xerrors.Errorf("cannot compute name of dynamic authorization policy key: %w", err)} + return nil, keyDataError{fmt.Errorf("cannot compute name of dynamic authorization policy key: %w", err)} } if authPublicKey.Type != tpm2.ObjectTypeECC { return nil, keyDataError{errors.New("public area of dynamic authorization policy signing key has the wrong type")} @@ -131,7 +130,7 @@ func (d *keyData_v3) ValidateData(tpm *tpm2.TPMContext, role []byte, session tpm if tpm2.IsResourceUnavailableError(err, pcrPolicyCounterHandle) { return nil, keyDataError{errors.New("PCR policy counter is unavailable")} } - return nil, xerrors.Errorf("cannot create context for PCR policy counter: %w", err) + return nil, fmt.Errorf("cannot create context for PCR policy counter: %w", err) } } @@ -179,17 +178,17 @@ func (d *keyData_v3) Decrypt(key, payload []byte, generation uint32, kdfAlg tpm2 AuthMode: authMode, }) if err != nil { - return nil, xerrors.Errorf("cannot create AAD: %w", err) + return nil, fmt.Errorf("cannot create AAD: %w", err) } b, err := aes.NewCipher(key[:32]) if err != nil { - return nil, xerrors.Errorf("cannot create cipher: %w", err) + return nil, fmt.Errorf("cannot create cipher: %w", err) } aead, err := cipher.NewGCM(b) if err != nil { - return nil, xerrors.Errorf("cannot create AEAD cipher: %w", err) + return nil, fmt.Errorf("cannot create AEAD cipher: %w", err) } return aead.Open(nil, key[32:], payload, aad) diff --git a/tpm2/pcr_profile.go b/tpm2/pcr_profile.go index b282fc6c..fb593a5f 100644 --- a/tpm2/pcr_profile.go +++ b/tpm2/pcr_profile.go @@ -34,8 +34,6 @@ import ( "github.com/canonical/go-tpm2" "github.com/canonical/go-tpm2/mu" "github.com/canonical/go-tpm2/util" - - "golang.org/x/xerrors" ) // maxPCR is the maximum PCR index representable by a selection. A selection is a @@ -1099,7 +1097,7 @@ func (p *PCRProtectionProfile) ComputePCRValues(tpm *tpm2.TPMContext) ([]tpm2.PC var err error _, tpmValues, err = tpm.PCRRead(p.pcrsToReadFromTPM) if err != nil { - return nil, xerrors.Errorf("cannot read current PCR values from TPM: %w", err) + return nil, fmt.Errorf("cannot read current PCR values from TPM: %w", err) } } context := &pcrProtectionProfileComputer{ @@ -1126,7 +1124,7 @@ func (p *PCRProtectionProfile) ComputePCRDigests(tpm *tpm2.TPMContext, alg tpm2. // Compute the PCR selection for this profile from the first branch. pcrs, err := values[0].SelectionList() if err != nil { - return nil, nil, xerrors.Errorf("cannot compute selection list: %w", err) + return nil, nil, fmt.Errorf("cannot compute selection list: %w", err) } // Compute the PCR digests for all branches, making sure that they all contain values for the same sets of PCRs. @@ -1134,7 +1132,7 @@ func (p *PCRProtectionProfile) ComputePCRDigests(tpm *tpm2.TPMContext, alg tpm2. for _, v := range values { p, digest, err := util.ComputePCRDigestFromAllValues(alg, v) if err != nil { - return nil, nil, xerrors.Errorf("cannot compute PCR digest from values: %w", err) + return nil, nil, fmt.Errorf("cannot compute PCR digest from values: %w", err) } if !mu.DeepEqual(p, pcrs) { return nil, nil, errors.New("not all branches contain values for the same sets of PCRs") diff --git a/tpm2/platform.go b/tpm2/platform.go index a097b0e4..614e31c7 100644 --- a/tpm2/platform.go +++ b/tpm2/platform.go @@ -74,7 +74,7 @@ func (h *platformKeyDataHandler) recoverKeysCommon(data *secboot.PlatformKeyData Type: secboot.PlatformHandlerErrorUnavailable, Err: err} case err != nil: - return nil, xerrors.Errorf("cannot connect to TPM: %w", err) + return nil, fmt.Errorf("cannot connect to TPM: %w", err) } defer tpm.Close() @@ -99,14 +99,14 @@ func (h *platformKeyDataHandler) recoverKeysCommon(data *secboot.PlatformKeyData Type: secboot.PlatformHandlerErrorInvalidAuthKey, Err: err} } - return nil, xerrors.Errorf("cannot unseal key: %w", err) + return nil, fmt.Errorf("cannot unseal key: %w", err) } payload, err := k.data.Decrypt(symKey, encryptedPayload, uint32(data.Generation), kdfAlg, data.AuthMode) if err != nil { return nil, &secboot.PlatformHandlerError{ Type: secboot.PlatformHandlerErrorInvalidData, - Err: xerrors.Errorf("cannot recover encrypted payload: %w", err)} + Err: fmt.Errorf("cannot recover encrypted payload: %w", err)} } return payload, nil @@ -128,7 +128,7 @@ func (h *platformKeyDataHandler) ChangeAuthKey(data *secboot.PlatformKeyData, ol Type: secboot.PlatformHandlerErrorUnavailable, Err: err} case err != nil: - return nil, xerrors.Errorf("cannot connect to TPM: %w", err) + return nil, fmt.Errorf("cannot connect to TPM: %w", err) } defer tpm.Close() @@ -155,7 +155,7 @@ func (h *platformKeyDataHandler) ChangeAuthKey(data *secboot.PlatformKeyData, ol Type: secboot.PlatformHandlerErrorInvalidData, Err: err} case err != nil: - return nil, xerrors.Errorf("cannot validate key data: %w", err) + return nil, fmt.Errorf("cannot validate key data: %w", err) } srk, err := tpm.CreateResourceContextFromTPM(tcg.SRKHandle) @@ -165,7 +165,7 @@ func (h *platformKeyDataHandler) ChangeAuthKey(data *secboot.PlatformKeyData, ol Type: secboot.PlatformHandlerErrorUninitialized, Err: ErrTPMProvisioning} case err != nil: - return nil, xerrors.Errorf("cannot create context for SRK: %w", err) + return nil, fmt.Errorf("cannot create context for SRK: %w", err) } keyObject, err := k.load(tpm.TPMContext, srk, tpm.HmacSession()) @@ -174,7 +174,7 @@ func (h *platformKeyDataHandler) ChangeAuthKey(data *secboot.PlatformKeyData, ol // The supplied key data is invalid or is not protected by the supplied SRK. return nil, &secboot.PlatformHandlerError{ Type: secboot.PlatformHandlerErrorInvalidData, - Err: xerrors.Errorf("cannot load sealed key object into TPM: %w", err)} + Err: fmt.Errorf("cannot load sealed key object into TPM: %w", err)} case isLoadInvalidParentError(err) || isImportInvalidParentError(err): // The supplied SRK is not a valid storage parent. return nil, &secboot.PlatformHandlerError{ @@ -182,7 +182,7 @@ func (h *platformKeyDataHandler) ChangeAuthKey(data *secboot.PlatformKeyData, ol Err: ErrTPMProvisioning} case err != nil: // This is an unexpected error - return nil, xerrors.Errorf("cannot load sealed key object into TPM: %w", err) + return nil, fmt.Errorf("cannot load sealed key object into TPM: %w", err) } defer tpm.FlushContext(keyObject) @@ -202,7 +202,7 @@ func (h *platformKeyDataHandler) ChangeAuthKey(data *secboot.PlatformKeyData, ol // Validate the modified key. There's no reason for this to fail, but do it anyway. We haven't made // any persistent changes yet and still have an opportunity to back out. if _, err = k.validateData(tpm.TPMContext, data.Role, tpm.HmacSession()); err != nil { - return nil, xerrors.Errorf("cannot validate key data after auth value change: %w", err) + return nil, fmt.Errorf("cannot validate key data after auth value change: %w", err) } newHandle, err := json.Marshal(k) diff --git a/tpm2/platform_legacy.go b/tpm2/platform_legacy.go index 2f54bd64..24ef34c7 100644 --- a/tpm2/platform_legacy.go +++ b/tpm2/platform_legacy.go @@ -60,7 +60,7 @@ func (h *legacyPlatformKeyDataHandler) RecoverKeys(data *secboot.PlatformKeyData Type: secboot.PlatformHandlerErrorUnavailable, Err: err} case err != nil: - return nil, xerrors.Errorf("cannot connect to TPM: %w", err) + return nil, fmt.Errorf("cannot connect to TPM: %w", err) } defer tpm.Close() @@ -79,7 +79,7 @@ func (h *legacyPlatformKeyDataHandler) RecoverKeys(data *secboot.PlatformKeyData Type: secboot.PlatformHandlerErrorInvalidData, Err: err} } - return nil, xerrors.Errorf("cannot read key object: %w", err) + return nil, fmt.Errorf("cannot read key object: %w", err) } key, authKey, err := k.UnsealFromTPM(tpm) @@ -99,7 +99,7 @@ func (h *legacyPlatformKeyDataHandler) RecoverKeys(data *secboot.PlatformKeyData Type: secboot.PlatformHandlerErrorUnavailable, Err: err} } - return nil, xerrors.Errorf("cannot unseal key: %w", err) + return nil, fmt.Errorf("cannot unseal key: %w", err) } keys := &legacyProtectedKeys{ diff --git a/tpm2/policy.go b/tpm2/policy.go index f1ca2547..f784569c 100644 --- a/tpm2/policy.go +++ b/tpm2/policy.go @@ -24,6 +24,7 @@ import ( "crypto" _ "crypto/sha256" "errors" + "fmt" "github.com/canonical/go-tpm2" "github.com/canonical/go-tpm2/templates" @@ -522,10 +523,10 @@ func BlockPCRProtectionPolicies(tpm *Connection, pcrs []int) error { for _, pcr := range pcrs { seq, err := tpm.HashSequenceStart(nil, tpm2.HashAlgorithmNull) if err != nil { - return xerrors.Errorf("cannot being hash sequence: %w", err) + return fmt.Errorf("cannot being hash sequence: %w", err) } if _, err := tpm.EventSequenceExecute(tpm.PCRHandleContext(pcr), seq, fence, session, nil); err != nil { - return xerrors.Errorf("cannot execute hash sequence: %w", err) + return fmt.Errorf("cannot execute hash sequence: %w", err) } } diff --git a/tpm2/policy_v0.go b/tpm2/policy_v0.go index 87890508..741896e8 100644 --- a/tpm2/policy_v0.go +++ b/tpm2/policy_v0.go @@ -267,7 +267,7 @@ func (d *pcrPolicyData_v0) addPcrAssertions(alg tpm2.HashAlgorithmId, trial *uti orTree, err := newPolicyOrTree(alg, trial, orDigests) if err != nil { - return xerrors.Errorf("cannot create tree for PolicyOR digests: %w", err) + return fmt.Errorf("cannot create tree for PolicyOR digests: %w", err) } d.OrData = newPolicyOrDataV0(orTree) return nil @@ -301,10 +301,10 @@ func (d *pcrPolicyData_v0) executePcrAssertions(tpm *tpm2.TPMContext, session tp tree, err := d.OrData.resolve() if err != nil { - return policyDataError{xerrors.Errorf("cannot resolve PolicyOR tree: %w", err)} + return policyDataError{fmt.Errorf("cannot resolve PolicyOR tree: %w", err)} } if err := tree.executeAssertions(tpm, session); err != nil { - err = xerrors.Errorf("cannot execute PolicyOR assertions: %w", err) + err = fmt.Errorf("cannot execute PolicyOR assertions: %w", err) switch { case tpm2.IsTPMParameterError(err, tpm2.ErrorValue, tpm2.CommandPolicyOR, 1): // A digest list in the tree is invalid. @@ -333,7 +333,7 @@ func (d *pcrPolicyData_v0) executeRevocationCheck(tpm *tpm2.TPMContext, counter // Either StaticData.PCRPolicyCounterAuthPolicies is invalid or the NV index isn't what's expected, so the key file is invalid. return policyDataError{errors.New("invalid PCR policy counter or associated authorization policy metadata")} } - return xerrors.Errorf("cannot complete PCR policy revocation check: %w", err) + return fmt.Errorf("cannot complete PCR policy revocation check: %w", err) } return nil @@ -371,14 +371,14 @@ func (p *keyDataPolicy_v0) UpdatePCRPolicy(alg tpm2.HashAlgorithmId, params *pcr trial := util.ComputeAuthPolicy(alg) if err := pcrData.addPcrAssertions(alg, trial, params.pcrs, params.pcrDigests); err != nil { - return xerrors.Errorf("cannot compute base PCR policy: %w", err) + return fmt.Errorf("cannot compute base PCR policy: %w", err) } pcrData.addRevocationCheck(trial, params.policyCounterName, params.policySequence) key, err := x509.ParsePKCS1PrivateKey(params.key) if err != nil { - return xerrors.Errorf("cannot parse auth key: %w", err) + return fmt.Errorf("cannot parse auth key: %w", err) } scheme := &tpm2.SigScheme{ @@ -387,7 +387,7 @@ func (p *keyDataPolicy_v0) UpdatePCRPolicy(alg tpm2.HashAlgorithmId, params *pcr RSAPSS: &tpm2.SigSchemeRSAPSS{ HashAlg: p.StaticData.AuthPublicKey.NameAlg}}} if err := pcrData.authorizePolicy(key, scheme, trial.GetDigest(), nil); err != nil { - return xerrors.Errorf("cannot authorize policy: %w", err) + return fmt.Errorf("cannot authorize policy: %w", err) } p.PCRData = pcrData @@ -400,7 +400,7 @@ func (p *keyDataPolicy_v0) SetPCRPolicyFrom(src keyDataPolicy) { func (p *keyDataPolicy_v0) ExecutePCRPolicy(tpm *tpm2.TPMContext, policySession, hmacSession tpm2.SessionContext) error { if err := p.PCRData.executePcrAssertions(tpm, policySession); err != nil { - return xerrors.Errorf("cannot execute PCR assertions: %w", err) + return fmt.Errorf("cannot execute PCR assertions: %w", err) } pcrPolicyCounterHandle := p.StaticData.PCRPolicyCounterHandle @@ -436,14 +436,14 @@ func (p *keyDataPolicy_v0) ExecutePCRPolicy(tpm *tpm2.TPMContext, policySession, // for the v0 NV index. Because the v0 NV index was also used for the PIN, it needed an authorization policy to // permit using the counter value in an assertion without knowing the authorization value of the index. if err := tpm.PolicyCommandCode(revocationCheckSession, tpm2.CommandPolicyNV); err != nil { - return xerrors.Errorf("cannot execute assertion for PCR policy revocation check: %w", err) + return fmt.Errorf("cannot execute assertion for PCR policy revocation check: %w", err) } if err := tpm.PolicyOR(revocationCheckSession, p.StaticData.PCRPolicyCounterAuthPolicies); err != nil { if tpm2.IsTPMParameterError(err, tpm2.ErrorValue, tpm2.CommandPolicyOR, 1) { // StaticData.PCRPolicyCounterAuthPolicies is invalid. return policyDataError{errors.New("authorization policy metadata for PCR policy counter is invalid")} } - return xerrors.Errorf("cannot execute assertion for PCR policy revocation check: %w", err) + return fmt.Errorf("cannot execute assertion for PCR policy revocation check: %w", err) } if err := p.PCRData.executeRevocationCheck(tpm, pcrPolicyCounter, policySession, revocationCheckSession); err != nil { @@ -455,7 +455,7 @@ func (p *keyDataPolicy_v0) ExecutePCRPolicy(tpm *tpm2.TPMContext, policySession, if err != nil { if tpm2.IsTPMParameterError(err, tpm2.AnyErrorCode, tpm2.CommandLoadExternal, 2) { // StaticData.AuthPublicKey is invalid - return policyDataError{xerrors.Errorf("public area of dynamic authorization policy signing key is invalid: %w", err)} + return policyDataError{fmt.Errorf("public area of dynamic authorization policy signing key is invalid: %w", err)} } return err } @@ -463,14 +463,14 @@ func (p *keyDataPolicy_v0) ExecutePCRPolicy(tpm *tpm2.TPMContext, policySession, pcrPolicyDigest, err := util.ComputePolicyAuthorizeDigest(authPublicKey.NameAlg, p.PCRData.AuthorizedPolicy, nil) if err != nil { - return policyDataError{xerrors.Errorf("cannot compute PCR policy digest: %w", err)} + return policyDataError{fmt.Errorf("cannot compute PCR policy digest: %w", err)} } authorizeTicket, err := tpm.VerifySignature(authorizeKey, pcrPolicyDigest, p.PCRData.AuthorizedPolicySignature) if err != nil { if tpm2.IsTPMParameterError(err, tpm2.AnyErrorCode, tpm2.CommandVerifySignature, 2) { // PCRData.AuthorizedPolicySignature is invalid. - return policyDataError{xerrors.Errorf("cannot verify PCR policy signature: %w", err)} + return policyDataError{fmt.Errorf("cannot verify PCR policy signature: %w", err)} } return err } @@ -503,7 +503,7 @@ func (p *keyDataPolicy_v0) ExecutePCRPolicy(tpm *tpm2.TPMContext, policySession, return err } if err := tpm.PolicyNV(lockIndex, lockIndex, policySession, nil, 0, tpm2.OpEq, nil); err != nil { - return xerrors.Errorf("policy lock check failed: %w", err) + return fmt.Errorf("policy lock check failed: %w", err) } return nil @@ -540,7 +540,7 @@ func (c *pcrPolicyCounterContext_v0) Get() (uint64, error) { func (c *pcrPolicyCounterContext_v0) Increment(key secboot.PrimaryKey) error { rsaKey, err := x509.ParsePKCS1PrivateKey(key) if err != nil { - return xerrors.Errorf("cannot parse auth key: %w", err) + return fmt.Errorf("cannot parse auth key: %w", err) } // Begin a policy session to increment the index. @@ -567,7 +567,7 @@ func (c *pcrPolicyCounterContext_v0) Increment(key secboot.PrimaryKey) error { HashAlg: c.updateKey.NameAlg}}} signature, err := util.SignPolicyAuthorization(rsaKey, &scheme, policySession.NonceTPM(), nil, nil, 0) if err != nil { - return xerrors.Errorf("cannot sign authorization: %w", err) + return fmt.Errorf("cannot sign authorization: %w", err) } // See the comment for computeV0PinNVIndexPostInitAuthPolicies for a description of the authorization policy @@ -596,7 +596,7 @@ func (p *keyDataPolicy_v0) PCRPolicyCounterContext(tpm *tpm2.TPMContext, pub *tp index, err := tpm2.CreateNVIndexResourceContextFromPublic(pub) if err != nil { - return nil, xerrors.Errorf("cannot create context for NV index: %w", err) + return nil, fmt.Errorf("cannot create context for NV index: %w", err) } return &pcrPolicyCounterContext_v0{ @@ -610,7 +610,7 @@ func (p *keyDataPolicy_v0) PCRPolicyCounterContext(tpm *tpm2.TPMContext, pub *tp func (p *keyDataPolicy_v0) ValidateAuthKey(key secboot.PrimaryKey) error { rsaKey, err := x509.ParsePKCS1PrivateKey(key) if err != nil { - return xerrors.Errorf("cannot parse auth key: %w", err) + return fmt.Errorf("cannot parse auth key: %w", err) } pub, ok := p.StaticData.AuthPublicKey.Public().(*rsa.PublicKey) diff --git a/tpm2/policy_v1.go b/tpm2/policy_v1.go index 7681e29a..e680b213 100644 --- a/tpm2/policy_v1.go +++ b/tpm2/policy_v1.go @@ -29,8 +29,6 @@ import ( "github.com/canonical/go-tpm2/mu" "github.com/canonical/go-tpm2/util" - "golang.org/x/xerrors" - "github.com/snapcore/secboot" ) @@ -143,7 +141,7 @@ func (p *keyDataPolicy_v1) UpdatePCRPolicy(alg tpm2.HashAlgorithmId, params *pcr trial := util.ComputeAuthPolicy(alg) if err := pcrData.addPcrAssertions(alg, trial, params.pcrs, params.pcrDigests); err != nil { - return xerrors.Errorf("cannot compute base PCR policy: %w", err) + return fmt.Errorf("cannot compute base PCR policy: %w", err) } if params.policyCounterName != nil { @@ -152,7 +150,7 @@ func (p *keyDataPolicy_v1) UpdatePCRPolicy(alg tpm2.HashAlgorithmId, params *pcr key, err := createECDSAPrivateKeyFromTPM(p.StaticData.AuthPublicKey, tpm2.ECCParameter(params.key)) if err != nil { - return xerrors.Errorf("cannot create auth key: %w", err) + return fmt.Errorf("cannot create auth key: %w", err) } scheme := &tpm2.SigScheme{ @@ -161,7 +159,7 @@ func (p *keyDataPolicy_v1) UpdatePCRPolicy(alg tpm2.HashAlgorithmId, params *pcr ECDSA: &tpm2.SigSchemeECDSA{ HashAlg: p.StaticData.AuthPublicKey.NameAlg}}} if err := pcrData.authorizePolicy(key, scheme, trial.GetDigest(), computeV1PcrPolicyRefFromCounterName(params.policyCounterName)); err != nil { - return xerrors.Errorf("cannot authorize policy: %w", err) + return fmt.Errorf("cannot authorize policy: %w", err) } p.PCRData = pcrData @@ -174,7 +172,7 @@ func (p *keyDataPolicy_v1) SetPCRPolicyFrom(src keyDataPolicy) { func (p *keyDataPolicy_v1) ExecutePCRPolicy(tpm *tpm2.TPMContext, policySession, hmacSession tpm2.SessionContext) error { if err := p.PCRData.executePcrAssertions(tpm, policySession); err != nil { - return xerrors.Errorf("cannot execute PCR assertions: %w", err) + return fmt.Errorf("cannot execute PCR assertions: %w", err) } pcrPolicyCounterHandle := p.StaticData.PCRPolicyCounterHandle @@ -204,7 +202,7 @@ func (p *keyDataPolicy_v1) ExecutePCRPolicy(tpm *tpm2.TPMContext, policySession, if err != nil { if tpm2.IsTPMParameterError(err, tpm2.AnyErrorCode, tpm2.CommandLoadExternal, 2) { // StaticData.AuthPublicKey is invalid - return policyDataError{xerrors.Errorf("public area of dynamic authorization policy signing key is invalid: %w", err)} + return policyDataError{fmt.Errorf("public area of dynamic authorization policy signing key is invalid: %w", err)} } return err } @@ -214,14 +212,14 @@ func (p *keyDataPolicy_v1) ExecutePCRPolicy(tpm *tpm2.TPMContext, policySession, pcrPolicyDigest, err := util.ComputePolicyAuthorizeDigest(authPublicKey.NameAlg, p.PCRData.AuthorizedPolicy, pcrPolicyRef) if err != nil { - return policyDataError{xerrors.Errorf("cannot compute PCR policy digest: %w", err)} + return policyDataError{fmt.Errorf("cannot compute PCR policy digest: %w", err)} } authorizeTicket, err := tpm.VerifySignature(authorizeKey, pcrPolicyDigest, p.PCRData.AuthorizedPolicySignature) if err != nil { if tpm2.IsTPMParameterError(err, tpm2.AnyErrorCode, tpm2.CommandVerifySignature, 2) { // PCRData.AuthorizedPolicySignature is invalid. - return policyDataError{xerrors.Errorf("cannot verify PCR policy signature: %w", err)} + return policyDataError{fmt.Errorf("cannot verify PCR policy signature: %w", err)} } return err } @@ -261,7 +259,7 @@ func (c *pcrPolicyCounterContext_v1) Get() (uint64, error) { func (c *pcrPolicyCounterContext_v1) Increment(key secboot.PrimaryKey) error { ecdsaKey, err := createECDSAPrivateKeyFromTPM(c.updateKey, tpm2.ECCParameter(key)) if err != nil { - return xerrors.Errorf("cannot create auth key: %w", err) + return fmt.Errorf("cannot create auth key: %w", err) } // Begin a policy session to increment the index. @@ -288,7 +286,7 @@ func (c *pcrPolicyCounterContext_v1) Increment(key secboot.PrimaryKey) error { HashAlg: c.updateKey.NameAlg}}} signature, err := util.SignPolicyAuthorization(ecdsaKey, &scheme, policySession.NonceTPM(), nil, nil, 0) if err != nil { - return xerrors.Errorf("cannot sign authorization: %w", err) + return fmt.Errorf("cannot sign authorization: %w", err) } if _, _, err := c.tpm.PolicySigned(keyLoaded, policySession, true, nil, nil, 0, signature); err != nil { @@ -310,7 +308,7 @@ func (p *keyDataPolicy_v1) PCRPolicyCounterContext(tpm *tpm2.TPMContext, pub *tp index, err := tpm2.CreateNVIndexResourceContextFromPublic(pub) if err != nil { - return nil, xerrors.Errorf("cannot create context for NV index: %w", err) + return nil, fmt.Errorf("cannot create context for NV index: %w", err) } return &pcrPolicyCounterContext_v1{ diff --git a/tpm2/policy_v3.go b/tpm2/policy_v3.go index 3d0172f5..629161e0 100644 --- a/tpm2/policy_v3.go +++ b/tpm2/policy_v3.go @@ -33,7 +33,6 @@ import ( "github.com/canonical/go-tpm2/util" "golang.org/x/crypto/hkdf" - "golang.org/x/xerrors" "github.com/snapcore/secboot" internal_crypto "github.com/snapcore/secboot/internal/crypto" @@ -176,7 +175,7 @@ func (p *keyDataPolicy_v3) UpdatePCRPolicy(alg tpm2.HashAlgorithmId, params *pcr trial := util.ComputeAuthPolicy(alg) if err := pcrData.addPcrAssertions(alg, trial, params.pcrs, params.pcrDigests); err != nil { - return xerrors.Errorf("cannot compute base PCR policy: %w", err) + return fmt.Errorf("cannot compute base PCR policy: %w", err) } if params.policyCounterName != nil { @@ -185,7 +184,7 @@ func (p *keyDataPolicy_v3) UpdatePCRPolicy(alg tpm2.HashAlgorithmId, params *pcr key, err := deriveV3PolicyAuthKey(p.StaticData.AuthPublicKey.NameAlg.GetHash(), params.key) if err != nil { - return xerrors.Errorf("cannot derive auth key: %w", err) + return fmt.Errorf("cannot derive auth key: %w", err) } scheme := &tpm2.SigScheme{ @@ -194,7 +193,7 @@ func (p *keyDataPolicy_v3) UpdatePCRPolicy(alg tpm2.HashAlgorithmId, params *pcr ECDSA: &tpm2.SigSchemeECDSA{ HashAlg: p.StaticData.AuthPublicKey.NameAlg}}} if err := pcrData.authorizePolicy(key, scheme, trial.GetDigest(), p.StaticData.PCRPolicyRef); err != nil { - return xerrors.Errorf("cannot authorize policy: %w", err) + return fmt.Errorf("cannot authorize policy: %w", err) } p.PCRData = pcrData @@ -207,7 +206,7 @@ func (p *keyDataPolicy_v3) SetPCRPolicyFrom(src keyDataPolicy) { func (p *keyDataPolicy_v3) ExecutePCRPolicy(tpm *tpm2.TPMContext, policySession, hmacSession tpm2.SessionContext) error { if err := p.PCRData.executePcrAssertions(tpm, policySession); err != nil { - return xerrors.Errorf("cannot execute PCR assertions: %w", err) + return fmt.Errorf("cannot execute PCR assertions: %w", err) } pcrPolicyCounterHandle := p.StaticData.PCRPolicyCounterHandle @@ -237,7 +236,7 @@ func (p *keyDataPolicy_v3) ExecutePCRPolicy(tpm *tpm2.TPMContext, policySession, if err != nil { if tpm2.IsTPMParameterError(err, tpm2.AnyErrorCode, tpm2.CommandLoadExternal, 2) { // StaticData.AuthPublicKey is invalid - return policyDataError{xerrors.Errorf("public area of dynamic authorization policy signing key is invalid: %w", err)} + return policyDataError{fmt.Errorf("public area of dynamic authorization policy signing key is invalid: %w", err)} } return err } @@ -246,14 +245,14 @@ func (p *keyDataPolicy_v3) ExecutePCRPolicy(tpm *tpm2.TPMContext, policySession, pcrPolicyRef := p.StaticData.PCRPolicyRef pcrPolicyDigest, err := util.ComputePolicyAuthorizeDigest(authPublicKey.NameAlg, p.PCRData.AuthorizedPolicy, pcrPolicyRef) if err != nil { - return policyDataError{xerrors.Errorf("cannot compute PCR policy digest: %w", err)} + return policyDataError{fmt.Errorf("cannot compute PCR policy digest: %w", err)} } authorizeTicket, err := tpm.VerifySignature(authorizeKey, pcrPolicyDigest, p.PCRData.AuthorizedPolicySignature) if err != nil { if tpm2.IsTPMParameterError(err, tpm2.AnyErrorCode, tpm2.CommandVerifySignature, 2) { // PCRData.AuthorizedPolicySignature is invalid. - return policyDataError{xerrors.Errorf("cannot verify PCR policy signature: %w", err)} + return policyDataError{fmt.Errorf("cannot verify PCR policy signature: %w", err)} } return err } @@ -290,7 +289,7 @@ func (c *pcrPolicyCounterContext_v3) Get() (uint64, error) { func (c *pcrPolicyCounterContext_v3) Increment(key secboot.PrimaryKey) error { ecdsaKey, err := deriveV3PolicyAuthKey(c.updateKey.NameAlg.GetHash(), key) if err != nil { - return xerrors.Errorf("cannot derive auth key: %w", err) + return fmt.Errorf("cannot derive auth key: %w", err) } // Begin a policy session to increment the index. @@ -317,7 +316,7 @@ func (c *pcrPolicyCounterContext_v3) Increment(key secboot.PrimaryKey) error { HashAlg: c.updateKey.NameAlg}}} signature, err := util.SignPolicyAuthorization(ecdsaKey, &scheme, policySession.NonceTPM(), nil, []byte("PCR-POLICY-REVOKE"), 0) if err != nil { - return xerrors.Errorf("cannot sign authorization: %w", err) + return fmt.Errorf("cannot sign authorization: %w", err) } if _, _, err := c.tpm.PolicySigned(keyLoaded, policySession, true, nil, []byte("PCR-POLICY-REVOKE"), 0, signature); err != nil { @@ -342,7 +341,7 @@ func (p *keyDataPolicy_v3) PCRPolicyCounterContext(tpm *tpm2.TPMContext, pub *tp index, err := tpm2.CreateNVIndexResourceContextFromPublic(pub) if err != nil { - return nil, xerrors.Errorf("cannot create context for NV index: %w", err) + return nil, fmt.Errorf("cannot create context for NV index: %w", err) } return &pcrPolicyCounterContext_v3{ @@ -355,7 +354,7 @@ func (p *keyDataPolicy_v3) PCRPolicyCounterContext(tpm *tpm2.TPMContext, pub *tp func (p *keyDataPolicy_v3) ValidateAuthKey(key secboot.PrimaryKey) error { priv, err := deriveV3PolicyAuthKey(p.StaticData.AuthPublicKey.NameAlg.GetHash(), key) if err != nil { - return xerrors.Errorf("cannot derive private key: %w", err) + return fmt.Errorf("cannot derive private key: %w", err) } pub, ok := p.StaticData.AuthPublicKey.Public().(*ecdsa.PublicKey) diff --git a/tpm2/provisioning.go b/tpm2/provisioning.go index 42b9c523..13c75919 100644 --- a/tpm2/provisioning.go +++ b/tpm2/provisioning.go @@ -74,25 +74,25 @@ func provisionPrimaryKey(tpm *tpm2.TPMContext, hierarchy tpm2.ResourceContext, t switch { case err != nil && !tpm2.IsResourceUnavailableError(err, handle): // Unexpected error - return nil, xerrors.Errorf("cannot create context to determine if persistent handle is already occupied: %w", err) + return nil, fmt.Errorf("cannot create context to determine if persistent handle is already occupied: %w", err) case tpm2.IsResourceUnavailableError(err, handle): // No existing object to evict default: // Evict the current object if _, err := tpm.EvictControl(tpm.OwnerHandleContext(), obj, handle, session); err != nil { - return nil, xerrors.Errorf("cannot evict existing object at persistent handle: %w", err) + return nil, fmt.Errorf("cannot evict existing object at persistent handle: %w", err) } } transientObj, _, _, _, _, err := tpm.CreatePrimary(hierarchy, nil, template, nil, nil, session) if err != nil { - return nil, xerrors.Errorf("cannot create key: %w", err) + return nil, fmt.Errorf("cannot create key: %w", err) } defer tpm.FlushContext(transientObj) obj, err = tpm.EvictControl(tpm.OwnerHandleContext(), transientObj, handle, session) if err != nil { - return nil, xerrors.Errorf("cannot make key persistent: %w", err) + return nil, fmt.Errorf("cannot make key persistent: %w", err) } return obj, nil @@ -133,7 +133,7 @@ func provisionStoragePrimaryKey(tpm *tpm2.TPMContext, session tpm2.SessionContex func storeSrkTemplate(tpm *tpm2.TPMContext, template *tpm2.Public, session tpm2.SessionContext) error { tmplB, err := mu.MarshalToBytes(template) if err != nil { - return xerrors.Errorf("cannot marshal template: %w", err) + return fmt.Errorf("cannot marshal template: %w", err) } nvPub := tpm2.NVPublic{ @@ -143,15 +143,15 @@ func storeSrkTemplate(tpm *tpm2.TPMContext, template *tpm2.Public, session tpm2. Size: uint16(len(tmplB))} nv, err := tpm.NVDefineSpace(tpm.OwnerHandleContext(), nil, &nvPub, session) if err != nil { - return xerrors.Errorf("cannot define NV index: %w", err) + return fmt.Errorf("cannot define NV index: %w", err) } if err := tpm.NVWrite(nv, nv, tmplB, 0, session); err != nil { - return xerrors.Errorf("cannot write NV index: %w", err) + return fmt.Errorf("cannot write NV index: %w", err) } if err := tpm.NVWriteLock(nv, nv, session); err != nil { - return xerrors.Errorf("cannot write lock NV index: %w", err) + return fmt.Errorf("cannot write lock NV index: %w", err) } return nil @@ -162,14 +162,14 @@ func removeStoredSrkTemplate(tpm *tpm2.TPMContext, session tpm2.SessionContext) switch { case err != nil && !tpm2.IsResourceUnavailableError(err, srkTemplateHandle): // Unexpected error - return xerrors.Errorf("cannot create resource context: %w", err) + return fmt.Errorf("cannot create resource context: %w", err) case tpm2.IsResourceUnavailableError(err, srkTemplateHandle): // Ok, nothing to do return nil } if err := tpm.NVUndefineSpace(tpm.OwnerHandleContext(), nv, session); err != nil { - return xerrors.Errorf("cannot undefine index: %w", err) + return fmt.Errorf("cannot undefine index: %w", err) } return nil @@ -180,7 +180,7 @@ func (t *Connection) ensureProvisionedInternal(mode ProvisionMode, newLockoutAut props, err := t.GetCapabilityTPMProperties(tpm2.PropertyPermanent, 1, session.IncludeAttrs(tpm2.AttrAudit)) if err != nil { - return xerrors.Errorf("cannot fetch permanent properties: %w", err) + return fmt.Errorf("cannot fetch permanent properties: %w", err) } if props[0].Property != tpm2.PropertyPermanent { return errors.New("TPM returned value for the wrong property") @@ -197,7 +197,7 @@ func (t *Connection) ensureProvisionedInternal(mode ProvisionMode, newLockoutAut case tpm2.IsTPMWarning(err, tpm2.WarningLockout, tpm2.CommandClear): return ErrTPMLockout } - return xerrors.Errorf("cannot clear the TPM: %w", err) + return fmt.Errorf("cannot clear the TPM: %w", err) } } @@ -209,7 +209,7 @@ func (t *Connection) ensureProvisionedInternal(mode ProvisionMode, newLockoutAut case isAuthFailError(err, tpm2.AnyCommandCode, 1): return AuthFailError{tpm2.HandleEndorsement} default: - return xerrors.Errorf("cannot provision endorsement key: %w", err) + return fmt.Errorf("cannot provision endorsement key: %w", err) } } @@ -220,7 +220,7 @@ func (t *Connection) ensureProvisionedInternal(mode ProvisionMode, newLockoutAut if xerrors.As(err, &verifyErr) { return TPMVerificationError{fmt.Sprintf("cannot reinitialize TPM connection after provisioning endorsement key: %v", err)} } - return xerrors.Errorf("cannot reinitialize TPM connection after provisioning endorsement key: %w", err) + return fmt.Errorf("cannot reinitialize TPM connection after provisioning endorsement key: %w", err) } session = t.HmacSession() @@ -230,13 +230,13 @@ func (t *Connection) ensureProvisionedInternal(mode ProvisionMode, newLockoutAut // need to do this if mode == ProvisionModeClear because it will have already // been removed. if err := removeStoredSrkTemplate(t.TPMContext, session); err != nil { - return xerrors.Errorf("cannot remove stored custom SRK template: %w", err) + return fmt.Errorf("cannot remove stored custom SRK template: %w", err) } } if srkTemplate != nil { // Persist the new custom template if err := storeSrkTemplate(t.TPMContext, srkTemplate, session); err != nil { - return xerrors.Errorf("cannot store custom SRK template: %w", err) + return fmt.Errorf("cannot store custom SRK template: %w", err) } } @@ -246,7 +246,7 @@ func (t *Connection) ensureProvisionedInternal(mode ProvisionMode, newLockoutAut case isAuthFailError(err, tpm2.AnyCommandCode, 1): return AuthFailError{tpm2.HandleOwner} default: - return xerrors.Errorf("cannot provision storage root key: %w", err) + return fmt.Errorf("cannot provision storage root key: %w", err) } } t.provisionedSrk = srk @@ -254,7 +254,7 @@ func (t *Connection) ensureProvisionedInternal(mode ProvisionMode, newLockoutAut if mode == ProvisionModeWithoutLockout { props, err := t.GetCapabilityTPMProperties(tpm2.PropertyPermanent, 1, session.IncludeAttrs(tpm2.AttrAudit)) if err != nil { - return xerrors.Errorf("cannot fetch permanent properties to determine if lockout hierarchy is required: %w", err) + return fmt.Errorf("cannot fetch permanent properties to determine if lockout hierarchy is required: %w", err) } if props[0].Property != tpm2.PropertyPermanent { return errors.New("TPM returned value for the wrong property") @@ -266,7 +266,7 @@ func (t *Connection) ensureProvisionedInternal(mode ProvisionMode, newLockoutAut props, err = t.GetCapabilityTPMProperties(tpm2.PropertyMaxAuthFail, 3, session.IncludeAttrs(tpm2.AttrAudit)) if err != nil { - return xerrors.Errorf("cannot fetch DA parameters to determine if lockout hierarchy is required: %w", err) + return fmt.Errorf("cannot fetch DA parameters to determine if lockout hierarchy is required: %w", err) } if props[0].Property != tpm2.PropertyMaxAuthFail || props[1].Property != tpm2.PropertyLockoutInterval || props[2].Property != tpm2.PropertyLockoutRecovery { return errors.New("TPM returned values for the wrong properties") @@ -288,18 +288,18 @@ func (t *Connection) ensureProvisionedInternal(mode ProvisionMode, newLockoutAut case tpm2.IsTPMWarning(err, tpm2.WarningLockout, tpm2.CommandDictionaryAttackParameters): return ErrTPMLockout } - return xerrors.Errorf("cannot configure dictionary attack parameters: %w", err) + return fmt.Errorf("cannot configure dictionary attack parameters: %w", err) } // Disable owner clear if err := t.ClearControl(t.LockoutHandleContext(), true, session); err != nil { // Lockout auth failure or lockout mode would have been caught by DictionaryAttackParameters - return xerrors.Errorf("cannot disable owner clear: %w", err) + return fmt.Errorf("cannot disable owner clear: %w", err) } // Set the lockout hierarchy authorization. if err := t.HierarchyChangeAuth(t.LockoutHandleContext(), newLockoutAuth, session.IncludeAttrs(tpm2.AttrCommandEncrypt)); err != nil { - return xerrors.Errorf("cannot set the lockout hierarchy authorization value: %w", err) + return fmt.Errorf("cannot set the lockout hierarchy authorization value: %w", err) } return nil @@ -419,12 +419,12 @@ func (t *Connection) EnsureProvisioned(mode ProvisionMode, newLockoutAuth []byte func RequestTPMClearUsingPPI() error { f, err := os.OpenFile(ppiPath, os.O_WRONLY, 0) if err != nil { - return xerrors.Errorf("cannot open request handle: %w", err) + return fmt.Errorf("cannot open request handle: %w", err) } defer f.Close() if _, err := f.WriteString(clearPPIRequest); err != nil { - return xerrors.Errorf("cannot submit request: %w", err) + return fmt.Errorf("cannot submit request: %w", err) } return nil diff --git a/tpm2/seal.go b/tpm2/seal.go index 6bd1a7fc..b1c59ffa 100644 --- a/tpm2/seal.go +++ b/tpm2/seal.go @@ -25,12 +25,11 @@ import ( "crypto/cipher" "crypto/rand" "errors" + "fmt" "github.com/canonical/go-tpm2" "github.com/canonical/go-tpm2/mu" - "golang.org/x/xerrors" - "github.com/snapcore/secboot" ) @@ -109,14 +108,14 @@ func makeSealedKeyData(tpm *tpm2.TPMContext, params *makeSealedKeyDataParams, se if primaryKey == nil { primaryKey = make(secboot.PrimaryKey, 32) if _, err := rand.Read(primaryKey); err != nil { - return nil, nil, nil, xerrors.Errorf("cannot create primary key: %w", err) + return nil, nil, nil, fmt.Errorf("cannot create primary key: %w", err) } } // Create the key for authorizing PCR policy updates. authPublicKey, err := newPolicyAuthPublicKey(primaryKey) if err != nil { - return nil, nil, nil, xerrors.Errorf("cannot derive public area of key for signing dynamic authorization policies: %w", err) + return nil, nil, nil, fmt.Errorf("cannot derive public area of key for signing dynamic authorization policies: %w", err) } // Create PCR policy counter, if requested and if one doesn't already exist. @@ -134,7 +133,7 @@ func makeSealedKeyData(tpm *tpm2.TPMContext, params *makeSealedKeyDataParams, se case isAuthFailError(err, tpm2.CommandNVDefineSpace, 1): return nil, nil, nil, AuthFailError{tpm2.HandleOwner} case err != nil: - return nil, nil, nil, xerrors.Errorf("cannot create new PCR policy counter: %w", err) + return nil, nil, nil, fmt.Errorf("cannot create new PCR policy counter: %w", err) } } @@ -144,13 +143,13 @@ func makeSealedKeyData(tpm *tpm2.TPMContext, params *makeSealedKeyDataParams, se policyData, authPolicyDigest, err := newKeyDataPolicy(nameAlg, authPublicKey, params.Role, pcrPolicyCounterPub, requireAuthValue) if err != nil { - return nil, nil, nil, xerrors.Errorf("cannot create initial policy data: %w", err) + return nil, nil, nil, fmt.Errorf("cannot create initial policy data: %w", err) } // Create a 32 byte symmetric key and 12 byte nonce. var symKey [32 + 12]byte if _, err := rand.Read(symKey[:]); err != nil { - return nil, nil, nil, xerrors.Errorf("cannot create symmetric key: %w", err) + return nil, nil, nil, fmt.Errorf("cannot create symmetric key: %w", err) } // Seal the symmetric key and nonce. @@ -162,7 +161,7 @@ func makeSealedKeyData(tpm *tpm2.TPMContext, params *makeSealedKeyDataParams, se // Create a new SealedKeyData. data, err := newKeyData(priv, pub, importSymSeed, policyData) if err != nil { - return nil, nil, nil, xerrors.Errorf("cannot create key data: %w", err) + return nil, nil, nil, fmt.Errorf("cannot create key data: %w", err) } skd := &SealedKeyData{sealedKeyDataBase: sealedKeyDataBase{data: data}} @@ -172,14 +171,14 @@ func makeSealedKeyData(tpm *tpm2.TPMContext, params *makeSealedKeyDataParams, se pcrProfile = NewPCRProtectionProfile() } if err := skdbUpdatePCRProtectionPolicyNoValidate(&skd.sealedKeyDataBase, tpm, primaryKey, pcrPolicyCounterPub, pcrProfile, resetPcrPolicyVersion, session); err != nil { - return nil, nil, nil, xerrors.Errorf("cannot set initial PCR policy: %w", err) + return nil, nil, nil, fmt.Errorf("cannot set initial PCR policy: %w", err) } // Create the GCM encrypted payload. Use the name algorithm as the KDF algorithm here. kdfAlg := crypto.SHA256 unlockKey, payload, err := secboot.MakeDiskUnlockKey(rand.Reader, kdfAlg, primaryKey) if err != nil { - return nil, nil, nil, xerrors.Errorf("cannot create new unlock key: %w", err) + return nil, nil, nil, fmt.Errorf("cannot create new unlock key: %w", err) } // Serialize the AAD. Note that we don't protect the role parameter directly because it's @@ -190,23 +189,23 @@ func makeSealedKeyData(tpm *tpm2.TPMContext, params *makeSealedKeyDataParams, se AuthMode: params.AuthMode, }) if err != nil { - return nil, nil, nil, xerrors.Errorf("cannot create AAD: %w", err) + return nil, nil, nil, fmt.Errorf("cannot create AAD: %w", err) } b, err := aes.NewCipher(symKey[:32]) if err != nil { - return nil, nil, nil, xerrors.Errorf("cannot create new cipher: %w", err) + return nil, nil, nil, fmt.Errorf("cannot create new cipher: %w", err) } aead, err := cipher.NewGCM(b) if err != nil { - return nil, nil, nil, xerrors.Errorf("cannot create AEAD cipher: %w", err) + return nil, nil, nil, fmt.Errorf("cannot create AEAD cipher: %w", err) } ciphertext := aead.Seal(nil, symKey[32:], payload, aad) // Construct the secboot.KeyData object kd, err := constructor(skd, params.Role, ciphertext, kdfAlg) if err != nil { - return nil, nil, nil, xerrors.Errorf("cannot create key data object: %w", err) + return nil, nil, nil, fmt.Errorf("cannot create key data object: %w", err) } return kd, primaryKey, unlockKey, nil diff --git a/tpm2/seal_legacy.go b/tpm2/seal_legacy.go index 897b867b..3d9e8200 100644 --- a/tpm2/seal_legacy.go +++ b/tpm2/seal_legacy.go @@ -32,8 +32,6 @@ import ( "github.com/canonical/go-tpm2/mu" "github.com/canonical/go-tpm2/util" - "golang.org/x/xerrors" - "github.com/snapcore/secboot" ) @@ -123,7 +121,7 @@ func SealKeyToExternalTPMStorageKey(tpmKey *tpm2.Public, key secboot.DiskUnlockK } else { goAuthKey, err = ecdsa.GenerateKey(elliptic.P256(), rand.Reader) if err != nil { - return nil, xerrors.Errorf("cannot generate key for signing dynamic authorization policies: %w", err) + return nil, fmt.Errorf("cannot generate key for signing dynamic authorization policies: %w", err) } } authPublicKey := createTPMPublicAreaForECDSAKey(&goAuthKey.PublicKey) @@ -134,7 +132,7 @@ func SealKeyToExternalTPMStorageKey(tpmKey *tpm2.Public, key secboot.DiskUnlockK // Create the initial policy data policyData, authPolicy, err := newKeyDataPolicyLegacy(pub.NameAlg, authPublicKey, nil, 0) if err != nil { - return nil, xerrors.Errorf("cannot create initial policy data: %w", err) + return nil, fmt.Errorf("cannot create initial policy data: %w", err) } pub.AuthPolicy = authPolicy @@ -154,7 +152,7 @@ func SealKeyToExternalTPMStorageKey(tpmKey *tpm2.Public, key secboot.DiskUnlockK SeedValue: make(tpm2.Digest, pub.NameAlg.Size()), Sensitive: &tpm2.SensitiveCompositeU{Bits: sealedData}} if _, err := io.ReadFull(rand.Reader, sensitive.SeedValue); err != nil { - return nil, xerrors.Errorf("cannot create seed value: %w", err) + return nil, fmt.Errorf("cannot create seed value: %w", err) } // Compute the public ID @@ -166,14 +164,14 @@ func SealKeyToExternalTPMStorageKey(tpmKey *tpm2.Public, key secboot.DiskUnlockK // Now create the importable sealed key object (duplication object). _, priv, importSymSeed, err := util.CreateDuplicationObject(&sensitive, pub, tpmKey, nil, nil) if err != nil { - return nil, xerrors.Errorf("cannot create duplication object: %w", err) + return nil, fmt.Errorf("cannot create duplication object: %w", err) } w := NewFileSealedKeyObjectWriter(keyPath) data, err := newKeyData(priv, pub, importSymSeed, policyData) if err != nil { - return nil, xerrors.Errorf("cannot create key data: %w", err) + return nil, fmt.Errorf("cannot create key data: %w", err) } // Marshal the entire object (sealed key object and auxiliary data) to disk @@ -185,11 +183,11 @@ func SealKeyToExternalTPMStorageKey(tpmKey *tpm2.Public, key secboot.DiskUnlockK pcrProfile = NewPCRProtectionProfile() } if err := sko.updatePCRProtectionPolicyNoValidate(nil, authKey, nil, pcrProfile, resetPcrPolicyVersion, nil); err != nil { - return nil, xerrors.Errorf("cannot create initial PCR policy: %w", err) + return nil, fmt.Errorf("cannot create initial PCR policy: %w", err) } if err := sko.WriteAtomic(w); err != nil { - return nil, xerrors.Errorf("cannot write key data file: %w", err) + return nil, fmt.Errorf("cannot write key data file: %w", err) } return authKey, nil @@ -263,7 +261,7 @@ func SealKeyToTPMMultiple(tpm *Connection, keys []*SealKeyRequest, params *KeyCr case isAuthFailError(err, tpm2.AnyCommandCode, 1): return nil, AuthFailError{tpm2.HandleOwner} case err != nil: - return nil, xerrors.Errorf("cannot provision storage root key: %w", err) + return nil, fmt.Errorf("cannot provision storage root key: %w", err) } } @@ -281,7 +279,7 @@ func SealKeyToTPMMultiple(tpm *Connection, keys []*SealKeyRequest, params *KeyCr } else { goAuthKey, err = ecdsa.GenerateKey(elliptic.P256(), rand.Reader) if err != nil { - return nil, xerrors.Errorf("cannot generate key for signing dynamic authorization policies: %w", err) + return nil, fmt.Errorf("cannot generate key for signing dynamic authorization policies: %w", err) } } authPublicKey := createTPMPublicAreaForECDSAKey(&goAuthKey.PublicKey) @@ -298,7 +296,7 @@ func SealKeyToTPMMultiple(tpm *Connection, keys []*SealKeyRequest, params *KeyCr case isAuthFailError(err, tpm2.CommandNVDefineSpace, 1): return nil, AuthFailError{tpm2.HandleOwner} case err != nil: - return nil, xerrors.Errorf("cannot create new dynamic authorization policy counter: %w", err) + return nil, fmt.Errorf("cannot create new dynamic authorization policy counter: %w", err) } defer func() { if succeeded { @@ -317,7 +315,7 @@ func SealKeyToTPMMultiple(tpm *Connection, keys []*SealKeyRequest, params *KeyCr // Create the initial policy data policyData, authPolicy, err := newKeyDataPolicyLegacy(template.NameAlg, authPublicKey, pcrPolicyCounterPub, pcrPolicyCount) if err != nil { - return nil, xerrors.Errorf("cannot create initial policy data: %w", err) + return nil, fmt.Errorf("cannot create initial policy data: %w", err) } // Define the template for the sealed key object, using the computed policy digest @@ -347,14 +345,14 @@ func SealKeyToTPMMultiple(tpm *Connection, keys []*SealKeyRequest, params *KeyCr // command will fail. We take advantage of parameter encryption here too. priv, pub, _, _, _, err := tpm.Create(srk, &sensitive, template, nil, nil, session.IncludeAttrs(tpm2.AttrCommandEncrypt)) if err != nil { - return nil, xerrors.Errorf("cannot create sealed data object for key: %w", err) + return nil, fmt.Errorf("cannot create sealed data object for key: %w", err) } w := NewFileSealedKeyObjectWriter(key.Path) data, err := newKeyData(priv, pub, nil, policyData) if err != nil { - return nil, xerrors.Errorf("cannot create key data: %w", err) + return nil, fmt.Errorf("cannot create key data: %w", err) } // Marshal the entire object (sealed key object and auxiliary data) to disk @@ -368,12 +366,12 @@ func SealKeyToTPMMultiple(tpm *Connection, keys []*SealKeyRequest, params *KeyCr pcrProfile = NewPCRProtectionProfile() } if err := sko.updatePCRProtectionPolicyNoValidate(tpm.TPMContext, authKey, pcrPolicyCounterPub, pcrProfile, resetPcrPolicyVersion, session); err != nil { - return nil, xerrors.Errorf("cannot create initial PCR policy: %w", err) + return nil, fmt.Errorf("cannot create initial PCR policy: %w", err) } } if err := sko.WriteAtomic(w); err != nil { - return nil, xerrors.Errorf("cannot write key data file: %w", err) + return nil, fmt.Errorf("cannot write key data file: %w", err) } } diff --git a/tpm2/snapmodel_policy.go b/tpm2/snapmodel_policy.go index 85901104..81527a81 100644 --- a/tpm2/snapmodel_policy.go +++ b/tpm2/snapmodel_policy.go @@ -23,13 +23,12 @@ import ( "encoding/base64" "encoding/binary" "errors" + "fmt" "hash" "io" "github.com/canonical/go-tpm2" - "golang.org/x/xerrors" - "github.com/snapcore/secboot" ) @@ -83,7 +82,7 @@ func (h *tpmSnapModelHasher) Abort() { func computeSnapModelDigest(newHash func() (snapModelHasher, error), model secboot.SnapModel) (digest tpm2.Digest, err error) { signKeyId, err := base64.RawURLEncoding.DecodeString(model.SignKeyID()) if err != nil { - return nil, xerrors.Errorf("cannot decode signing key ID: %w", err) + return nil, fmt.Errorf("cannot decode signing key ID: %w", err) } h, err := newHash() @@ -198,7 +197,7 @@ func AddSnapModelProfile(branch *PCRProtectionProfileBranch, params *SnapModelPr func MeasureSnapSystemEpochToTPM(tpm *Connection, pcrIndex int) error { seq, err := tpm.HashSequenceStart(nil, tpm2.HashAlgorithmNull) if err != nil { - return xerrors.Errorf("cannot begin event sequence: %w", err) + return fmt.Errorf("cannot begin event sequence: %w", err) } var epoch [4]byte @@ -207,7 +206,7 @@ func MeasureSnapSystemEpochToTPM(tpm *Connection, pcrIndex int) error { binary.LittleEndian.PutUint32(epoch[:], zeroSnapSystemEpoch) if _, err := tpm.EventSequenceExecute(tpm.PCRHandleContext(pcrIndex), seq, epoch[:], tpm.HmacSession(), nil); err != nil { - return xerrors.Errorf("cannot execute event sequence: %w", err) + return fmt.Errorf("cannot execute event sequence: %w", err) } return nil @@ -219,7 +218,7 @@ func MeasureSnapSystemEpochToTPM(tpm *Connection, pcrIndex int) error { func MeasureSnapModelToTPM(tpm *Connection, pcrIndex int, model secboot.SnapModel) error { pcrSelection, err := tpm.GetCapabilityPCRs(tpm.HmacSession().IncludeAttrs(tpm2.AttrAudit)) if err != nil { - return xerrors.Errorf("cannot determine supported PCR banks: %w", err) + return fmt.Errorf("cannot determine supported PCR banks: %w", err) } var digests tpm2.TaggedHashList @@ -232,7 +231,7 @@ func MeasureSnapModelToTPM(tpm *Connection, pcrIndex int, model secboot.SnapMode return &tpmSnapModelHasher{tpm: tpm, seq: seq}, nil }, model) if err != nil { - return xerrors.Errorf("cannot compute digest for algorithm %v: %w", s.Hash, err) + return fmt.Errorf("cannot compute digest for algorithm %v: %w", s.Hash, err) } digests = append(digests, tpm2.MakeTaggedHash(s.Hash, digest)) diff --git a/tpm2/tpm.go b/tpm2/tpm.go index aa65fa68..971b699a 100644 --- a/tpm2/tpm.go +++ b/tpm2/tpm.go @@ -131,7 +131,7 @@ func (t *Connection) Close() error { func createTransientEk(tpm *tpm2.TPMContext) (tpm2.ResourceContext, error) { session, err := tpm.StartAuthSession(nil, tpm.EndorsementHandleContext(), tpm2.SessionTypeHMAC, nil, tpm2.HashAlgorithmSHA256) if err != nil { - return nil, xerrors.Errorf("cannot start auth session: %w", err) + return nil, fmt.Errorf("cannot start auth session: %w", err) } defer tpm.FlushContext(session) @@ -225,7 +225,7 @@ func (t *Connection) init() error { }() if err != nil { // A lack of EK should be fatal in this context - return xerrors.Errorf("cannot obtain context for EK: %w", err) + return fmt.Errorf("cannot obtain context for EK: %w", err) } ekIsPersistent := func() bool { @@ -263,7 +263,7 @@ func (t *Connection) init() error { return nil, err }() if err != nil { - return verificationError{xerrors.Errorf("cannot verify public area of endorsement key read from the TPM: %w", err)} + return verificationError{fmt.Errorf("cannot verify public area of endorsement key read from the TPM: %w", err)} } if rc != nil { // The persistent EK was bad, and we created and verified a transient EK instead @@ -273,7 +273,7 @@ func (t *Connection) init() error { // If we don't have a verified EK certificate and ek is a persistent object, just do a sanity check that the public area returned // from the TPM has the expected properties. If it doesn't, then don't use it, as TPM2_StartAuthSession might fail. if ok, err := isObjectPrimaryKeyWithTemplate(t.TPMContext, t.EndorsementHandleContext(), ek, tcg.EKTemplate, nil); err != nil { - return xerrors.Errorf("cannot determine if object is a primary key in the endorsement hierarchy: %w", err) + return fmt.Errorf("cannot determine if object is a primary key in the endorsement hierarchy: %w", err) } else if !ok { ek = nil } @@ -289,7 +289,7 @@ func (t *Connection) init() error { Mode: &tpm2.SymModeU{Sym: tpm2.SymModeCFB}} session, err := t.StartAuthSession(ek, nil, tpm2.SessionTypeHMAC, &symmetric, defaultSessionHashAlgorithm, nil) if err != nil { - return xerrors.Errorf("cannot create HMAC session: %w", err) + return fmt.Errorf("cannot create HMAC session: %w", err) } succeeded := false defer func() { @@ -305,7 +305,7 @@ func (t *Connection) init() error { if isAuthFailError(err, tpm2.CommandGetRandom, 1) { return verificationError{errors.New("endorsement key proof of ownership check failed")} } - return xerrors.Errorf("cannot execute command to complete EK proof of ownership check: %w", err) + return fmt.Errorf("cannot execute command to complete EK proof of ownership check: %w", err) } } @@ -323,17 +323,17 @@ func (t *Connection) init() error { func readEkCertFromTPM(tpm *tpm2.TPMContext) ([]byte, error) { ekCertIndex, err := tpm.CreateResourceContextFromTPM(tcg.EKCertHandle) if err != nil { - return nil, xerrors.Errorf("cannot create context: %w", err) + return nil, fmt.Errorf("cannot create context: %w", err) } ekCertPub, _, err := tpm.NVReadPublic(ekCertIndex) if err != nil { - return nil, xerrors.Errorf("cannot read public area of index: %w", err) + return nil, fmt.Errorf("cannot read public area of index: %w", err) } cert, err := tpm.NVRead(ekCertIndex, ekCertIndex, ekCertPub.Size, 0, nil) if err != nil { - return nil, xerrors.Errorf("cannot read index: %w", err) + return nil, fmt.Errorf("cannot read index: %w", err) } return cert, nil @@ -346,7 +346,7 @@ func connectToDefaultTPM() (*tpm2.TPMContext, error) { if isPathError(err) { return nil, ErrNoTPM2Device } - return nil, xerrors.Errorf("cannot open TPM device: %w", err) + return nil, fmt.Errorf("cannot open TPM device: %w", err) } tpm := tpm2.NewTPMContext(tcti) @@ -547,7 +547,7 @@ func verifyEkCertificate(data *ekCertData) ([]*x509.Certificate, *DeviceAttribut // Parse EK cert cert, err := x509.ParseCertificate(data.Cert) if err != nil { - return nil, nil, xerrors.Errorf("cannot parse endorsement key certificate: %w", err) + return nil, nil, fmt.Errorf("cannot parse endorsement key certificate: %w", err) } // Parse other certs, building root and intermediates store @@ -556,7 +556,7 @@ func verifyEkCertificate(data *ekCertData) ([]*x509.Certificate, *DeviceAttribut for _, d := range data.Parents { c, err := x509.ParseCertificate(d) if err != nil { - return nil, nil, xerrors.Errorf("cannot parse certificate: %w", err) + return nil, nil, fmt.Errorf("cannot parse certificate: %w", err) } if isCertificateTrustedCA(c) { roots.AddCert(c) @@ -586,7 +586,7 @@ func verifyEkCertificate(data *ekCertData) ([]*x509.Certificate, *DeviceAttribut attrs, attrsRDN, err = parseDeviceAttributesFromSAN(e.Value) // SubjectAltName MUST include TPM manufacturer, model and firmware version if err != nil { - return nil, nil, xerrors.Errorf("cannot parse TPM device attributes: %w", err) + return nil, nil, fmt.Errorf("cannot parse TPM device attributes: %w", err) } if len(cert.Subject.Names) == 0 { // If subject is empty, fill the Subject field with the TPM device attributes so that String() returns something useful @@ -624,7 +624,7 @@ func verifyEkCertificate(data *ekCertData) ([]*x509.Certificate, *DeviceAttribut KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageAny}} candidates, err := cert.Verify(opts) if err != nil { - return nil, nil, xerrors.Errorf("certificate verification failed: %w", err) + return nil, nil, fmt.Errorf("certificate verification failed: %w", err) } // Extended Key Usage MUST contain tcg-kp-EKCertificate (and also require that the usage is nested) @@ -672,16 +672,16 @@ func fetchParentCertificates(cert *x509.Certificate) ([][]byte, error) { if p, e := func(url string) (*x509.Certificate, error) { resp, err := client.Get(url) if err != nil { - return nil, xerrors.Errorf("GET request failed: %w", err) + return nil, fmt.Errorf("GET request failed: %w", err) } body, err := ioutil.ReadAll(resp.Body) resp.Body.Close() if err != nil { - return nil, xerrors.Errorf("cannot read body: %w", err) + return nil, fmt.Errorf("cannot read body: %w", err) } cert, err := x509.ParseCertificate(body) if err != nil { - return nil, xerrors.Errorf("cannot parse certificate: %w", err) + return nil, fmt.Errorf("cannot parse certificate: %w", err) } return cert, nil }(issuerUrl); e == nil { @@ -689,12 +689,12 @@ func fetchParentCertificates(cert *x509.Certificate) ([][]byte, error) { err = nil break } else { - err = xerrors.Errorf("download from %s failed: %w", issuerUrl, e) + err = fmt.Errorf("download from %s failed: %w", issuerUrl, e) } } if err != nil { - return nil, xerrors.Errorf("cannot download parent certificate of %v: %w", cert.Subject, err) + return nil, fmt.Errorf("cannot download parent certificate of %v: %w", cert.Subject, err) } out = append(out, parent.Raw) @@ -711,7 +711,7 @@ func fetchEkCertificateChain(tpm *tpm2.TPMContext, parentsOnly bool) (*ekCertDat var data ekCertData if cert, err := readEkCertFromTPM(tpm); err != nil { - return nil, xerrors.Errorf("cannot obtain endorsement key certificate from TPM: %w", err) + return nil, fmt.Errorf("cannot obtain endorsement key certificate from TPM: %w", err) } else { if !parentsOnly { data.Cert = cert @@ -719,12 +719,12 @@ func fetchEkCertificateChain(tpm *tpm2.TPMContext, parentsOnly bool) (*ekCertDat c, err := x509.ParseCertificate(cert) if err != nil { - return nil, xerrors.Errorf("cannot parse endorsement key certificate: %w", err) + return nil, fmt.Errorf("cannot parse endorsement key certificate: %w", err) } parents, err := fetchParentCertificates(c) if err != nil { - return nil, xerrors.Errorf("cannot obtain parent certificates for %s: %w", c.Subject, err) + return nil, fmt.Errorf("cannot obtain parent certificates for %s: %w", c.Subject, err) } data.Parents = parents } @@ -737,16 +737,16 @@ func fetchEkCertificateChain(tpm *tpm2.TPMContext, parentsOnly bool) (*ekCertDat func saveEkCertificateChain(data *ekCertData, dest string) error { f, err := osutil.NewAtomicFile(dest, 0600, 0, sys.UserID(osutil.NoChown), sys.GroupID(osutil.NoChown)) if err != nil { - return xerrors.Errorf("cannot create new atomic file: %w", err) + return fmt.Errorf("cannot create new atomic file: %w", err) } defer f.Cancel() if _, err := mu.MarshalToWriter(f, data); err != nil { - return xerrors.Errorf("cannot marshal cert chain: %w", err) + return fmt.Errorf("cannot marshal cert chain: %w", err) } if err := f.Commit(); err != nil { - return xerrors.Errorf("cannot atomically replace file: %w", err) + return fmt.Errorf("cannot atomically replace file: %w", err) } return nil @@ -813,7 +813,7 @@ func EncodeEKCertificateChain(ekCert *x509.Certificate, parents []*x509.Certific } if _, err := mu.MarshalToWriter(w, &data); err != nil { - return xerrors.Errorf("cannot marshal cert chain: %w", err) + return fmt.Errorf("cannot marshal cert chain: %w", err) } return nil @@ -844,7 +844,7 @@ func ConnectToDefaultTPM() (*Connection, error) { if err := t.init(); err != nil { var verifyErr verificationError if !tpm2.IsResourceUnavailableError(err, tpm2.AnyHandle) && !xerrors.As(err, &verifyErr) { - return nil, xerrors.Errorf("cannot initialize TPM connection: %w", err) + return nil, fmt.Errorf("cannot initialize TPM connection: %w", err) } } @@ -932,7 +932,7 @@ func SecureConnectToDefaultTPM(ekCertDataReader io.Reader, endorsementAuth []byt if xerrors.As(err, &verifyErr) { return nil, TPMVerificationError{err.Error()} } - return nil, xerrors.Errorf("cannot initialize TPM connection: %w", err) + return nil, fmt.Errorf("cannot initialize TPM connection: %w", err) } succeeded = true diff --git a/tpm2/tpm2_test.go b/tpm2/tpm2_test.go index 42d77f88..634eea9c 100644 --- a/tpm2/tpm2_test.go +++ b/tpm2/tpm2_test.go @@ -34,8 +34,6 @@ import ( "github.com/canonical/go-tpm2/mssim" tpm2_testutil "github.com/canonical/go-tpm2/testutil" - "golang.org/x/xerrors" - . "gopkg.in/check.v1" "github.com/snapcore/secboot/internal/tpm2test" @@ -108,14 +106,14 @@ func TestMain(m *testing.M) { if err := func() error { tcti, err := mssim.OpenConnection("", tpm2_testutil.MssimPort) if err != nil { - return xerrors.Errorf("cannot open connection: %w", err) + return fmt.Errorf("cannot open connection: %w", err) } tpm := tpm2.NewTPMContext(tcti) defer tpm.Close() testEkCert, err = tpm2test.CreateTestEKCert(tpm, testCACert, caKey) if err != nil { - return xerrors.Errorf("cannot create test EK certificate: %w", err) + return fmt.Errorf("cannot create test EK certificate: %w", err) } return tpm2test.CertifyTPM(tpm, testEkCert) }(); err != nil { diff --git a/tpm2/unseal.go b/tpm2/unseal.go index ca7371b6..9d022a40 100644 --- a/tpm2/unseal.go +++ b/tpm2/unseal.go @@ -24,8 +24,6 @@ import ( "github.com/canonical/go-tpm2" - "golang.org/x/xerrors" - "github.com/snapcore/secboot/internal/tcg" ) @@ -60,7 +58,7 @@ func (k *sealedKeyDataBase) loadForUnseal(tpm *tpm2.TPMContext, session tpm2.Ses continue } else if err != nil { // This is an unexpected error - return nil, xerrors.Errorf("cannot create context for SRK: %w", err) + return nil, fmt.Errorf("cannot create context for SRK: %w", err) } } else { var err error @@ -71,7 +69,7 @@ func (k *sealedKeyDataBase) loadForUnseal(tpm *tpm2.TPMContext, session tpm2.Ses continue } else if err != nil { // This is an unexpected error - return nil, xerrors.Errorf("cannot create transient SRK: %w", err) + return nil, fmt.Errorf("cannot create transient SRK: %w", err) } defer tpm.FlushContext(srk) } @@ -89,7 +87,7 @@ func (k *sealedKeyDataBase) loadForUnseal(tpm *tpm2.TPMContext, session tpm2.Ses continue } else if err != nil { // This is an unexpected error - return nil, xerrors.Errorf("cannot load sealed key object into TPM: %w", err) + return nil, fmt.Errorf("cannot load sealed key object into TPM: %w", err) } return keyObject, nil @@ -103,7 +101,7 @@ func (k *sealedKeyDataBase) unsealDataFromTPM(tpm *tpm2.TPMContext, authValue [] // Check if the TPM is in lockout mode props, err := tpm.GetCapabilityTPMProperties(tpm2.PropertyPermanent, 1) if err != nil { - return nil, xerrors.Errorf("cannot fetch properties from TPM: %w", err) + return nil, fmt.Errorf("cannot fetch properties from TPM: %w", err) } if tpm2.PermanentAttributes(props[0].Value)&tpm2.AttrInLockout > 0 { @@ -121,12 +119,12 @@ func (k *sealedKeyDataBase) unsealDataFromTPM(tpm *tpm2.TPMContext, authValue [] // Begin and execute policy session policySession, err := tpm.StartAuthSession(nil, nil, tpm2.SessionTypePolicy, nil, k.data.Public().NameAlg) if err != nil { - return nil, xerrors.Errorf("cannot start policy session: %w", err) + return nil, fmt.Errorf("cannot start policy session: %w", err) } defer tpm.FlushContext(policySession) if err := k.data.Policy().ExecutePCRPolicy(tpm, policySession, hmacSession); err != nil { - err = xerrors.Errorf("cannot complete authorization policy assertions: %w", err) + err = fmt.Errorf("cannot complete authorization policy assertions: %w", err) switch { case isPolicyDataError(err): return nil, InvalidKeyDataError{err.Error()} @@ -142,7 +140,7 @@ func (k *sealedKeyDataBase) unsealDataFromTPM(tpm *tpm2.TPMContext, authValue [] case tpm2.IsTPMSessionError(err, tpm2.ErrorPolicyFail, tpm2.CommandUnseal, 1): return nil, InvalidKeyDataError{"the authorization policy check failed during unsealing"} case err != nil: - return nil, xerrors.Errorf("cannot unseal key: %w", err) + return nil, fmt.Errorf("cannot unseal key: %w", err) } return data, nil diff --git a/tpm2/update.go b/tpm2/update.go index 3d68e60d..d483f5ec 100644 --- a/tpm2/update.go +++ b/tpm2/update.go @@ -25,8 +25,6 @@ import ( "github.com/canonical/go-tpm2" - "golang.org/x/xerrors" - "github.com/snapcore/secboot" ) @@ -88,12 +86,12 @@ func (k *sealedKeyDataBase) updatePCRProtectionPolicyNoValidate(tpm *tpm2.TPMCon case resetPcrPolicyVersion, newPcrPolicyVersion: counterContext, err := k.data.Policy().PCRPolicyCounterContext(tpm, counterPub, session) if err != nil { - return xerrors.Errorf("cannot obtain PCR policy counter context: %w", err) + return fmt.Errorf("cannot obtain PCR policy counter context: %w", err) } value, err := counterContext.Get() if err != nil { - return xerrors.Errorf("cannot obtain PCR policy counter value: %w", err) + return fmt.Errorf("cannot obtain PCR policy counter value: %w", err) } policySequence = value @@ -110,7 +108,7 @@ func (k *sealedKeyDataBase) updatePCRProtectionPolicyNoValidate(tpm *tpm2.TPMCon var err error supportedPcrs, err = tpm.GetCapabilityPCRs(session.IncludeAttrs(tpm2.AttrAudit)) if err != nil { - return xerrors.Errorf("cannot determine supported PCRs: %w", err) + return fmt.Errorf("cannot determine supported PCRs: %w", err) } } else { // Defined as mandatory in the TCG PC Client Platform TPM Profile Specification for TPM 2.0 @@ -124,7 +122,7 @@ func (k *sealedKeyDataBase) updatePCRProtectionPolicyNoValidate(tpm *tpm2.TPMCon // Compute PCR digests pcrs, pcrDigests, err := profile.ComputePCRDigests(tpm, alg) if err != nil { - return xerrors.Errorf("cannot compute PCR digests from protection profile: %w", err) + return fmt.Errorf("cannot compute PCR digests from protection profile: %w", err) } if len(pcrDigests) == 0 { @@ -169,13 +167,13 @@ func (k *sealedKeyDataBase) updatePCRProtectionPolicy(tpm *tpm2.TPMContext, auth if isKeyDataError(err) { return InvalidKeyDataError{err.Error()} } - return xerrors.Errorf("cannot validate key data: %w", err) + return fmt.Errorf("cannot validate key data: %w", err) } if err := k.data.Policy().ValidateAuthKey(authKey); err != nil { if isKeyDataError(err) { return InvalidKeyDataError{err.Error()} } - return xerrors.Errorf("cannot validate auth key: %w", err) + return fmt.Errorf("cannot validate auth key: %w", err) } if pcrProfile == nil { @@ -190,7 +188,7 @@ func (k *sealedKeyDataBase) revokeOldPCRProtectionPolicies(tpm *tpm2.TPMContext, if isKeyDataError(err) { return InvalidKeyDataError{err.Error()} } - return xerrors.Errorf("cannot validate key data: %w", err) + return fmt.Errorf("cannot validate key data: %w", err) } if pcrPolicyCounterPub == nil { @@ -201,7 +199,7 @@ func (k *sealedKeyDataBase) revokeOldPCRProtectionPolicies(tpm *tpm2.TPMContext, context, err := k.data.Policy().PCRPolicyCounterContext(tpm, pcrPolicyCounterPub, session) if err != nil { - return xerrors.Errorf("cannot create context for PCR policy counter: %w", err) + return fmt.Errorf("cannot create context for PCR policy counter: %w", err) } var lastCurrent uint64 @@ -210,7 +208,7 @@ func (k *sealedKeyDataBase) revokeOldPCRProtectionPolicies(tpm *tpm2.TPMContext, current, err := context.Get() switch { case err != nil: - return xerrors.Errorf("cannot read current value: %w", err) + return fmt.Errorf("cannot read current value: %w", err) case current > target: return errors.New("cannot set counter to a lower value") case current == lastCurrent && incremented: @@ -224,7 +222,7 @@ func (k *sealedKeyDataBase) revokeOldPCRProtectionPolicies(tpm *tpm2.TPMContext, lastCurrent = current if err := context.Increment(key); err != nil { - return xerrors.Errorf("cannot increment counter: %w", err) + return fmt.Errorf("cannot increment counter: %w", err) } incremented = true } @@ -272,10 +270,10 @@ func (o PCRPolicyVersionOption) internalOpt() pcrPolicyVersionOption { // from the supplied PCRProtectionProfile. It must be persisted using SealedKeyObject.WriteAtomic. func (k *SealedKeyData) UpdatePCRProtectionPolicy(tpm *Connection, authKey secboot.PrimaryKey, pcrProfile *PCRProtectionProfile, policyVersionOption PCRPolicyVersionOption) error { if err := k.updatePCRProtectionPolicy(tpm.TPMContext, authKey, k.k.Role(), pcrProfile, policyVersionOption.internalOpt(), tpm.HmacSession()); err != nil { - return xerrors.Errorf("cannot update PCR protection policy: %w", err) + return fmt.Errorf("cannot update PCR protection policy: %w", err) } if err := k.k.MarshalAndUpdatePlatformHandle(k); err != nil { - return xerrors.Errorf("cannot update TPM platform handle on KeyData: %w", err) + return fmt.Errorf("cannot update TPM platform handle on KeyData: %w", err) } return nil } @@ -322,11 +320,11 @@ func UpdateKeyDataPCRProtectionPolicy(tpm *Connection, authKey secboot.PrimaryKe for i, key := range keys { skd, err := NewSealedKeyData(key) if err != nil { - return xerrors.Errorf("cannot obtain SealedKeyData for key at index %d: %w", i, err) + return fmt.Errorf("cannot obtain SealedKeyData for key at index %d: %w", i, err) } if err := skd.UpdatePCRProtectionPolicy(tpm, authKey, pcrProfile, policyVersionOption); err != nil { - return xerrors.Errorf("cannot update key at index %d: %w", i, err) + return fmt.Errorf("cannot update key at index %d: %w", i, err) } } diff --git a/tpm2/update_legacy.go b/tpm2/update_legacy.go index f6c73aa0..d2272175 100644 --- a/tpm2/update_legacy.go +++ b/tpm2/update_legacy.go @@ -25,8 +25,6 @@ import ( "fmt" "os" - "golang.org/x/xerrors" - "github.com/snapcore/secboot" ) @@ -49,7 +47,7 @@ import ( func (k *SealedKeyObject) UpdatePCRProtectionPolicyV0(tpm *Connection, policyUpdatePath string, pcrProfile *PCRProtectionProfile) error { policyUpdateFile, err := os.Open(policyUpdatePath) if err != nil { - return xerrors.Errorf("cannot open private data file: %w", err) + return fmt.Errorf("cannot open private data file: %w", err) } defer policyUpdateFile.Close() @@ -82,7 +80,7 @@ func (k *SealedKeyObject) UpdatePCRProtectionPolicyV0(tpm *Connection, policyUpd func (k *SealedKeyObject) RevokeOldPCRProtectionPoliciesV0(tpm *Connection, policyUpdatePath string) error { policyUpdateFile, err := os.Open(policyUpdatePath) if err != nil { - return xerrors.Errorf("cannot open private data file: %w", err) + return fmt.Errorf("cannot open private data file: %w", err) } defer policyUpdateFile.Close() @@ -147,7 +145,7 @@ func UpdateKeyPCRProtectionPolicyMultiple(tpm *Connection, keys []*SealedKeyObje for i, key := range keys { if err := key.UpdatePCRProtectionPolicy(tpm, authKey, pcrProfile); err != nil { - return xerrors.Errorf("cannot update key at index %d: %w", i, err) + return fmt.Errorf("cannot update key at index %d: %w", i, err) } } @@ -163,7 +161,7 @@ func UpdateKeyPCRProtectionPolicyMultiple(tpm *Connection, keys []*SealedKeyObje if isKeyDataError(err) { return InvalidKeyDataError{fmt.Sprintf("%v (%d)", err.Error(), i+1)} } - return xerrors.Errorf("cannot validate related key data: %w", err) + return fmt.Errorf("cannot validate related key data: %w", err) } // The metadata is valid and consistent with the object's static authorization policy. // Verify that it also has the same static authorization policy as the first key object passed diff --git a/tpm2/utils.go b/tpm2/utils.go index a69b8760..ba2180b8 100644 --- a/tpm2/utils.go +++ b/tpm2/utils.go @@ -110,7 +110,7 @@ func isObjectPrimaryKeyWithTemplate(tpm *tpm2.TPMContext, hierarchy, object tpm2 if xerrors.As(err, &he) && he.Code == tpm2.ErrorHandle { return false, nil } - return false, xerrors.Errorf("cannot read public area of object: %w", err) + return false, fmt.Errorf("cannot read public area of object: %w", err) } pub.Unique = template.Unique From 8844fae70614f5d710227d8e90fb069c33592c38 Mon Sep 17 00:00:00 2001 From: Spyros Seimenis Date: Thu, 14 Mar 2024 17:57:45 +0200 Subject: [PATCH 2/4] multiple: replace xerrors.Is and As with errors.Is and As as of Go 1.13, Is, As and Unwrap have been incorporated into the standard library's errors package. --- crypt.go | 6 ++---- efi/pe.go | 3 +-- internal/keyring/keyring_test.go | 6 +++--- internal/luksview/tokens.go | 6 ++---- internal/testutil/checkers.go | 6 +++--- keydata.go | 3 +-- keyring.go | 6 ++---- tpm2/errors.go | 8 +++----- tpm2/keydata.go | 4 +--- tpm2/platform.go | 4 +--- tpm2/platform_legacy.go | 5 ++--- tpm2/policy.go | 4 +--- tpm2/policy_v0.go | 4 +--- tpm2/provisioning.go | 4 +--- tpm2/tpm.go | 6 ++---- tpm2/utils.go | 8 +++----- 16 files changed, 29 insertions(+), 54 deletions(-) diff --git a/crypt.go b/crypt.go index 84cd7e13..93e6a343 100755 --- a/crypt.go +++ b/crypt.go @@ -30,8 +30,6 @@ import ( "github.com/snapcore/snapd/asserts" - "golang.org/x/xerrors" - "github.com/snapcore/secboot/internal/keyring" "github.com/snapcore/secboot/internal/luks2" "github.com/snapcore/secboot/internal/luksview" @@ -253,13 +251,13 @@ func (s *activateWithKeyDataState) run() (success bool, err error) { continue } - if k.err != nil && !xerrors.Is(k.err, ErrInvalidPassphrase) { + if k.err != nil && !errors.Is(k.err, ErrInvalidPassphrase) { // Skip keys that failed for anything other than an invalid passphrase. continue } if err := s.tryKeyDataAuthModePassphrase(k.KeyData, k.slot, passphrase); err != nil { - if !xerrors.Is(err, ErrInvalidPassphrase) { + if !errors.Is(err, ErrInvalidPassphrase) { numPassphraseKeys -= 1 } k.err = err diff --git a/efi/pe.go b/efi/pe.go index d1b3703e..8e84db61 100644 --- a/efi/pe.go +++ b/efi/pe.go @@ -29,7 +29,6 @@ import ( "strconv" efi "github.com/canonical/go-efilib" - "golang.org/x/xerrors" pe "github.com/snapcore/secboot/internal/pe1.14" ) @@ -225,7 +224,7 @@ SignatureLoop: c, err := efi.ReadWinCertificate(certReader) switch { - case xerrors.Is(err, io.EOF): + case errors.Is(err, io.EOF): break SignatureLoop case err != nil: return nil, fmt.Errorf("cannot decode WIN_CERTIFICATE from security directory entry %d: %w", i, err) diff --git a/internal/keyring/keyring_test.go b/internal/keyring/keyring_test.go index ebcd6fea..3e1f2b68 100644 --- a/internal/keyring/keyring_test.go +++ b/internal/keyring/keyring_test.go @@ -20,6 +20,7 @@ package keyring_test import ( + "errors" "math/rand" "syscall" "testing" @@ -28,7 +29,6 @@ import ( "github.com/snapcore/secboot/internal/testutil" "golang.org/x/sys/unix" - "golang.org/x/xerrors" . "gopkg.in/check.v1" ) @@ -143,7 +143,7 @@ func (s *keyringSuite) TestGetKeyFromUserKeyringNoKey(c *C) { c.Check(err, ErrorMatches, "cannot find key: required key not available") var e syscall.Errno - c.Check(xerrors.As(err, &e), testutil.IsTrue) + c.Check(errors.As(err, &e), testutil.IsTrue) c.Check(e, Equals, syscall.ENOKEY) } @@ -180,6 +180,6 @@ func (s *keyringSuite) TestRemoveKeyFromUserKeyringNoKey(c *C) { c.Check(err, ErrorMatches, "cannot find key: required key not available") var e syscall.Errno - c.Check(xerrors.As(err, &e), testutil.IsTrue) + c.Check(errors.As(err, &e), testutil.IsTrue) c.Check(e, Equals, syscall.ENOKEY) } diff --git a/internal/luksview/tokens.go b/internal/luksview/tokens.go index b2c523a8..910a4d68 100644 --- a/internal/luksview/tokens.go +++ b/internal/luksview/tokens.go @@ -25,8 +25,6 @@ import ( "fmt" "strconv" - "golang.org/x/xerrors" - "github.com/snapcore/secboot/internal/luks2" ) @@ -44,13 +42,13 @@ func fallbackDecodeTokenHelper(data []byte, origErr error) (luks2.Token, error) switch { case origErr == nil: panic("asked to decode fallback token without an error") - case xerrors.Is(origErr, errOrphanedNamedToken): + case errors.Is(origErr, errOrphanedNamedToken): var token *orphanedToken if err := json.Unmarshal(data, &token); err != nil { return nil, err } return token, nil - case xerrors.Is(origErr, errInvalidNamedToken): + case errors.Is(origErr, errInvalidNamedToken): var token *luks2.GenericToken if err := json.Unmarshal(data, &token); err != nil { return nil, err diff --git a/internal/testutil/checkers.go b/internal/testutil/checkers.go index dd020483..fc60fa8e 100644 --- a/internal/testutil/checkers.go +++ b/internal/testutil/checkers.go @@ -20,9 +20,9 @@ package testutil import ( + "errors" "reflect" - "golang.org/x/xerrors" . "gopkg.in/check.v1" ) @@ -162,7 +162,7 @@ type errorIsChecker struct { } // ErrorIs determines whether any error in a chain has a specific -// value, using xerrors.Is +// value, using errors.Is // // For example: // @@ -181,5 +181,5 @@ func (checker *errorIsChecker) Check(params []interface{}, names []string) (resu return false, "expected is not an error" } - return xerrors.Is(err, expected), "" + return errors.Is(err, expected), "" } diff --git a/keydata.go b/keydata.go index 78087309..90dda7c5 100644 --- a/keydata.go +++ b/keydata.go @@ -34,7 +34,6 @@ import ( "golang.org/x/crypto/cryptobyte" cryptobyte_asn1 "golang.org/x/crypto/cryptobyte/asn1" "golang.org/x/crypto/hkdf" - "golang.org/x/xerrors" ) const ( @@ -345,7 +344,7 @@ type keyData struct { func processPlatformHandlerError(err error) error { var pe *PlatformHandlerError - if xerrors.As(err, &pe) { + if errors.As(err, &pe) { switch pe.Type { case PlatformHandlerErrorInvalidData: return &InvalidKeyDataError{pe.Err} diff --git a/keyring.go b/keyring.go index f4d07810..47a7e307 100644 --- a/keyring.go +++ b/keyring.go @@ -26,8 +26,6 @@ import ( "syscall" "github.com/snapcore/secboot/internal/keyring" - - "golang.org/x/xerrors" ) const ( @@ -56,7 +54,7 @@ func GetDiskUnlockKeyFromKernel(prefix, devicePath string, remove bool) (DiskUnl key, err := keyring.GetKeyFromUserKeyring(devicePath, keyringPurposeDiskUnlock, keyringPrefixOrDefault(prefix)) if err != nil { var e syscall.Errno - if xerrors.As(err, &e) && e == syscall.ENOKEY { + if errors.As(err, &e) && e == syscall.ENOKEY { return nil, ErrKernelKeyNotFound } return nil, err @@ -85,7 +83,7 @@ func GetPrimaryKeyFromKernel(prefix, devicePath string, remove bool) (PrimaryKey key, err := keyring.GetKeyFromUserKeyring(devicePath, keyringPurposeAuxiliary, keyringPrefixOrDefault(prefix)) if err != nil { var e syscall.Errno - if xerrors.As(err, &e) && e == syscall.ENOKEY { + if errors.As(err, &e) && e == syscall.ENOKEY { return nil, ErrKernelKeyNotFound } return nil, err diff --git a/tpm2/errors.go b/tpm2/errors.go index 4c9fe9f3..87f0b0c8 100644 --- a/tpm2/errors.go +++ b/tpm2/errors.go @@ -24,8 +24,6 @@ import ( "fmt" "github.com/canonical/go-tpm2" - - "golang.org/x/xerrors" ) var ( @@ -89,7 +87,7 @@ func (e EKCertVerificationError) Error() string { func isEKCertVerificationError(err error) bool { var e EKCertVerificationError - return xerrors.As(err, &e) + return errors.As(err, &e) } // TPMVerificationError is returned from SecureConnectToDefaultTPM if the TPM cannot prove it is the device for which the verified @@ -104,7 +102,7 @@ func (e TPMVerificationError) Error() string { func isTPMVerificationError(err error) bool { var e TPMVerificationError - return xerrors.As(err, &e) + return errors.As(err, &e) } // InvalidKeyDataError indicates that the provided key data file is invalid. This error may also be returned in some @@ -120,5 +118,5 @@ func (e InvalidKeyDataError) Error() string { func isInvalidKeyDataError(err error) bool { var e InvalidKeyDataError - return xerrors.As(err, &e) + return errors.As(err, &e) } diff --git a/tpm2/keydata.go b/tpm2/keydata.go index fed6a2e6..8e8d9628 100644 --- a/tpm2/keydata.go +++ b/tpm2/keydata.go @@ -29,8 +29,6 @@ import ( "github.com/canonical/go-tpm2" "github.com/canonical/go-tpm2/mu" - "golang.org/x/xerrors" - "github.com/snapcore/secboot" "github.com/snapcore/secboot/internal/tcg" ) @@ -49,7 +47,7 @@ func (e keyDataError) Unwrap() error { func isKeyDataError(err error) bool { var e keyDataError - return xerrors.As(err, &e) + return errors.As(err, &e) } // keyData represents the actual data for a SealedKeyData or legacy SealedKeyObject. diff --git a/tpm2/platform.go b/tpm2/platform.go index 614e31c7..4cc61669 100644 --- a/tpm2/platform.go +++ b/tpm2/platform.go @@ -28,8 +28,6 @@ import ( "github.com/canonical/go-tpm2" - "golang.org/x/xerrors" - "github.com/snapcore/secboot" "github.com/snapcore/secboot/internal/tcg" ) @@ -82,7 +80,7 @@ func (h *platformKeyDataHandler) recoverKeysCommon(data *secboot.PlatformKeyData if err != nil { var e InvalidKeyDataError switch { - case xerrors.As(err, &e): + case errors.As(err, &e): return nil, &secboot.PlatformHandlerError{ Type: secboot.PlatformHandlerErrorInvalidData, Err: errors.New(e.msg)} diff --git a/tpm2/platform_legacy.go b/tpm2/platform_legacy.go index 24ef34c7..32abf427 100644 --- a/tpm2/platform_legacy.go +++ b/tpm2/platform_legacy.go @@ -29,7 +29,6 @@ import ( "golang.org/x/crypto/cryptobyte" cryptobyte_asn1 "golang.org/x/crypto/cryptobyte/asn1" - "golang.org/x/xerrors" "github.com/snapcore/secboot" ) @@ -74,7 +73,7 @@ func (h *legacyPlatformKeyDataHandler) RecoverKeys(data *secboot.PlatformKeyData k, err := ReadSealedKeyObject(bytes.NewReader(handle)) if err != nil { var e InvalidKeyDataError - if xerrors.As(err, &e) { + if errors.As(err, &e) { return nil, &secboot.PlatformHandlerError{ Type: secboot.PlatformHandlerErrorInvalidData, Err: err} @@ -86,7 +85,7 @@ func (h *legacyPlatformKeyDataHandler) RecoverKeys(data *secboot.PlatformKeyData if err != nil { var e InvalidKeyDataError switch { - case xerrors.As(err, &e): + case errors.As(err, &e): return nil, &secboot.PlatformHandlerError{ Type: secboot.PlatformHandlerErrorInvalidData, Err: errors.New(e.msg)} diff --git a/tpm2/policy.go b/tpm2/policy.go index f784569c..0bdabb6c 100644 --- a/tpm2/policy.go +++ b/tpm2/policy.go @@ -30,8 +30,6 @@ import ( "github.com/canonical/go-tpm2/templates" "github.com/canonical/go-tpm2/util" - "golang.org/x/xerrors" - "github.com/snapcore/secboot" ) @@ -462,7 +460,7 @@ func (e policyDataError) Unwrap() error { func isPolicyDataError(err error) bool { var e policyDataError - return xerrors.As(err, &e) + return errors.As(err, &e) } var errSessionDigestNotFound = errors.New("current session digest not found in policy data") diff --git a/tpm2/policy_v0.go b/tpm2/policy_v0.go index 741896e8..ddd1b542 100644 --- a/tpm2/policy_v0.go +++ b/tpm2/policy_v0.go @@ -30,8 +30,6 @@ import ( "github.com/canonical/go-tpm2" "github.com/canonical/go-tpm2/util" - "golang.org/x/xerrors" - "github.com/snapcore/secboot" ) @@ -309,7 +307,7 @@ func (d *pcrPolicyData_v0) executePcrAssertions(tpm *tpm2.TPMContext, session tp case tpm2.IsTPMParameterError(err, tpm2.ErrorValue, tpm2.CommandPolicyOR, 1): // A digest list in the tree is invalid. return policyDataError{errors.New("cannot execute PolicyOR assertions: invalid data")} - case xerrors.Is(err, errSessionDigestNotFound): + case errors.Is(err, errSessionDigestNotFound): // Current session digest does not appear in any leaf node. return policyDataError{err} default: diff --git a/tpm2/provisioning.go b/tpm2/provisioning.go index 13c75919..51eb1399 100644 --- a/tpm2/provisioning.go +++ b/tpm2/provisioning.go @@ -27,8 +27,6 @@ import ( "github.com/canonical/go-tpm2" "github.com/canonical/go-tpm2/mu" - "golang.org/x/xerrors" - "github.com/snapcore/secboot/internal/tcg" ) @@ -217,7 +215,7 @@ func (t *Connection) ensureProvisionedInternal(mode ProvisionMode, newLockoutAut // This will have a symmetric algorithm for parameter encryption during HierarchyChangeAuth. if err := t.init(); err != nil { var verifyErr verificationError - if xerrors.As(err, &verifyErr) { + if errors.As(err, &verifyErr) { return TPMVerificationError{fmt.Sprintf("cannot reinitialize TPM connection after provisioning endorsement key: %v", err)} } return fmt.Errorf("cannot reinitialize TPM connection after provisioning endorsement key: %w", err) diff --git a/tpm2/tpm.go b/tpm2/tpm.go index 971b699a..c97c20f1 100644 --- a/tpm2/tpm.go +++ b/tpm2/tpm.go @@ -42,8 +42,6 @@ import ( "github.com/snapcore/snapd/osutil" "github.com/snapcore/snapd/osutil/sys" - "golang.org/x/xerrors" - "github.com/snapcore/secboot/internal/tcg" "github.com/snapcore/secboot/internal/tcti" "github.com/snapcore/secboot/internal/truststore" @@ -843,7 +841,7 @@ func ConnectToDefaultTPM() (*Connection, error) { if err := t.init(); err != nil { var verifyErr verificationError - if !tpm2.IsResourceUnavailableError(err, tpm2.AnyHandle) && !xerrors.As(err, &verifyErr) { + if !tpm2.IsResourceUnavailableError(err, tpm2.AnyHandle) && !errors.As(err, &verifyErr) { return nil, fmt.Errorf("cannot initialize TPM connection: %w", err) } } @@ -929,7 +927,7 @@ func SecureConnectToDefaultTPM(ekCertDataReader io.Reader, endorsementAuth []byt return nil, ErrTPMProvisioning } var verifyErr verificationError - if xerrors.As(err, &verifyErr) { + if errors.As(err, &verifyErr) { return nil, TPMVerificationError{err.Error()} } return nil, fmt.Errorf("cannot initialize TPM connection: %w", err) diff --git a/tpm2/utils.go b/tpm2/utils.go index ba2180b8..1c307bc6 100644 --- a/tpm2/utils.go +++ b/tpm2/utils.go @@ -31,13 +31,11 @@ import ( "github.com/canonical/go-tpm2" "github.com/canonical/go-tpm2/mu" - - "golang.org/x/xerrors" ) func isPathError(err error) bool { var e *os.PathError - return xerrors.As(err, &e) + return errors.As(err, &e) } // isAuthFailError indicates whether the specified error is a TPM authorization check failure, with or without DA implications. @@ -88,7 +86,7 @@ func (e *tpmErrorWithHandle) Unwrap() error { // isTpmErrorWithHandle indicates whether the specified error is a *tpmErrorWithHandle. func isTpmErrorWithHandle(err error) bool { var e *tpmErrorWithHandle - return xerrors.As(err, &e) + return errors.As(err, &e) } // isObjectPrimaryKeyWithTemplate checks whether the object associated with context is primary key in the specified hierarchy with @@ -107,7 +105,7 @@ func isObjectPrimaryKeyWithTemplate(tpm *tpm2.TPMContext, hierarchy, object tpm2 pub, _, qualifiedName, err := tpm.ReadPublic(object, session) if err != nil { var he *tpm2.TPMHandleError - if xerrors.As(err, &he) && he.Code == tpm2.ErrorHandle { + if errors.As(err, &he) && he.Code == tpm2.ErrorHandle { return false, nil } return false, fmt.Errorf("cannot read public area of object: %w", err) From 7285fbe0fb02f65fd120596c7b8c24f0b88dd39f Mon Sep 17 00:00:00 2001 From: Spyros Seimenis Date: Thu, 14 Mar 2024 18:16:55 +0200 Subject: [PATCH 3/4] go.mod, go.sum: ran go mod tidy --- go.mod | 2 +- go.sum | 6 ------ 2 files changed, 1 insertion(+), 7 deletions(-) diff --git a/go.mod b/go.mod index feb17558..86b6cb32 100644 --- a/go.mod +++ b/go.mod @@ -11,7 +11,6 @@ require ( github.com/snapcore/snapd v0.0.0-20220714152900-4a1f4c93fc85 golang.org/x/crypto v0.9.0 golang.org/x/sys v0.8.0 - golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c gopkg.in/yaml.v2 v2.3.0 maze.io/x/crypto v0.0.0-20190131090603-9b94c9afe066 @@ -23,6 +22,7 @@ require ( github.com/kr/text v0.1.0 // indirect github.com/snapcore/go-gettext v0.0.0-20191107141714-82bbea49e785 // indirect golang.org/x/net v0.10.0 // indirect + golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 // indirect gopkg.in/retry.v1 v1.0.3 // indirect gopkg.in/tomb.v2 v2.0.0-20161208151619-d5d1b5820637 // indirect ) diff --git a/go.sum b/go.sum index 9caf132b..03317da1 100644 --- a/go.sum +++ b/go.sum @@ -2,8 +2,6 @@ github.com/bsiegert/ranges v0.0.0-20111221115336-19303dc7aa63/go.mod h1:8z71/aZj github.com/canonical/go-efilib v0.0.0-20210909101908-41435fa545d4/go.mod h1:9Sr9kd7IhQPYqaU5nut8Ky97/CtlhHDzQncQnrULgDM= github.com/canonical/go-efilib v0.3.0/go.mod h1:9b2PNAuPcZsB76x75/uwH99D8CyH/A2y4rq1/+bvplg= github.com/canonical/go-efilib v0.3.1-0.20220314143719-95d50e8afc82/go.mod h1:9b2PNAuPcZsB76x75/uwH99D8CyH/A2y4rq1/+bvplg= -github.com/canonical/go-efilib v0.9.4 h1:cD6oNSWeQSgeSeJZMCxhGEW4GoLSxFhIJ12Hg3vFCtU= -github.com/canonical/go-efilib v0.9.4/go.mod h1:tHjv3Mni7hEpNSUNd1KJEV/AZJsFSH6LX/EQ0I75AZE= github.com/canonical/go-efilib v0.9.5 h1:zRpWG4z61GiYsEmFYvXYuj+8xV2eJ200YY5Ht9EjrRU= github.com/canonical/go-efilib v0.9.5/go.mod h1:tHjv3Mni7hEpNSUNd1KJEV/AZJsFSH6LX/EQ0I75AZE= github.com/canonical/go-sp800.108-kdf v0.0.0-20210314145419-a3359f2d21b9/go.mod h1:Zrs3YjJr+w51u0R/dyLh/oWt/EcBVdLPCVFYC4daW5s= @@ -13,10 +11,6 @@ github.com/canonical/go-sp800.90a-drbg v0.0.0-20210314144037-6eeb1040d6c3 h1:oe6 github.com/canonical/go-sp800.90a-drbg v0.0.0-20210314144037-6eeb1040d6c3/go.mod h1:qdP0gaj0QtgX2RUZhnlVrceJ+Qln8aSlDyJwelLLFeM= github.com/canonical/go-tpm2 v0.0.0-20210827151749-f80ff5afff61/go.mod h1:vG41hdbBjV4+/fkubTT1ENBBqSkLwLr7mCeW9Y6kpZY= github.com/canonical/go-tpm2 v0.1.0/go.mod h1:vG41hdbBjV4+/fkubTT1ENBBqSkLwLr7mCeW9Y6kpZY= -github.com/canonical/go-tpm2 v1.0.2 h1:2HNCI/UKghbVaR8Ix1BEcK6G/GzKlkOoBSXNc7R7mLw= -github.com/canonical/go-tpm2 v1.0.2/go.mod h1:FD6TavnteNqLZv1m3meU0QighLDmfyEq5+ShiN2Ik64= -github.com/canonical/go-tpm2 v1.1.0 h1:i3YeiYTWciamtbUpKZC9FIGhCP9rWSu1AZpYnWUO9HE= -github.com/canonical/go-tpm2 v1.1.0/go.mod h1:kLkR1//7ocrPDl6LZfijTKEoPGxRIZSbb8GuWaO1JM8= github.com/canonical/go-tpm2 v1.3.0 h1:+xc2++IM4kaMCJruFzlgtYgQyV5Q0EReaP++z8VTqJk= github.com/canonical/go-tpm2 v1.3.0/go.mod h1:kLkR1//7ocrPDl6LZfijTKEoPGxRIZSbb8GuWaO1JM8= github.com/canonical/tcglog-parser v0.0.0-20210824131805-69fa1e9f0ad2/go.mod h1:QoW2apR2tBl6T/4czdND/EHjL1Ia9cCmQnIj9Xe0Kt8= From 99c8824b616754c59062691fa1120af7958c44e6 Mon Sep 17 00:00:00 2001 From: Spyros Seimenis Date: Fri, 22 Mar 2024 18:07:05 +0200 Subject: [PATCH 4/4] i/tpm2test/ekcert.go: fix typo in verb used as format string in Errorf --- internal/tpm2test/ekcert.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/internal/tpm2test/ekcert.go b/internal/tpm2test/ekcert.go index 51cab265..660d3c98 100644 --- a/internal/tpm2test/ekcert.go +++ b/internal/tpm2test/ekcert.go @@ -103,7 +103,7 @@ func CreateTestEKCert(tpm *tpm2.TPMContext, caCert []byte, caKey crypto.PrivateK pkix.AttributeTypeAndValue{Type: tcg.OIDTcgAttributeTpmVersion, Value: "id:00010002"}}} tpmDeviceAttrData, err := asn1.Marshal(tpmDeviceAttrValues) if err != nil { - return nil, fmt.Errorf("cannot marshal SAN value: %2", err) + return nil, fmt.Errorf("cannot marshal SAN value: %w", err) } sanData, err := asn1.Marshal([]asn1.RawValue{ asn1.RawValue{Class: asn1.ClassContextSpecific, Tag: tcg.SANDirectoryNameTag, IsCompound: true, Bytes: tpmDeviceAttrData}})