Bump github.com/containers/ocicrypt from 1.1.6 to 1.1.7

Bumps [github.com/containers/ocicrypt](https://github.com/containers/ocicrypt) from 1.1.6 to 1.1.7.
- [Release notes](https://github.com/containers/ocicrypt/releases)
- [Commits](https://github.com/containers/ocicrypt/compare/v1.1.6...v1.1.7)

---
updated-dependencies:
- dependency-name: github.com/containers/ocicrypt
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
This commit is contained in:
dependabot[bot] 2023-01-19 09:03:20 +00:00 committed by GitHub
parent b51eb214c2
commit 63da8390f1
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
27 changed files with 247 additions and 236 deletions

2
go.mod
View File

@ -5,7 +5,7 @@ go 1.17
require (
github.com/containers/common v0.50.1
github.com/containers/image/v5 v5.23.1-0.20230113185223-cf9ccfb4d9b1
github.com/containers/ocicrypt v1.1.6
github.com/containers/ocicrypt v1.1.7
github.com/containers/storage v1.45.1
github.com/docker/distribution v2.8.1+incompatible
github.com/opencontainers/go-digest v1.0.0

3
go.sum
View File

@ -930,8 +930,9 @@ github.com/containers/ocicrypt v1.1.1/go.mod h1:Dm55fwWm1YZAjYRaJ94z2mfZikIyIN4B
github.com/containers/ocicrypt v1.1.2/go.mod h1:Dm55fwWm1YZAjYRaJ94z2mfZikIyIN4B0oB3dj3jFxY=
github.com/containers/ocicrypt v1.1.3/go.mod h1:xpdkbVAuaH3WzbEabUd5yDsl9SwJA5pABH85425Es2g=
github.com/containers/ocicrypt v1.1.5/go.mod h1:WgjxPWdTJMqYMjf3M6cuIFFA1/MpyyhIM99YInA+Rvc=
github.com/containers/ocicrypt v1.1.6 h1:uoG52u2e91RE4UqmBICZY8dNshgfvkdl3BW6jnxiFaI=
github.com/containers/ocicrypt v1.1.6/go.mod h1:WgjxPWdTJMqYMjf3M6cuIFFA1/MpyyhIM99YInA+Rvc=
github.com/containers/ocicrypt v1.1.7 h1:thhNr4fu2ltyGz8aMx8u48Ae0Pnbip3ePP9/mzkZ/3U=
github.com/containers/ocicrypt v1.1.7/go.mod h1:7CAhjcj2H8AYp5YvEie7oVSK2AhBY8NscCYRawuDNtw=
github.com/containers/storage v1.43.0/go.mod h1:uZ147thiIFGdVTjMmIw19knttQnUCl3y9zjreHrg11s=
github.com/containers/storage v1.45.0/go.mod h1:OdRUYHrq1HP6iAo79VxqtYuJzC5j4eA2I60jKOoCT7g=
github.com/containers/storage v1.45.1 h1:hsItObigGLm77Dn4ebUxQ68EfE6nMrwGcIdMRqzgclI=

1
vendor/github.com/containers/ocicrypt/.gitignore generated vendored Normal file
View File

@ -0,0 +1 @@
*~

31
vendor/github.com/containers/ocicrypt/.golangci.yml generated vendored Normal file
View File

@ -0,0 +1,31 @@
linters:
enable:
- depguard
- staticcheck
- unconvert
- gofmt
- goimports
- revive
- ineffassign
- vet
- unused
- misspell
linters-settings:
depguard:
list-type: denylist
include-go-root: true
packages:
# use "io" or "os" instead
# https://go.dev/doc/go1.16#ioutil
- io/ioutil
revive:
severity: error
rules:
- name: indent-error-flow
severity: warning
disabled: false
- name: error-strings
disabled: false

View File

@ -1,29 +0,0 @@
dist: bionic
language: go
os:
- linux
go:
- "1.13.x"
- "1.16.x"
matrix:
include:
- os: linux
addons:
apt:
packages:
- gnutls-bin
- softhsm2
go_import_path: github.com/containers/ocicrypt
install:
- curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(go env GOPATH)/bin v1.46.2
script:
- make
- make check
- make test

View File

@ -17,10 +17,11 @@
package blockcipher
import (
"errors"
"fmt"
"io"
"github.com/opencontainers/go-digest"
"github.com/pkg/errors"
)
// LayerCipherType is the ciphertype as specified in the layer metadata
@ -129,7 +130,7 @@ func (h *LayerBlockCipherHandler) Encrypt(plainDataReader io.Reader, typ LayerCi
}
return encDataReader, fin, err
}
return nil, nil, errors.Errorf("unsupported cipher type: %s", typ)
return nil, nil, fmt.Errorf("unsupported cipher type: %s", typ)
}
// Decrypt is the handler for the layer decryption routine
@ -138,10 +139,10 @@ func (h *LayerBlockCipherHandler) Decrypt(encDataReader io.Reader, opt LayerBloc
if typ == "" {
return nil, LayerBlockCipherOptions{}, errors.New("no cipher type provided")
}
if c, ok := h.cipherMap[LayerCipherType(typ)]; ok {
if c, ok := h.cipherMap[typ]; ok {
return c.Decrypt(encDataReader, opt)
}
return nil, LayerBlockCipherOptions{}, errors.Errorf("unsupported cipher type: %s", typ)
return nil, LayerBlockCipherOptions{}, fmt.Errorf("unsupported cipher type: %s", typ)
}
// NewLayerBlockCipherHandler returns a new default handler
@ -153,7 +154,7 @@ func NewLayerBlockCipherHandler() (*LayerBlockCipherHandler, error) {
var err error
h.cipherMap[AES256CTR], err = NewAESCTRLayerBlockCipher(256)
if err != nil {
return nil, errors.Wrap(err, "unable to set up Cipher AES-256-CTR")
return nil, fmt.Errorf("unable to set up Cipher AES-256-CTR: %w", err)
}
return &h, nil

View File

@ -22,12 +22,12 @@ import (
"crypto/hmac"
"crypto/rand"
"crypto/sha256"
"errors"
"fmt"
"hash"
"io"
"github.com/containers/ocicrypt/utils"
"github.com/pkg/errors"
)
// AESCTRLayerBlockCipher implements the AES CTR stream cipher
@ -74,7 +74,7 @@ func (r *aesctrcryptor) Read(p []byte) (int, error) {
if !r.bc.encrypt {
if _, err := r.bc.hmac.Write(p[:o]); err != nil {
r.bc.err = errors.Wrapf(err, "could not write to hmac")
r.bc.err = fmt.Errorf("could not write to hmac: %w", err)
return 0, r.bc.err
}
@ -92,7 +92,7 @@ func (r *aesctrcryptor) Read(p []byte) (int, error) {
if r.bc.encrypt {
if _, err := r.bc.hmac.Write(p[:o]); err != nil {
r.bc.err = errors.Wrapf(err, "could not write to hmac")
r.bc.err = fmt.Errorf("could not write to hmac: %w", err)
return 0, r.bc.err
}
@ -120,13 +120,13 @@ func (bc *AESCTRLayerBlockCipher) init(encrypt bool, reader io.Reader, opts Laye
if !ok {
nonce = make([]byte, aes.BlockSize)
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
return LayerBlockCipherOptions{}, errors.Wrap(err, "unable to generate random nonce")
return LayerBlockCipherOptions{}, fmt.Errorf("unable to generate random nonce: %w", err)
}
}
block, err := aes.NewCipher(key)
if err != nil {
return LayerBlockCipherOptions{}, errors.Wrap(err, "aes.NewCipher failed")
return LayerBlockCipherOptions{}, fmt.Errorf("aes.NewCipher failed: %w", err)
}
bc.reader = reader

View File

@ -17,10 +17,11 @@
package config
import (
"github.com/containers/ocicrypt/crypto/pkcs11"
"errors"
"fmt"
"strings"
"github.com/pkg/errors"
"github.com/containers/ocicrypt/crypto/pkcs11"
"gopkg.in/yaml.v3"
)
@ -85,7 +86,7 @@ func EncryptWithPkcs11(pkcs11Config *pkcs11.Pkcs11Config, pkcs11Pubkeys, pkcs11Y
}
p11confYaml, err := yaml.Marshal(pkcs11Config)
if err != nil {
return CryptoConfig{}, errors.Wrapf(err, "Could not marshal Pkcs11Config to Yaml")
return CryptoConfig{}, fmt.Errorf("Could not marshal Pkcs11Config to Yaml: %w", err)
}
dc = DecryptConfig{
@ -223,7 +224,7 @@ func DecryptWithGpgPrivKeys(gpgPrivKeys, gpgPrivKeysPwds [][]byte) (CryptoConfig
func DecryptWithPkcs11Yaml(pkcs11Config *pkcs11.Pkcs11Config, pkcs11Yamls [][]byte) (CryptoConfig, error) {
p11confYaml, err := yaml.Marshal(pkcs11Config)
if err != nil {
return CryptoConfig{}, errors.Wrapf(err, "Could not marshal Pkcs11Config to Yaml")
return CryptoConfig{}, fmt.Errorf("Could not marshal Pkcs11Config to Yaml: %w", err)
}
dc := DecryptConfig{

View File

@ -18,8 +18,7 @@ package config
import (
"encoding/json"
"github.com/pkg/errors"
"io/ioutil"
"fmt"
"os"
)
@ -52,7 +51,7 @@ func parseConfigFile(filename string) (*OcicryptConfig, error) {
return nil, nil
}
data, err := ioutil.ReadFile(filename)
data, err := os.ReadFile(filename)
if err != nil {
return nil, err
}
@ -72,7 +71,7 @@ func GetConfiguration() (*OcicryptConfig, error) {
if len(filename) > 0 {
ic, err = parseConfigFile(filename)
if err != nil {
return nil, errors.Wrap(err, "Error while parsing keyprovider config file")
return nil, fmt.Errorf("Error while parsing keyprovider config file: %w", err)
}
} else {
return nil, nil

View File

@ -17,13 +17,12 @@
package pkcs11config
import (
"errors"
"fmt"
"io/ioutil"
"os"
"path"
"github.com/containers/ocicrypt/crypto/pkcs11"
"github.com/pkg/errors"
"gopkg.in/yaml.v3"
)
@ -39,11 +38,11 @@ const ENVVARNAME = "OCICRYPT_CONFIG"
// not exist, so no error is returned.
// A config file may look like this:
// module-directories:
// - /usr/lib64/pkcs11/
// - /usr/lib/pkcs11/
// - /usr/lib64/pkcs11/
// - /usr/lib/pkcs11/
// allowed-module-paths:
// - /usr/lib64/pkcs11/
// - /usr/lib/pkcs11/
// - /usr/lib64/pkcs11/
// - /usr/lib/pkcs11/
func parseConfigFile(filename string) (*OcicryptConfig, error) {
// a non-existent config file is not an error
_, err := os.Stat(filename)
@ -51,7 +50,7 @@ func parseConfigFile(filename string) (*OcicryptConfig, error) {
return nil, nil
}
data, err := ioutil.ReadFile(filename)
data, err := os.ReadFile(filename)
if err != nil {
return nil, err
}

View File

@ -15,7 +15,7 @@ package pkcs11
import (
"fmt"
"github.com/pkg/errors"
pkcs11uri "github.com/stefanberger/go-pkcs11uri"
"gopkg.in/yaml.v3"
)
@ -42,7 +42,7 @@ func ParsePkcs11Uri(uri string) (*pkcs11uri.Pkcs11URI, error) {
p11uri := pkcs11uri.New()
err := p11uri.Parse(uri)
if err != nil {
return nil, errors.Wrapf(err, "Could not parse Pkcs11URI from file")
return nil, fmt.Errorf("Could not parse Pkcs11URI from file: %w", err)
}
return p11uri, err
}
@ -50,14 +50,14 @@ func ParsePkcs11Uri(uri string) (*pkcs11uri.Pkcs11URI, error) {
// ParsePkcs11KeyFile parses a pkcs11 key file holding a pkcs11 URI describing a private key.
// The file has the following yaml format:
// pkcs11:
// - uri : <pkcs11 uri>
// - uri : <pkcs11 uri>
// An error is returned if the pkcs11 URI is malformed
func ParsePkcs11KeyFile(yamlstr []byte) (*Pkcs11KeyFileObject, error) {
p11keyfile := Pkcs11KeyFile{}
err := yaml.Unmarshal([]byte(yamlstr), &p11keyfile)
err := yaml.Unmarshal(yamlstr, &p11keyfile)
if err != nil {
return nil, errors.Wrapf(err, "Could not unmarshal pkcs11 keyfile")
return nil, fmt.Errorf("Could not unmarshal pkcs11 keyfile: %w", err)
}
p11uri, err := ParsePkcs11Uri(p11keyfile.Pkcs11.Uri)
@ -126,9 +126,9 @@ func GetDefaultModuleDirectoriesYaml(indent string) string {
func ParsePkcs11ConfigFile(yamlstr []byte) (*Pkcs11Config, error) {
p11conf := Pkcs11Config{}
err := yaml.Unmarshal([]byte(yamlstr), &p11conf)
err := yaml.Unmarshal(yamlstr, &p11conf)
if err != nil {
return &p11conf, errors.Wrapf(err, "Could not parse Pkcs11Config")
return &p11conf, fmt.Errorf("Could not parse Pkcs11Config: %w", err)
}
return &p11conf, nil
}

View File

@ -1,3 +1,4 @@
//go:build cgo
// +build cgo
/*
@ -25,6 +26,7 @@ import (
"crypto/sha256"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"hash"
"net/url"
@ -33,7 +35,6 @@ import (
"strings"
"github.com/miekg/pkcs11"
"github.com/pkg/errors"
pkcs11uri "github.com/stefanberger/go-pkcs11uri"
)
@ -76,11 +77,11 @@ func rsaPublicEncryptOAEP(pubKey *rsa.PublicKey, plaintext []byte) ([]byte, stri
hashfunc = sha256.New()
hashalg = "sha256"
default:
return nil, "", errors.Errorf("Unsupported OAEP hash '%s'", oaephash)
return nil, "", fmt.Errorf("Unsupported OAEP hash '%s'", oaephash)
}
ciphertext, err := rsa.EncryptOAEP(hashfunc, rand.Reader, pubKey, plaintext, OAEPLabel)
if err != nil {
return nil, "", errors.Wrapf(err, "rss.EncryptOAEP failed")
return nil, "", fmt.Errorf("rss.EncryptOAEP failed: %w", err)
}
return ciphertext, hashalg, nil
@ -104,7 +105,7 @@ func pkcs11UriGetLoginParameters(p11uri *pkcs11uri.Pkcs11URI, privateKeyOperatio
module, err := p11uri.GetModule()
if err != nil {
return "", "", 0, errors.Wrap(err, "No module available in pkcs11 URI")
return "", "", 0, fmt.Errorf("No module available in pkcs11 URI: %w", err)
}
slotid := int64(-1)
@ -113,7 +114,7 @@ func pkcs11UriGetLoginParameters(p11uri *pkcs11uri.Pkcs11URI, privateKeyOperatio
if ok {
slotid, err = strconv.ParseInt(slot, 10, 64)
if err != nil {
return "", "", 0, errors.Wrap(err, "slot-id is not a valid number")
return "", "", 0, fmt.Errorf("slot-id is not a valid number: %w", err)
}
if slotid < 0 {
return "", "", 0, fmt.Errorf("slot-id is a negative number")
@ -138,21 +139,21 @@ func pkcs11UriGetKeyIdAndLabel(p11uri *pkcs11uri.Pkcs11URI) (string, string, err
// pkcs11OpenSession opens a session with a pkcs11 device at the given slot and logs in with the given PIN
func pkcs11OpenSession(p11ctx *pkcs11.Ctx, slotid uint, pin string) (session pkcs11.SessionHandle, err error) {
session, err = p11ctx.OpenSession(uint(slotid), pkcs11.CKF_SERIAL_SESSION|pkcs11.CKF_RW_SESSION)
session, err = p11ctx.OpenSession(slotid, pkcs11.CKF_SERIAL_SESSION|pkcs11.CKF_RW_SESSION)
if err != nil {
return 0, errors.Wrapf(err, "OpenSession to slot %d failed", slotid)
return 0, fmt.Errorf("OpenSession to slot %d failed: %w", slotid, err)
}
if len(pin) > 0 {
err = p11ctx.Login(session, pkcs11.CKU_USER, pin)
if err != nil {
_ = p11ctx.CloseSession(session)
return 0, errors.Wrap(err, "Could not login to device")
return 0, fmt.Errorf("Could not login to device: %w", err)
}
}
return session, nil
}
// pkcs11UriLogin uses the given pkcs11 URI to select the pkcs11 module (share libary) and to get
// pkcs11UriLogin uses the given pkcs11 URI to select the pkcs11 module (shared library) and to get
// the PIN to use for login; if the URI contains a slot-id, the given slot-id will be used, otherwise
// one slot after the other will be attempted and the first one where login succeeds will be used
func pkcs11UriLogin(p11uri *pkcs11uri.Pkcs11URI, privateKeyOperation bool) (ctx *pkcs11.Ctx, session pkcs11.SessionHandle, err error) {
@ -170,40 +171,40 @@ func pkcs11UriLogin(p11uri *pkcs11uri.Pkcs11URI, privateKeyOperation bool) (ctx
if err != nil {
p11Err := err.(pkcs11.Error)
if p11Err != pkcs11.CKR_CRYPTOKI_ALREADY_INITIALIZED {
return nil, 0, errors.Wrap(err, "Initialize failed")
return nil, 0, fmt.Errorf("Initialize failed: %w", err)
}
}
if slotid >= 0 {
session, err := pkcs11OpenSession(p11ctx, uint(slotid), pin)
return p11ctx, session, err
} else {
slots, err := p11ctx.GetSlotList(true)
if err != nil {
return nil, 0, errors.Wrap(err, "GetSlotList failed")
}
tokenlabel, ok := p11uri.GetPathAttribute("token", false)
if !ok {
return nil, 0, errors.New("Missing 'token' attribute since 'slot-id' was not given")
}
for _, slot := range slots {
ti, err := p11ctx.GetTokenInfo(slot)
if err != nil || ti.Label != tokenlabel {
continue
}
session, err = pkcs11OpenSession(p11ctx, slot, pin)
if err == nil {
return p11ctx, session, err
}
}
if len(pin) > 0 {
return nil, 0, errors.New("Could not create session to any slot and/or log in")
}
return nil, 0, errors.New("Could not create session to any slot")
}
slots, err := p11ctx.GetSlotList(true)
if err != nil {
return nil, 0, fmt.Errorf("GetSlotList failed: %w", err)
}
tokenlabel, ok := p11uri.GetPathAttribute("token", false)
if !ok {
return nil, 0, errors.New("Missing 'token' attribute since 'slot-id' was not given")
}
for _, slot := range slots {
ti, err := p11ctx.GetTokenInfo(slot)
if err != nil || ti.Label != tokenlabel {
continue
}
session, err = pkcs11OpenSession(p11ctx, slot, pin)
if err == nil {
return p11ctx, session, err
}
}
if len(pin) > 0 {
return nil, 0, errors.New("Could not create session to any slot and/or log in")
}
return nil, 0, errors.New("Could not create session to any slot")
}
func pkcs11Logout(ctx *pkcs11.Ctx, session pkcs11.SessionHandle) {
@ -233,24 +234,24 @@ func findObject(p11ctx *pkcs11.Ctx, session pkcs11.SessionHandle, class uint, ke
}
if err := p11ctx.FindObjectsInit(session, template); err != nil {
return 0, errors.Wrap(err, "FindObjectsInit failed")
return 0, fmt.Errorf("FindObjectsInit failed: %w", err)
}
obj, _, err := p11ctx.FindObjects(session, 100)
if err != nil {
return 0, errors.Wrap(err, "FindObjects failed")
return 0, fmt.Errorf("FindObjects failed: %w", err)
}
if err := p11ctx.FindObjectsFinal(session); err != nil {
return 0, errors.Wrap(err, "FindObjectsFinal failed")
return 0, fmt.Errorf("FindObjectsFinal failed: %w", err)
}
if len(obj) > 1 {
return 0, errors.Errorf("There are too many (=%d) keys with %s", len(obj), msg)
return 0, fmt.Errorf("There are too many (=%d) keys with %s", len(obj), msg)
} else if len(obj) == 1 {
return obj[0], nil
}
return 0, errors.Errorf("Could not find any object with %s", msg)
return 0, fmt.Errorf("Could not find any object with %s", msg)
}
// publicEncryptOAEP uses a public key described by a pkcs11 URI to OAEP encrypt the given plaintext
@ -290,17 +291,17 @@ func publicEncryptOAEP(pubKey *Pkcs11KeyFileObject, plaintext []byte) ([]byte, s
oaep = OAEPSha256Params
hashalg = "sha256"
default:
return nil, "", errors.Errorf("Unsupported OAEP hash '%s'", oaephash)
return nil, "", fmt.Errorf("Unsupported OAEP hash '%s'", oaephash)
}
err = p11ctx.EncryptInit(session, []*pkcs11.Mechanism{pkcs11.NewMechanism(pkcs11.CKM_RSA_PKCS_OAEP, oaep)}, p11PubKey)
if err != nil {
return nil, "", errors.Wrap(err, "EncryptInit error")
return nil, "", fmt.Errorf("EncryptInit error: %w", err)
}
ciphertext, err := p11ctx.Encrypt(session, plaintext)
if err != nil {
return nil, "", errors.Wrap(err, "Encrypt failed")
return nil, "", fmt.Errorf("Encrypt failed: %w", err)
}
return ciphertext, hashalg, nil
}
@ -338,16 +339,16 @@ func privateDecryptOAEP(privKeyObj *Pkcs11KeyFileObject, ciphertext []byte, hash
case "sha256":
oaep = OAEPSha256Params
default:
return nil, errors.Errorf("Unsupported hash algorithm '%s' for decryption", hashalg)
return nil, fmt.Errorf("Unsupported hash algorithm '%s' for decryption", hashalg)
}
err = p11ctx.DecryptInit(session, []*pkcs11.Mechanism{pkcs11.NewMechanism(pkcs11.CKM_RSA_PKCS_OAEP, oaep)}, p11PrivKey)
if err != nil {
return nil, errors.Wrapf(err, "DecryptInit failed")
return nil, fmt.Errorf("DecryptInit failed: %w", err)
}
plaintext, err := p11ctx.Decrypt(session, ciphertext)
if err != nil {
return nil, errors.Wrapf(err, "Decrypt failed")
return nil, fmt.Errorf("Decrypt failed: %w", err)
}
return plaintext, err
}
@ -373,19 +374,19 @@ type Pkcs11Recipient struct {
// may either be *rsa.PublicKey or *pkcs11uri.Pkcs11URI; the returned byte array is a JSON string of the
// following format:
// {
// recipients: [ // recipient list
// {
// "version": 0,
// "blob": <base64 encoded RSA OAEP encrypted blob>,
// "hash": <hash used for OAEP other than 'sha256'>
// } ,
// {
// "version": 0,
// "blob": <base64 encoded RSA OAEP encrypted blob>,
// "hash": <hash used for OAEP other than 'sha256'>
// } ,
// [...]
// ]
// recipients: [ // recipient list
// {
// "version": 0,
// "blob": <base64 encoded RSA OAEP encrypted blob>,
// "hash": <hash used for OAEP other than 'sha256'>
// } ,
// {
// "version": 0,
// "blob": <base64 encoded RSA OAEP encrypted blob>,
// "hash": <hash used for OAEP other than 'sha256'>
// } ,
// [...]
// ]
// }
func EncryptMultiple(pubKeys []interface{}, data []byte) ([]byte, error) {
var (
@ -402,7 +403,7 @@ func EncryptMultiple(pubKeys []interface{}, data []byte) ([]byte, error) {
case *Pkcs11KeyFileObject:
ciphertext, hashalg, err = publicEncryptOAEP(pkey, data)
default:
err = errors.Errorf("Unsupported key object type for pkcs11 public key")
err = fmt.Errorf("Unsupported key object type for pkcs11 public key")
}
if err != nil {
return nil, err
@ -422,33 +423,32 @@ func EncryptMultiple(pubKeys []interface{}, data []byte) ([]byte, error) {
// Decrypt tries to decrypt one of the recipients' blobs using a pkcs11 private key.
// The input pkcs11blobstr is a string with the following format:
// {
// recipients: [ // recipient list
// {
// "version": 0,
// "blob": <base64 encoded RSA OAEP encrypted blob>,
// "hash": <hash used for OAEP other than 'sha1'>
// } ,
// {
// "version": 0,
// "blob": <base64 encoded RSA OAEP encrypted blob>,
// "hash": <hash used for OAEP other than 'sha1'>
// } ,
// [...]
// recipients: [ // recipient list
// {
// "version": 0,
// "blob": <base64 encoded RSA OAEP encrypted blob>,
// "hash": <hash used for OAEP other than 'sha1'>
// } ,
// {
// "version": 0,
// "blob": <base64 encoded RSA OAEP encrypted blob>,
// "hash": <hash used for OAEP other than 'sha1'>
// } ,
// [...]
// }
// Note: More recent versions of this code explicitly write 'sha1'
// while older versions left it empty in case of 'sha1'.
//
// while older versions left it empty in case of 'sha1'.
func Decrypt(privKeyObjs []*Pkcs11KeyFileObject, pkcs11blobstr []byte) ([]byte, error) {
pkcs11blob := Pkcs11Blob{}
err := json.Unmarshal(pkcs11blobstr, &pkcs11blob)
if err != nil {
return nil, errors.Wrapf(err, "Could not parse Pkcs11Blob")
return nil, fmt.Errorf("Could not parse Pkcs11Blob: %w", err)
}
switch pkcs11blob.Version {
case 0:
// latest supported version
default:
return nil, errors.Errorf("Found Pkcs11Blob with version %d but maximum supported version is 0.", pkcs11blob.Version)
return nil, fmt.Errorf("found Pkcs11Blob with version %d but maximum supported version is 0", pkcs11blob.Version)
}
// since we do trial and error, collect all encountered errors
errs := ""
@ -458,7 +458,7 @@ func Decrypt(privKeyObjs []*Pkcs11KeyFileObject, pkcs11blobstr []byte) ([]byte,
case 0:
// last supported version
default:
return nil, errors.Errorf("Found Pkcs11Recipient with version %d but maximum supported version is 0.", recipient.Version)
return nil, fmt.Errorf("found Pkcs11Recipient with version %d but maximum supported version is 0", recipient.Version)
}
ciphertext, err := base64.StdEncoding.DecodeString(recipient.Blob)
@ -481,5 +481,5 @@ func Decrypt(privKeyObjs []*Pkcs11KeyFileObject, pkcs11blobstr []byte) ([]byte,
}
}
return nil, errors.Errorf("Could not find a pkcs11 key for decryption:\n%s", errs)
return nil, fmt.Errorf("Could not find a pkcs11 key for decryption:\n%s", errs)
}

View File

@ -1,3 +1,4 @@
//go:build !cgo
// +build !cgo
/*
@ -18,14 +19,12 @@
package pkcs11
import (
"github.com/pkg/errors"
)
import "fmt"
func EncryptMultiple(pubKeys []interface{}, data []byte) ([]byte, error) {
return nil, errors.Errorf("ocicrypt pkcs11 not supported on this build")
return nil, fmt.Errorf("ocicrypt pkcs11 not supported on this build")
}
func Decrypt(privKeyObjs []*Pkcs11KeyFileObject, pkcs11blobstr []byte) ([]byte, error) {
return nil, errors.Errorf("ocicrypt pkcs11 not supported on this build")
return nil, fmt.Errorf("ocicrypt pkcs11 not supported on this build")
}

View File

@ -17,12 +17,11 @@
package pkcs11
import (
"fmt"
"os"
"runtime"
"strings"
"sync"
"github.com/pkg/errors"
)
var (
@ -45,7 +44,7 @@ func setEnvVars(env map[string]string) ([]string, error) {
err := os.Setenv(k, v)
if err != nil {
restoreEnv(oldenv)
return nil, errors.Wrapf(err, "Could not set environment variable '%s' to '%s'", k, v)
return nil, fmt.Errorf("Could not set environment variable '%s' to '%s': %w", k, v, err)
}
}

View File

@ -19,22 +19,22 @@ package ocicrypt
import (
"encoding/base64"
"encoding/json"
"errors"
"fmt"
keyproviderconfig "github.com/containers/ocicrypt/config/keyprovider-config"
"github.com/containers/ocicrypt/keywrap/keyprovider"
"io"
"strings"
"github.com/containers/ocicrypt/blockcipher"
"github.com/containers/ocicrypt/config"
keyproviderconfig "github.com/containers/ocicrypt/config/keyprovider-config"
"github.com/containers/ocicrypt/keywrap"
"github.com/containers/ocicrypt/keywrap/jwe"
"github.com/containers/ocicrypt/keywrap/keyprovider"
"github.com/containers/ocicrypt/keywrap/pgp"
"github.com/containers/ocicrypt/keywrap/pkcs11"
"github.com/containers/ocicrypt/keywrap/pkcs7"
"github.com/opencontainers/go-digest"
ocispec "github.com/opencontainers/image-spec/specs-go/v1"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
)
@ -133,11 +133,11 @@ func EncryptLayer(ec *config.EncryptConfig, encOrPlainLayerReader io.Reader, des
}
privOptsData, err = json.Marshal(opts.Private)
if err != nil {
return nil, errors.Wrapf(err, "could not JSON marshal opts")
return nil, fmt.Errorf("could not JSON marshal opts: %w", err)
}
pubOptsData, err = json.Marshal(opts.Public)
if err != nil {
return nil, errors.Wrapf(err, "could not JSON marshal opts")
return nil, fmt.Errorf("could not JSON marshal opts: %w", err)
}
}
@ -243,9 +243,9 @@ func decryptLayerKeyOptsData(dc *config.DecryptConfig, desc ocispec.Descriptor)
}
}
if !privKeyGiven {
return nil, errors.New("missing private key needed for decryption")
return nil, fmt.Errorf("missing private key needed for decryption:\n%s", errs)
}
return nil, errors.Errorf("no suitable key unwrapper found or none of the private keys could be used for decryption:\n%s", errs)
return nil, fmt.Errorf("no suitable key unwrapper found or none of the private keys could be used for decryption:\n%s", errs)
}
func getLayerPubOpts(desc ocispec.Descriptor) ([]byte, error) {
@ -276,7 +276,7 @@ func preUnwrapKey(keywrapper keywrap.KeyWrapper, dc *config.DecryptConfig, b64An
}
return optsData, nil
}
return nil, errors.Errorf("no suitable key found for decrypting layer key:\n%s", errs)
return nil, fmt.Errorf("no suitable key found for decrypting layer key:\n%s", errs)
}
// commonEncryptLayer is a function to encrypt the plain layer using a new random
@ -311,7 +311,7 @@ func commonDecryptLayer(encLayerReader io.Reader, privOptsData []byte, pubOptsDa
privOpts := blockcipher.PrivateLayerBlockCipherOptions{}
err := json.Unmarshal(privOptsData, &privOpts)
if err != nil {
return nil, "", errors.Wrapf(err, "could not JSON unmarshal privOptsData")
return nil, "", fmt.Errorf("could not JSON unmarshal privOptsData: %w", err)
}
lbch, err := blockcipher.NewLayerBlockCipherHandler()
@ -323,7 +323,7 @@ func commonDecryptLayer(encLayerReader io.Reader, privOptsData []byte, pubOptsDa
if len(pubOptsData) > 0 {
err := json.Unmarshal(pubOptsData, &pubOpts)
if err != nil {
return nil, "", errors.Wrapf(err, "could not JSON unmarshal pubOptsData")
return nil, "", fmt.Errorf("could not JSON unmarshal pubOptsData: %w", err)
}
}

View File

@ -17,16 +17,17 @@
package ocicrypt
import (
"errors"
"fmt"
"io/ioutil"
"io"
"os"
"os/exec"
"regexp"
"strconv"
"strings"
"sync"
ocispec "github.com/opencontainers/image-spec/specs-go/v1"
"github.com/pkg/errors"
"golang.org/x/term"
)
@ -132,7 +133,7 @@ func (gc *gpgv2Client) GetGPGPrivateKey(keyid uint64, passphrase string) ([]byte
rfile, wfile, err := os.Pipe()
if err != nil {
return nil, errors.Wrapf(err, "could not create pipe")
return nil, fmt.Errorf("could not create pipe: %w", err)
}
defer func() {
rfile.Close()
@ -272,8 +273,8 @@ func runGPGGetOutput(cmd *exec.Cmd) ([]byte, error) {
return nil, err
}
stdoutstr, err2 := ioutil.ReadAll(stdout)
stderrstr, _ := ioutil.ReadAll(stderr)
stdoutstr, err2 := io.ReadAll(stdout)
stderrstr, _ := io.ReadAll(stderr)
if err := cmd.Wait(); err != nil {
return nil, fmt.Errorf("error from %s: %s", cmd.Path, string(stderrstr))
@ -310,9 +311,15 @@ func resolveRecipients(gc GPGClient, recipients []string) []string {
return result
}
var emailPattern = regexp.MustCompile(`uid\s+\[.*\]\s.*\s<(?P<email>.+)>`)
var (
onceRegexp sync.Once
emailPattern *regexp.Regexp
)
func extractEmailFromDetails(details []byte) string {
onceRegexp.Do(func() {
emailPattern = regexp.MustCompile(`uid\s+\[.*\]\s.*\s<(?P<email>.+)>`)
})
loc := emailPattern.FindSubmatchIndex(details)
if len(loc) == 0 {
return ""
@ -352,7 +359,7 @@ func GPGGetPrivateKey(descs []ocispec.Descriptor, gpgClient GPGClient, gpgVault
}
keywrapper := GetKeyWrapper(scheme)
if keywrapper == nil {
return nil, nil, errors.Errorf("could not get KeyWrapper for %s\n", scheme)
return nil, nil, fmt.Errorf("could not get KeyWrapper for %s", scheme)
}
keyIds, err := keywrapper.GetKeyIdsFromPacket(b64pgpPackets)
if err != nil {
@ -411,7 +418,7 @@ func GPGGetPrivateKey(descs []ocispec.Descriptor, gpgClient GPGClient, gpgVault
if !found && len(b64pgpPackets) > 0 && mustFindKey {
ids := uint64ToStringArray("0x%x", keyIds)
return nil, nil, errors.Errorf("missing key for decryption of layer %x of %s. Need one of the following keys: %s", desc.Digest, desc.Platform, strings.Join(ids, ", "))
return nil, nil, fmt.Errorf("missing key for decryption of layer %x of %s. Need one of the following keys: %s", desc.Digest, desc.Platform, strings.Join(ids, ", "))
}
}
}

View File

@ -18,9 +18,9 @@ package ocicrypt
import (
"bytes"
"io/ioutil"
"fmt"
"os"
"github.com/pkg/errors"
"golang.org/x/crypto/openpgp"
"golang.org/x/crypto/openpgp/packet"
)
@ -55,7 +55,7 @@ func (g *gpgVault) AddSecretKeyRingData(gpgSecretKeyRingData []byte) error {
r := bytes.NewReader(gpgSecretKeyRingData)
entityList, err := openpgp.ReadKeyRing(r)
if err != nil {
return errors.Wrapf(err, "could not read keyring")
return fmt.Errorf("could not read keyring: %w", err)
}
g.entityLists = append(g.entityLists, entityList)
g.keyDataList = append(g.keyDataList, gpgSecretKeyRingData)
@ -76,7 +76,7 @@ func (g *gpgVault) AddSecretKeyRingDataArray(gpgSecretKeyRingDataArray [][]byte)
// AddSecretKeyRingFiles adds the secret key rings given their filenames
func (g *gpgVault) AddSecretKeyRingFiles(filenames []string) error {
for _, filename := range filenames {
gpgSecretKeyRingData, err := ioutil.ReadFile(filename)
gpgSecretKeyRingData, err := os.ReadFile(filename)
if err != nil {
return err
}

View File

@ -1,8 +1,8 @@
package helpers
import (
"errors"
"fmt"
"io/ioutil"
"os"
"strconv"
"strings"
@ -12,8 +12,6 @@ import (
"github.com/containers/ocicrypt/config/pkcs11config"
"github.com/containers/ocicrypt/crypto/pkcs11"
encutils "github.com/containers/ocicrypt/utils"
"github.com/pkg/errors"
)
// processRecipientKeys sorts the array of recipients by type. Recipients may be either
@ -43,9 +41,9 @@ func processRecipientKeys(recipients []string) ([][]byte, [][]byte, [][]byte, []
gpgRecipients = append(gpgRecipients, []byte(value))
case "jwe":
tmp, err := ioutil.ReadFile(value)
tmp, err := os.ReadFile(value)
if err != nil {
return nil, nil, nil, nil, nil, nil, errors.Wrap(err, "Unable to read file")
return nil, nil, nil, nil, nil, nil, fmt.Errorf("Unable to read file: %w", err)
}
if !encutils.IsPublicKey(tmp) {
return nil, nil, nil, nil, nil, nil, errors.New("File provided is not a public key")
@ -53,9 +51,9 @@ func processRecipientKeys(recipients []string) ([][]byte, [][]byte, [][]byte, []
pubkeys = append(pubkeys, tmp)
case "pkcs7":
tmp, err := ioutil.ReadFile(value)
tmp, err := os.ReadFile(value)
if err != nil {
return nil, nil, nil, nil, nil, nil, errors.Wrap(err, "Unable to read file")
return nil, nil, nil, nil, nil, nil, fmt.Errorf("Unable to read file: %w", err)
}
if !encutils.IsCertificate(tmp) {
return nil, nil, nil, nil, nil, nil, errors.New("File provided is not an x509 cert")
@ -63,9 +61,9 @@ func processRecipientKeys(recipients []string) ([][]byte, [][]byte, [][]byte, []
x509s = append(x509s, tmp)
case "pkcs11":
tmp, err := ioutil.ReadFile(value)
tmp, err := os.ReadFile(value)
if err != nil {
return nil, nil, nil, nil, nil, nil, errors.Wrap(err, "Unable to read file")
return nil, nil, nil, nil, nil, nil, fmt.Errorf("Unable to read file: %w", err)
}
if encutils.IsPkcs11PublicKey(tmp) {
pkcs11Yamls = append(pkcs11Yamls, tmp)
@ -93,9 +91,9 @@ func processx509Certs(keys []string) ([][]byte, error) {
if _, err := os.Stat(fileName); os.IsNotExist(err) {
continue
}
tmp, err := ioutil.ReadFile(fileName)
tmp, err := os.ReadFile(fileName)
if err != nil {
return nil, errors.Wrap(err, "Unable to read file")
return nil, fmt.Errorf("Unable to read file: %w", err)
}
if !encutils.IsCertificate(tmp) {
continue
@ -113,14 +111,14 @@ func processx509Certs(keys []string) ([][]byte, error) {
// - <password>
func processPwdString(pwdString string) ([]byte, error) {
if strings.HasPrefix(pwdString, "file=") {
return ioutil.ReadFile(pwdString[5:])
return os.ReadFile(pwdString[5:])
} else if strings.HasPrefix(pwdString, "pass=") {
return []byte(pwdString[5:]), nil
} else if strings.HasPrefix(pwdString, "fd=") {
fdStr := pwdString[3:]
fd, err := strconv.Atoi(fdStr)
if err != nil {
return nil, errors.Wrapf(err, "could not parse file descriptor %s", fdStr)
return nil, fmt.Errorf("could not parse file descriptor %s: %w", fdStr, err)
}
f := os.NewFile(uintptr(fd), "pwdfile")
if f == nil {
@ -130,7 +128,7 @@ func processPwdString(pwdString string) ([]byte, error) {
pwd := make([]byte, 64)
n, err := f.Read(pwd)
if err != nil {
return nil, errors.Wrapf(err, "could not read from file descriptor")
return nil, fmt.Errorf("could not read from file descriptor: %w", err)
}
return pwd[:n], nil
}
@ -174,7 +172,7 @@ func processPrivateKeyFiles(keyFilesAndPwds []string) ([][]byte, [][]byte, [][]b
}
keyfile := parts[0]
tmp, err := ioutil.ReadFile(keyfile)
tmp, err := os.ReadFile(keyfile)
if err != nil {
return nil, nil, nil, nil, nil, nil, err
}
@ -374,7 +372,6 @@ func CreateCryptoConfig(recipients []string, keys []string) (encconfig.CryptoCon
if len(ccs) > 0 {
return encconfig.CombineCryptoConfigs(ccs), nil
} else {
return encconfig.CryptoConfig{}, nil
}
return encconfig.CryptoConfig{}, nil
}

View File

@ -18,11 +18,12 @@ package jwe
import (
"crypto/ecdsa"
"errors"
"fmt"
"github.com/containers/ocicrypt/config"
"github.com/containers/ocicrypt/keywrap"
"github.com/containers/ocicrypt/utils"
"github.com/pkg/errors"
jose "gopkg.in/square/go-jose.v2"
)
@ -54,11 +55,11 @@ func (kw *jweKeyWrapper) WrapKeys(ec *config.EncryptConfig, optsData []byte) ([]
encrypter, err := jose.NewMultiEncrypter(jose.A256GCM, joseRecipients, nil)
if err != nil {
return nil, errors.Wrapf(err, "jose.NewMultiEncrypter failed")
return nil, fmt.Errorf("jose.NewMultiEncrypter failed: %w", err)
}
jwe, err := encrypter.Encrypt(optsData)
if err != nil {
return nil, errors.Wrapf(err, "JWE Encrypt failed")
return nil, fmt.Errorf("JWE Encrypt failed: %w", err)
}
return []byte(jwe.FullSerialize()), nil
}

View File

@ -19,12 +19,14 @@ package keyprovider
import (
"context"
"encoding/json"
"errors"
"fmt"
"github.com/containers/ocicrypt/config"
keyproviderconfig "github.com/containers/ocicrypt/config/keyprovider-config"
"github.com/containers/ocicrypt/keywrap"
"github.com/containers/ocicrypt/utils"
keyproviderpb "github.com/containers/ocicrypt/utils/keyprovider"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
"google.golang.org/grpc"
)
@ -112,13 +114,13 @@ func (kw *keyProviderKeyWrapper) WrapKeys(ec *config.EncryptConfig, optsData []b
if kw.attrs.Command != nil {
protocolOuput, err := getProviderCommandOutput(input, kw.attrs.Command)
if err != nil {
return nil, errors.Wrap(err, "error while retrieving keyprovider protocol command output")
return nil, fmt.Errorf("error while retrieving keyprovider protocol command output: %w", err)
}
return protocolOuput.KeyWrapResults.Annotation, nil
} else if kw.attrs.Grpc != "" {
protocolOuput, err := getProviderGRPCOutput(input, kw.attrs.Grpc, OpKeyWrap)
if err != nil {
return nil, errors.Wrap(err, "error while retrieving keyprovider protocol grpc output")
return nil, fmt.Errorf("error while retrieving keyprovider protocol grpc output: %w", err)
}
return protocolOuput.KeyWrapResults.Annotation, nil
@ -170,7 +172,7 @@ func getProviderGRPCOutput(input []byte, connString string, operation KeyProvide
var grpcOutput *keyproviderpb.KeyProviderKeyWrapProtocolOutput
cc, err := grpc.Dial(connString, grpc.WithInsecure())
if err != nil {
return nil, errors.Wrap(err, "error while dialing rpc server")
return nil, fmt.Errorf("error while dialing rpc server: %w", err)
}
defer func() {
derr := cc.Close()
@ -187,12 +189,12 @@ func getProviderGRPCOutput(input []byte, connString string, operation KeyProvide
if operation == OpKeyWrap {
grpcOutput, err = client.WrapKey(context.Background(), req)
if err != nil {
return nil, errors.Wrap(err, "Error from grpc method")
return nil, fmt.Errorf("Error from grpc method: %w", err)
}
} else if operation == OpKeyUnwrap {
grpcOutput, err = client.UnWrapKey(context.Background(), req)
if err != nil {
return nil, errors.Wrap(err, "Error from grpc method")
return nil, fmt.Errorf("Error from grpc method: %w", err)
}
} else {
return nil, errors.New("Unsupported operation")
@ -201,7 +203,7 @@ func getProviderGRPCOutput(input []byte, connString string, operation KeyProvide
respBytes := grpcOutput.GetKeyProviderKeyWrapProtocolOutput()
err = json.Unmarshal(respBytes, &protocolOuput)
if err != nil {
return nil, errors.Wrap(err, "Error while unmarshalling grpc method output")
return nil, fmt.Errorf("Error while unmarshalling grpc method output: %w", err)
}
return &protocolOuput, nil
@ -216,7 +218,7 @@ func getProviderCommandOutput(input []byte, command *keyproviderconfig.Command)
}
err = json.Unmarshal(respBytes, &protocolOuput)
if err != nil {
return nil, errors.Wrap(err, "Error while unmarshalling binary executable command output")
return nil, fmt.Errorf("Error while unmarshalling binary executable command output: %w", err)
}
return &protocolOuput, nil
}

View File

@ -21,16 +21,15 @@ import (
"crypto"
"crypto/rand"
"encoding/base64"
"errors"
"fmt"
"io"
"io/ioutil"
"net/mail"
"strconv"
"strings"
"github.com/containers/ocicrypt/config"
"github.com/containers/ocicrypt/keywrap"
"github.com/pkg/errors"
"golang.org/x/crypto/openpgp"
"golang.org/x/crypto/openpgp/packet"
)
@ -64,7 +63,7 @@ func (kw *gpgKeyWrapper) WrapKeys(ec *config.EncryptConfig, optsData []byte) ([]
ciphertext := new(bytes.Buffer)
el, err := kw.createEntityList(ec)
if err != nil {
return nil, errors.Wrap(err, "unable to create entity list")
return nil, fmt.Errorf("unable to create entity list: %w", err)
}
if len(el) == 0 {
// nothing to do -- not an error
@ -100,7 +99,7 @@ func (kw *gpgKeyWrapper) UnwrapKey(dc *config.DecryptConfig, pgpPacket []byte) (
r := bytes.NewBuffer(pgpPrivateKey)
entityList, err := openpgp.ReadKeyRing(r)
if err != nil {
return nil, errors.Wrap(err, "unable to parse private keys")
return nil, fmt.Errorf("unable to parse private keys: %w", err)
}
var prompt openpgp.PromptFunction
@ -126,7 +125,7 @@ func (kw *gpgKeyWrapper) UnwrapKey(dc *config.DecryptConfig, pgpPacket []byte) (
continue
}
// we get the plain key options back
optsData, err := ioutil.ReadAll(md.UnverifiedBody)
optsData, err := io.ReadAll(md.UnverifiedBody)
if err != nil {
continue
}
@ -142,7 +141,7 @@ func (kw *gpgKeyWrapper) GetKeyIdsFromPacket(b64pgpPackets string) ([]uint64, er
for _, b64pgpPacket := range strings.Split(b64pgpPackets, ",") {
pgpPacket, err := base64.StdEncoding.DecodeString(b64pgpPacket)
if err != nil {
return nil, errors.Wrapf(err, "could not decode base64 encoded PGP packet")
return nil, fmt.Errorf("could not decode base64 encoded PGP packet: %w", err)
}
newids, err := kw.getKeyIDs(pgpPacket)
if err != nil {
@ -166,7 +165,7 @@ ParsePackets:
break ParsePackets
}
if err != nil {
return []uint64{}, errors.Wrapf(err, "packets.Next() failed")
return []uint64{}, fmt.Errorf("packets.Next() failed: %w", err)
}
switch p := p.(type) {
case *packet.EncryptedKey:

View File

@ -17,12 +17,13 @@
package pkcs11
import (
"errors"
"fmt"
"github.com/containers/ocicrypt/config"
"github.com/containers/ocicrypt/crypto/pkcs11"
"github.com/containers/ocicrypt/keywrap"
"github.com/containers/ocicrypt/utils"
"github.com/pkg/errors"
)
type pkcs11KeyWrapper struct {
@ -51,7 +52,7 @@ func (kw *pkcs11KeyWrapper) WrapKeys(ec *config.EncryptConfig, optsData []byte)
jsonString, err := pkcs11.EncryptMultiple(pkcs11Recipients, optsData)
if err != nil {
return nil, errors.Wrapf(err, "PKCS11 EncryptMulitple failed")
return nil, fmt.Errorf("PKCS11 EncryptMulitple failed: %w", err)
}
return jsonString, nil
}
@ -91,7 +92,7 @@ func (kw *pkcs11KeyWrapper) UnwrapKey(dc *config.DecryptConfig, jsonString []byt
return plaintext, nil
}
return nil, errors.Wrapf(err, "PKCS11: No suitable private key found for decryption")
return nil, fmt.Errorf("PKCS11: No suitable private key found for decryption: %w", err)
}
func (kw *pkcs11KeyWrapper) NoPossibleKeys(dcparameters map[string][][]byte) bool {

View File

@ -19,11 +19,12 @@ package pkcs7
import (
"crypto"
"crypto/x509"
"errors"
"fmt"
"github.com/containers/ocicrypt/config"
"github.com/containers/ocicrypt/keywrap"
"github.com/containers/ocicrypt/utils"
"github.com/pkg/errors"
"go.mozilla.org/pkcs7"
)
@ -104,7 +105,7 @@ func (kw *pkcs7KeyWrapper) UnwrapKey(dc *config.DecryptConfig, pkcs7Packet []byt
p7, err := pkcs7.Parse(pkcs7Packet)
if err != nil {
return nil, errors.Wrapf(err, "could not parse PKCS7 packet")
return nil, fmt.Errorf("could not parse PKCS7 packet: %w", err)
}
for idx, privKey := range privKeys {

View File

@ -18,7 +18,7 @@ package utils
import (
"bytes"
"github.com/pkg/errors"
"fmt"
"io"
"os/exec"
)
@ -44,13 +44,15 @@ type Runner struct{}
// ExecuteCommand is used to execute a linux command line command and return the output of the command with an error if it exists.
func (r Runner) Exec(cmdName string, args []string, input []byte) ([]byte, error) {
var out bytes.Buffer
var stderr bytes.Buffer
stdInputBuffer := bytes.NewBuffer(input)
cmd := exec.Command(cmdName, args...)
cmd.Stdin = stdInputBuffer
cmd.Stdout = &out
cmd.Stderr = &stderr
err := cmd.Run()
if err != nil {
return nil, errors.Wrapf(err, "Error while running command: %s", cmdName)
return nil, fmt.Errorf("Error while running command: %s. stderr: %s: %w", cmdName, stderr.String(), err)
}
return out.Bytes(), nil
}

View File

@ -24,17 +24,16 @@ import (
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"fmt"
"math/big"
"time"
"github.com/pkg/errors"
)
// CreateRSAKey creates an RSA key
func CreateRSAKey(bits int) (*rsa.PrivateKey, error) {
key, err := rsa.GenerateKey(rand.Reader, bits)
if err != nil {
return nil, errors.Wrap(err, "rsa.GenerateKey failed")
return nil, fmt.Errorf("rsa.GenerateKey failed: %w", err)
}
return key, nil
}
@ -49,7 +48,7 @@ func CreateRSATestKey(bits int, password []byte, pemencode bool) ([]byte, []byte
pubData, err := x509.MarshalPKIXPublicKey(&key.PublicKey)
if err != nil {
return nil, nil, errors.Wrap(err, "x509.MarshalPKIXPublicKey failed")
return nil, nil, fmt.Errorf("x509.MarshalPKIXPublicKey failed: %w", err)
}
privData := x509.MarshalPKCS1PrivateKey(key)
@ -69,7 +68,7 @@ func CreateRSATestKey(bits int, password []byte, pemencode bool) ([]byte, []byte
if len(password) > 0 {
block, err = x509.EncryptPEMBlock(rand.Reader, typ, privData, password, x509.PEMCipherAES256) //nolint:staticcheck // ignore SA1019, which is kept for backward compatibility
if err != nil {
return nil, nil, errors.Wrap(err, "x509.EncryptPEMBlock failed")
return nil, nil, fmt.Errorf("x509.EncryptPEMBlock failed: %w", err)
}
} else {
block = &pem.Block{
@ -88,17 +87,17 @@ func CreateRSATestKey(bits int, password []byte, pemencode bool) ([]byte, []byte
func CreateECDSATestKey(curve elliptic.Curve) ([]byte, []byte, error) {
key, err := ecdsa.GenerateKey(curve, rand.Reader)
if err != nil {
return nil, nil, errors.Wrapf(err, "ecdsa.GenerateKey failed")
return nil, nil, fmt.Errorf("ecdsa.GenerateKey failed: %w", err)
}
pubData, err := x509.MarshalPKIXPublicKey(&key.PublicKey)
if err != nil {
return nil, nil, errors.Wrapf(err, "x509.MarshalPKIXPublicKey failed")
return nil, nil, fmt.Errorf("x509.MarshalPKIXPublicKey failed: %w", err)
}
privData, err := x509.MarshalECPrivateKey(key)
if err != nil {
return nil, nil, errors.Wrapf(err, "x509.MarshalECPrivateKey failed")
return nil, nil, fmt.Errorf("x509.MarshalECPrivateKey failed: %w", err)
}
return pubData, privData, nil
@ -108,7 +107,7 @@ func CreateECDSATestKey(curve elliptic.Curve) ([]byte, []byte, error) {
func CreateTestCA() (*rsa.PrivateKey, *x509.Certificate, error) {
key, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
return nil, nil, errors.Wrap(err, "rsa.GenerateKey failed")
return nil, nil, fmt.Errorf("rsa.GenerateKey failed: %w", err)
}
ca := &x509.Certificate{
@ -154,12 +153,12 @@ func certifyKey(pub interface{}, template *x509.Certificate, caKey *rsa.PrivateK
certDER, err := x509.CreateCertificate(rand.Reader, template, caCert, pub, caKey)
if err != nil {
return nil, errors.Wrap(err, "x509.CreateCertificate failed")
return nil, fmt.Errorf("x509.CreateCertificate failed: %w", err)
}
cert, err := x509.ParseCertificate(certDER)
if err != nil {
return nil, errors.Wrap(err, "x509.ParseCertificate failed")
return nil, fmt.Errorf("x509.ParseCertificate failed: %w", err)
}
return cert, nil

View File

@ -21,12 +21,12 @@ import (
"crypto/x509"
"encoding/base64"
"encoding/pem"
"errors"
"fmt"
"strings"
"github.com/containers/ocicrypt/crypto/pkcs11"
"github.com/pkg/errors"
"golang.org/x/crypto/openpgp"
json "gopkg.in/square/go-jose.v2"
)
@ -36,7 +36,7 @@ func parseJWKPrivateKey(privKey []byte, prefix string) (interface{}, error) {
jwk := json.JSONWebKey{}
err := jwk.UnmarshalJSON(privKey)
if err != nil {
return nil, errors.Wrapf(err, "%s: Could not parse input as JWK", prefix)
return nil, fmt.Errorf("%s: Could not parse input as JWK: %w", prefix, err)
}
if jwk.IsPublic() {
return nil, fmt.Errorf("%s: JWK is not a private key", prefix)
@ -49,7 +49,7 @@ func parseJWKPublicKey(privKey []byte, prefix string) (interface{}, error) {
jwk := json.JSONWebKey{}
err := jwk.UnmarshalJSON(privKey)
if err != nil {
return nil, errors.Wrapf(err, "%s: Could not parse input as JWK", prefix)
return nil, fmt.Errorf("%s: Could not parse input as JWK: %w", prefix, err)
}
if !jwk.IsPublic() {
return nil, fmt.Errorf("%s: JWK is not a public key", prefix)
@ -97,11 +97,11 @@ func ParsePrivateKey(privKey, privKeyPassword []byte, prefix string) (interface{
var der []byte
if x509.IsEncryptedPEMBlock(block) { //nolint:staticcheck // ignore SA1019, which is kept for backward compatibility
if privKeyPassword == nil {
return nil, errors.Errorf("%s: Missing password for encrypted private key", prefix)
return nil, fmt.Errorf("%s: Missing password for encrypted private key", prefix)
}
der, err = x509.DecryptPEMBlock(block, privKeyPassword) //nolint:staticcheck // ignore SA1019, which is kept for backward compatibility
if err != nil {
return nil, errors.Errorf("%s: Wrong password: could not decrypt private key", prefix)
return nil, fmt.Errorf("%s: Wrong password: could not decrypt private key", prefix)
}
} else {
der = block.Bytes
@ -111,7 +111,7 @@ func ParsePrivateKey(privKey, privKeyPassword []byte, prefix string) (interface{
if err != nil {
key, err = x509.ParsePKCS1PrivateKey(der)
if err != nil {
return nil, errors.Wrapf(err, "%s: Could not parse private key", prefix)
return nil, fmt.Errorf("%s: Could not parse private key: %w", prefix, err)
}
}
} else {
@ -145,7 +145,7 @@ func ParsePublicKey(pubKey []byte, prefix string) (interface{}, error) {
if block != nil {
key, err = x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
return nil, errors.Wrapf(err, "%s: Could not parse public key", prefix)
return nil, fmt.Errorf("%s: Could not parse public key: %w", prefix, err)
}
} else {
key, err = parseJWKPublicKey(pubKey, prefix)
@ -179,7 +179,7 @@ func ParseCertificate(certBytes []byte, prefix string) (*x509.Certificate, error
}
x509Cert, err = x509.ParseCertificate(block.Bytes)
if err != nil {
return nil, errors.Wrapf(err, "%s: Could not parse x509 certificate", prefix)
return nil, fmt.Errorf("%s: Could not parse x509 certificate: %w", prefix, err)
}
}
return x509Cert, err

4
vendor/modules.txt vendored
View File

@ -131,8 +131,8 @@ github.com/containers/image/v5/version
# github.com/containers/libtrust v0.0.0-20200511145503-9c3a6c22cd9a
## explicit
github.com/containers/libtrust
# github.com/containers/ocicrypt v1.1.6
## explicit; go 1.12
# github.com/containers/ocicrypt v1.1.7
## explicit; go 1.16
github.com/containers/ocicrypt
github.com/containers/ocicrypt/blockcipher
github.com/containers/ocicrypt/config