diff --git a/keystore/keystore.go b/keystore/keystore.go index 56dfd1b0137..5dd43385280 100644 --- a/keystore/keystore.go +++ b/keystore/keystore.go @@ -7,9 +7,12 @@ import ( "path/filepath" "strings" + logging "gx/ipfs/QmRb5jh8z2E8hMGN2tkvs1yHynUanqnZ3UeKwgN1i9P1F8/go-log" ci "gx/ipfs/QmaPbCnUMBohSGo3KnxEa2bHqyJVVeEEcwtqJAYxerieBo/go-libp2p-crypto" ) +var log = logging.Logger("keystore") + // Keystore provides a key management interface type Keystore interface { // Has returns whether or not a key exist in the Keystore @@ -77,6 +80,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 +156,21 @@ func (ks *FSKeystore) List() ([]string, error) { return nil, err } - return dir.Readdirnames(0) + dirs, err := dir.Readdirnames(0) + if err != nil { + return nil, err + } + + list := make([]string, 0, len(dirs)) + + for _, name := range dirs { + err := validateName(name) + if err == nil { + list = append(list, name) + } else { + log.Warningf("Ignoring the invalid keyfile: %s", name) + } + } + + return list, nil } diff --git a/keystore/keystore_test.go b/keystore/keystore_test.go index cf6281be20f..0731f252bb5 100644 --- a/keystore/keystore_test.go +++ b/keystore/keystore_test.go @@ -4,6 +4,8 @@ import ( "fmt" "io/ioutil" "math/rand" + "os" + "path/filepath" "sort" "testing" @@ -143,6 +145,64 @@ func TestKeystoreBasics(t *testing.T) { } } +func TestInvalidKeyFiles(t *testing.T) { + tdir, err := ioutil.TempDir("", "keystore-test") + + if err != nil { + t.Fatal(err) + } + + defer os.RemoveAll(tdir) + + 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 {