Skip to content

Commit

Permalink
Keyloader: split LoadKey (sub function NewKey) (#26)
Browse files Browse the repository at this point in the history
* Keyloader: split LoadKey into a sub function NewKey() which directly accepts KeyConfig objects without going through configstore.

* Keyloader NewKey: sort key configs

* Update .travis.yaml
  • Loading branch information
loopfz committed Apr 24, 2020
1 parent 262d351 commit 55da9c7
Show file tree
Hide file tree
Showing 3 changed files with 125 additions and 30 deletions.
7 changes: 3 additions & 4 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
language: go
go:
- 1.11.x
- 1.12.x
- 1.13.x
- 1.14.x

# Only clone the most recent commit.
git:
Expand All @@ -15,8 +15,7 @@ notifications:
# build and immediately stop. It's sorta like having set -e enabled in bash.
# Make sure golangci-lint is vendored.
before_script:
- go get -v -u github.com/golangci/golangci-lint/cmd/golangci-lint
- go install github.com/golangci/golangci-lint/cmd/golangci-lint
- curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(go env GOPATH)/bin v1.25.0

# script always runs to completion (set +e). If we have linter issues AND a
# failing test, we want to see both. Configure golangci-lint with a
Expand Down
92 changes: 66 additions & 26 deletions keyloader/keyloader.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package keyloader

import (
"fmt"
"sort"
"strconv"
"sync"
"sync/atomic"
Expand Down Expand Up @@ -202,6 +203,7 @@ func reorderTimestamp(s *configstore.Item) int64 {
i, err := s.Unmarshaled()
if err == nil {
ret := i.(*KeyConfig).Timestamp
// small hack to tiebreak in favor of sealed keys (mostly in case of zero-value timestamp)
if i.(*KeyConfig).Sealed {
ret++
}
Expand All @@ -218,7 +220,62 @@ func configFactory() interface{} {
** CONSTRUCTORS
*/

// NewKey returns a symmecrypt.Key object configured from a number of KeyConfig objects.
// If several KeyConfigs are supplied, the returned Key will be composite.
// A composite key encrypts with the latest Key (based on timestamp) and decrypts with any of they keys.
//
// If the key configuration specifies it is sealed, the key returned will be wrapped by an unseal mechanism.
// When the symmecrypt/seal global singleton gets unsealed, the key will become usable instantly. It will return errors in the meantime.
//
// The key cipher name is expected to match a KeyFactory that got registered through RegisterCipher().
// Either use a built-in cipher, or make sure to register a proper factory for this cipher.
// This KeyFactory will be called, either directly or when the symmecrypt/seal global singleton gets unsealed, if applicable.
func NewKey(cfgs ...*KeyConfig) (symmecrypt.Key, error) {

if len(cfgs) == 0 {
return nil, errors.New("missing key config")
}

// sort by timestamp: latest (bigger timestamp) first
sort.Slice(cfgs, func(i, j int) bool { return cfgs[i].Timestamp > cfgs[j].Timestamp })

firstNonSealed := !cfgs[0].Sealed
comp := symmecrypt.CompositeKey{}

for _, cfg := range cfgs {

var ref symmecrypt.Key
factory, err := symmecrypt.GetKeyFactory(cfg.Cipher)
if err != nil {
return nil, err
}
if cfg.Sealed {
// if the first position (used for encryption in composite keys) was not sealed, but other keys used for fallback decryption are sealed
// it may be an attack to trigger a reencrypt with a key known by the attacker
if firstNonSealed {
return nil, errors.New("DANGER! Detected downgrade to non-sealed encryption key. Non-sealed key has higher priority, this looks malicious. Aborting!")
}
ref = newSealedKey(cfg, factory)
} else {
ref, err = factory.NewKey(cfg.Key)
if err != nil {
return nil, err
}
}

comp = append(comp, ref)
}

// if only a single key config was provided, decapsulate the composite key
if len(comp) == 1 {
return comp[0], nil
}

return comp, nil
}

// LoadKey instantiates a new encryption key for a given identifier from the default store in configstore.
// It retrieves all the necessary data from configstore then calls NewKey().
//
// If several keys are found for the identifier, they are sorted by timestamp, and a composite key is returned.
// The most recent key will be used for encryption, and decryption will be done by any of them.
Expand All @@ -235,6 +292,7 @@ func LoadKey(identifier string) (symmecrypt.Key, error) {
}

// LoadKeyFromStore instantiates a new encryption key for a given identifier from a specific store instance.
// It retrieves all the necessary data from configstore then calls NewKey().
//
// If several keys are found for the identifier, they are sorted by timestamp, and a composite key is returned.
// The most recent key will be used for encryption, and decryption will be done by any of them.
Expand All @@ -261,52 +319,34 @@ func LoadKeyFromStore(identifier string, store *configstore.Store) (symmecrypt.K
return nil, fmt.Errorf("ambiguous config: several encryption keys conflicting for '%s'", identifier)
}

comp := symmecrypt.CompositeKey{}

hadNonSealed := false
var cfgs []*KeyConfig

for _, item := range items.Items {

i, err := item.Unmarshaled()
if err != nil {
return nil, err
}
var ref symmecrypt.Key
cfg := i.(*KeyConfig)
factory, err := symmecrypt.GetKeyFactory(cfg.Cipher)
if err != nil {
return nil, err
}
if cfg.Sealed {
if hadNonSealed {
panic(fmt.Sprintf("encryption key '%s': DANGER! Detected downgrade to non-sealed encryption key. Non-sealed key has higher priority, this looks malicious. Aborting!", identifier))
}
ref = newSealedKey(cfg, factory)
} else {
hadNonSealed = true
ref, err = factory.NewKey(cfg.Key)
if err != nil {
return nil, err
}
}

comp = append(comp, ref)
cfgs = append(cfgs, cfg)
}

if len(comp) == 1 {
return comp[0], nil
key, err := NewKey(cfgs...)
if err != nil {
return nil, fmt.Errorf("encryption key '%s': %s", identifier, err)
}

return comp, nil
return key, nil
}

// LoadSingleKey instantiates a new encryption key using LoadKey from the default store in configstore without specifying its identifier.
// It retrieves all the necessary data from configstore then calls NewKey().
// It will error if several different identifiers are found.
func LoadSingleKey() (symmecrypt.Key, error) {
return LoadSingleKeyFromStore(configstore.DefaultStore)
}

// LoadSingleKey instantiates a new encryption key using LoadKey from a specific store instance without specifying its identifier.
// It retrieves all the necessary data from configstore then calls NewKey().
// It will error if several different identifiers are found.
func LoadSingleKeyFromStore(store *configstore.Store) (symmecrypt.Key, error) {
ident, err := singleKeyIdentifier(store)
Expand Down
56 changes: 56 additions & 0 deletions symmecrypt_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,49 @@ func ProviderTest() (configstore.ItemList, error) {
return ret, nil
}

// Bad config: conflicting timestamps
func ProviderTestKOTimestamp() (configstore.ItemList, error) {
ret := configstore.ItemList{
Items: []configstore.Item{
configstore.NewItem(
keyloader.EncryptionKeyConfigName,
`{"key":"5fdb8af280b007a46553dfddb3f42bc10619dcabca8d4fdf5239b09445ab1a41","identifier":"test","sealed":false,"timestamp":1,"cipher":"aes-gcm"}`,
1,
),
configstore.NewItem(
keyloader.EncryptionKeyConfigName,
`{"key":"QXdDW4N/jmJzpMu7i1zu4YF1opTn7H+eOk9CLFGBSFg=","identifier":"test","sealed":false,"timestamp":1,"cipher":"xchacha20-poly1305"}`,
1,
),
},
}
return ret, nil
}

// Bad config: latest key non sealed
func ProviderTestKOSeal() (configstore.ItemList, error) {
ret := configstore.ItemList{
Items: []configstore.Item{
configstore.NewItem(
keyloader.EncryptionKeyConfigName,
`{"key":"5fdb8af280b007a46553dfddb3f42bc10619dcabca8d4fdf5239b09445ab1a41","identifier":"test","sealed":false,"timestamp":10,"cipher":"aes-gcm"}`,
1,
),
configstore.NewItem(
keyloader.EncryptionKeyConfigName,
`{"key":"QXdDW4N/jmJzpMu7i1zu4YF1opTn7H+eOk9CLFGBSFg=","identifier":"test","sealed":true,"timestamp":1,"cipher":"xchacha20-poly1305"}`,
1,
),
},
}
return ret, nil
}

var KOTests = map[string]func() (configstore.ItemList, error){
"timestamp": ProviderTestKOTimestamp,
"seal": ProviderTestKOSeal,
}

func TestMain(m *testing.M) {

configstore.RegisterProvider("test", ProviderTest)
Expand Down Expand Up @@ -353,6 +396,19 @@ func TestWriterWithEncoders(t *testing.T) {
}
}

func TestKeyloaderKO(t *testing.T) {

for testName, provider := range KOTests {
st := configstore.NewStore()
st.RegisterProvider("test", provider)

_, err := keyloader.LoadKeyFromStore("test", st)
if err == nil {
t.Fatalf("nil error with KO config (%s)", testName)
}
}
}

func ExampleNewWriter() {
k, err := keyloader.LoadKey("test")
if err != nil {
Expand Down

0 comments on commit 55da9c7

Please sign in to comment.