From 934b497101f1817a518f5a0755b4fa03ef4aceae Mon Sep 17 00:00:00 2001 From: Brian Kassouf Date: Wed, 12 Jun 2019 08:56:16 -0700 Subject: [PATCH] Clear the Barrier AEAD cache on keyring reload (#6870) * Clear the barrier's AEAD cache on keyring reload * Update barrier_aes_gcm_test.go --- vault/barrier_aes_gcm.go | 1 + vault/barrier_aes_gcm_test.go | 79 +++++++++++++++++++++++++++++++++++ 2 files changed, 80 insertions(+) diff --git a/vault/barrier_aes_gcm.go b/vault/barrier_aes_gcm.go index d186879ab..fa02abbc3 100644 --- a/vault/barrier_aes_gcm.go +++ b/vault/barrier_aes_gcm.go @@ -287,6 +287,7 @@ func (b *AESGCMBarrier) ReloadKeyring(ctx context.Context) error { } // Setup the keyring and finish + b.cache = make(map[uint32]cipher.AEAD) b.keyring = keyring return nil } diff --git a/vault/barrier_aes_gcm_test.go b/vault/barrier_aes_gcm_test.go index 38960355b..b466bb305 100644 --- a/vault/barrier_aes_gcm_test.go +++ b/vault/barrier_aes_gcm_test.go @@ -516,3 +516,82 @@ func TestEncrypt_BarrierEncryptor(t *testing.T) { t.Fatalf("bad: %s", plain) } } + +func TestAESGCMBarrier_ReloadKeyring(t *testing.T) { + inm, err := inmem.NewInmem(nil, logger) + if err != nil { + t.Fatalf("err: %v", err) + } + b, err := NewAESGCMBarrier(inm) + if err != nil { + t.Fatalf("err: %v", err) + } + + // Initialize and unseal + key, _ := b.GenerateKey() + b.Initialize(context.Background(), key) + b.Unseal(context.Background(), key) + + keyringRaw, err := inm.Get(context.Background(), keyringPath) + if err != nil { + t.Fatalf("err: %v", err) + } + + // Encrypt something to test cache invalidation + _, err = b.Encrypt(context.Background(), "foo", []byte("quick brown fox")) + if err != nil { + t.Fatalf("err: %v", err) + } + + { + // Create a second barrier and rotate the keyring + b2, err := NewAESGCMBarrier(inm) + if err != nil { + t.Fatalf("err: %v", err) + } + b2.Unseal(context.Background(), key) + _, err = b2.Rotate(context.Background()) + if err != nil { + t.Fatalf("err: %v", err) + } + } + + // Reload the keyring on the first + err = b.ReloadKeyring(context.Background()) + if err != nil { + t.Fatalf("err: %v", err) + } + + if b.keyring.ActiveTerm() != 2 { + t.Fatal("failed to reload keyring") + } + if len(b.cache) != 0 { + t.Fatal("failed to clear cache") + } + + // Encrypt something to test cache invalidation + _, err = b.Encrypt(context.Background(), "foo", []byte("quick brown fox")) + if err != nil { + t.Fatalf("err: %v", err) + } + + // Restore old keyring to test rolling back + err = inm.Put(context.Background(), keyringRaw) + if err != nil { + t.Fatalf("err: %v", err) + } + + // Reload the keyring on the first + err = b.ReloadKeyring(context.Background()) + if err != nil { + t.Fatalf("err: %v", err) + } + + if b.keyring.ActiveTerm() != 1 { + t.Fatal("failed to reload keyring") + } + if len(b.cache) != 0 { + t.Fatal("failed to clear cache") + } + +}