From 0e0e1a14216f7f9dbb186c7a0f10746d34d09786 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miloslav=20Trma=C4=8D?= Date: Fri, 20 Oct 2023 17:51:33 +0200 Subject: [PATCH] Fix a possible race with concurrent encryption with the same config MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit append() can allocate arrays with cap(s) > len(s), and future append() calls would then just write to the free slots; doing that from multiple goroutines would race. Signed-off-by: Miloslav Trmač --- keywrap/pkcs11/keywrapper_pkcs11.go | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/keywrap/pkcs11/keywrapper_pkcs11.go b/keywrap/pkcs11/keywrapper_pkcs11.go index 236764d..b9a83c5 100644 --- a/keywrap/pkcs11/keywrapper_pkcs11.go +++ b/keywrap/pkcs11/keywrapper_pkcs11.go @@ -41,7 +41,11 @@ func NewKeyWrapper() keywrap.KeyWrapper { // WrapKeys wraps the session key for recpients and encrypts the optsData, which // describe the symmetric key used for encrypting the layer func (kw *pkcs11KeyWrapper) WrapKeys(ec *config.EncryptConfig, optsData []byte) ([]byte, error) { - pkcs11Recipients, err := addPubKeys(&ec.DecryptConfig, append(ec.Parameters["pkcs11-pubkeys"], ec.Parameters["pkcs11-yamls"]...)) + // append({}, ...) allocates a fresh backing array, and that's necessary to guarantee concurrent calls to WrapKeys (as in c/image/copy.Image) + // can't race writing to the same backing array. + pubKeys := append([][]byte{}, ec.Parameters["pkcs11-pubkeys"]...) // In Go 1.21, slices.Clone(ec.Parameters["pkcs11-pubkeys"]) + pubKeys = append(pubKeys, ec.Parameters["pkcs11-yamls"]...) + pkcs11Recipients, err := addPubKeys(&ec.DecryptConfig, pubKeys) if err != nil { return nil, err }