From 407ec27649726439a8614d7b0aa2a2c94be6296e Mon Sep 17 00:00:00 2001 From: matrushka Date: Wed, 14 Feb 2018 12:31:22 +0100 Subject: [PATCH] Modified keystore to ignore invalid key files inside the keystore directory to address #4681 * Has calls the validateName function before checking if we have the file * List filters the returned list of file names by validateName. License: MIT Signed-off-by: matrushka --- keystore/keystore.go | 20 +++++++++++++- keystore/keystore_test.go | 57 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 76 insertions(+), 1 deletion(-) diff --git a/keystore/keystore.go b/keystore/keystore.go index 56dfd1b0137b..2db9a9b920cd 100644 --- a/keystore/keystore.go +++ b/keystore/keystore.go @@ -77,6 +77,10 @@ func (ks *FSKeystore) Has(name string) (bool, error) { return false, err } + if err := validateName(name); err != nil { + return false, err + } + return true, nil } @@ -149,5 +153,19 @@ func (ks *FSKeystore) List() ([]string, error) { return nil, err } - return dir.Readdirnames(0) + dirs, err := dir.Readdirnames(0) + if err != nil { + return nil, err + } + + var list []string + + for _, name := range dirs { + err := validateName(name) + if err == nil { + list = append(list, name) + } + } + + return list, err } diff --git a/keystore/keystore_test.go b/keystore/keystore_test.go index cf6281be20f4..f0c1b3105448 100644 --- a/keystore/keystore_test.go +++ b/keystore/keystore_test.go @@ -4,6 +4,7 @@ import ( "fmt" "io/ioutil" "math/rand" + "path/filepath" "sort" "testing" @@ -143,6 +144,62 @@ func TestKeystoreBasics(t *testing.T) { } } +func TestInvalidKeyFiles(t *testing.T) { + tdir, err := ioutil.TempDir("", "keystore-test") + + if err != nil { + t.Fatal(err) + } + + ks, err := NewFSKeystore(tdir) + if err != nil { + t.Fatal(err) + } + + key := privKeyOrFatal(t) + + bytes, err := key.Bytes() + if err != nil { + t.Fatal(err) + } + + err = ioutil.WriteFile(filepath.Join(ks.dir, "valid"), bytes, 0644) + if err != nil { + t.Fatal(err) + } + + err = ioutil.WriteFile(filepath.Join(ks.dir, ".invalid"), bytes, 0644) + if err != nil { + t.Fatal(err) + } + + l, err := ks.List() + if err != nil { + t.Fatal(err) + } + + sort.Strings(l) + if len(l) != 1 { + t.Fatal("wrong entry count") + } + + if l[0] != "valid" { + t.Fatal("wrong entries listed") + } + + exist, err := ks.Has("valid") + if !exist { + t.Fatal("should know it has a key named valid") + } + if err != nil { + t.Fatal(err) + } + + if exist, err = ks.Has(".invalid"); err == nil { + t.Fatal("shouldnt be able to put a key with a 'hidden' name") + } +} + func TestNonExistingKey(t *testing.T) { tdir, err := ioutil.TempDir("", "keystore-test") if err != nil {