From 3c722a94989b3537aeca241efafbd39541b47a1e Mon Sep 17 00:00:00 2001 From: Roman Khimov Date: Thu, 1 Sep 2022 22:06:18 +0300 Subject: [PATCH] keys: clean temporary data during key imports Don't leak anything this way. --- pkg/crypto/keys/nep2.go | 11 ++++++++++- pkg/crypto/keys/private_key.go | 2 ++ pkg/crypto/keys/wif.go | 2 ++ 3 files changed, 14 insertions(+), 1 deletion(-) diff --git a/pkg/crypto/keys/nep2.go b/pkg/crypto/keys/nep2.go index abfa9277d..dd4ab206d 100644 --- a/pkg/crypto/keys/nep2.go +++ b/pkg/crypto/keys/nep2.go @@ -7,6 +7,7 @@ import ( "github.com/nspcc-dev/neo-go/pkg/crypto/hash" "github.com/nspcc-dev/neo-go/pkg/encoding/base58" + "github.com/nspcc-dev/neo-go/pkg/util/slice" "golang.org/x/crypto/scrypt" "golang.org/x/text/unicode/norm" ) @@ -52,10 +53,15 @@ func NEP2Encrypt(priv *PrivateKey, passphrase string, params ScryptParams) (s st if err != nil { return s, err } + defer slice.Clean(derivedKey) derivedKey1 := derivedKey[:32] derivedKey2 := derivedKey[32:] - xr := xor(priv.Bytes(), derivedKey1) + + privBytes := priv.Bytes() + defer slice.Clean(privBytes) + xr := xor(privBytes, derivedKey1) + defer slice.Clean(xr) encrypted, err := aesEncrypt(xr, derivedKey2) if err != nil { @@ -93,6 +99,7 @@ func NEP2Decrypt(key, passphrase string, params ScryptParams) (*PrivateKey, erro if err != nil { return nil, err } + defer slice.Clean(derivedKey) derivedKey1 := derivedKey[:32] derivedKey2 := derivedKey[32:] @@ -102,8 +109,10 @@ func NEP2Decrypt(key, passphrase string, params ScryptParams) (*PrivateKey, erro if err != nil { return nil, err } + defer slice.Clean(decrypted) privBytes := xor(decrypted, derivedKey1) + defer slice.Clean(privBytes) // Rebuild the private key. privKey, err := NewPrivateKeyFromBytes(privBytes) diff --git a/pkg/crypto/keys/private_key.go b/pkg/crypto/keys/private_key.go index 775c8e556..744e49ab1 100644 --- a/pkg/crypto/keys/private_key.go +++ b/pkg/crypto/keys/private_key.go @@ -13,6 +13,7 @@ import ( "github.com/btcsuite/btcd/btcec" "github.com/nspcc-dev/neo-go/pkg/crypto/hash" "github.com/nspcc-dev/neo-go/pkg/util" + "github.com/nspcc-dev/neo-go/pkg/util/slice" "github.com/nspcc-dev/rfc6979" ) @@ -48,6 +49,7 @@ func NewPrivateKeyFromHex(str string) (*PrivateKey, error) { if err != nil { return nil, err } + defer slice.Clean(b) return NewPrivateKeyFromBytes(b) } diff --git a/pkg/crypto/keys/wif.go b/pkg/crypto/keys/wif.go index 0e4d57b3d..7da78ea8e 100644 --- a/pkg/crypto/keys/wif.go +++ b/pkg/crypto/keys/wif.go @@ -5,6 +5,7 @@ import ( "fmt" "github.com/nspcc-dev/neo-go/pkg/encoding/base58" + "github.com/nspcc-dev/neo-go/pkg/util/slice" ) const ( @@ -53,6 +54,7 @@ func WIFDecode(wif string, version byte) (*WIF, error) { if err != nil { return nil, err } + defer slice.Clean(b) if version == 0x00 { version = WIFVersion