repository: reject key and config files that are too short (#21977)

Signed-off-by: Arpit Jain <arpitjain099@gmail.com>
This commit is contained in:
Arpit Jain authored and GitHub committed 2026-07-22 20:38:07 +00:00
1 parent d4088aa09b
commit 8baffc4027
4 files changed
+65

No files matched your search

@@ -14,6 +14,7 @@ import (
"github.com/google/go-cmp/cmp"
"github.com/klauspost/compress/zstd"
"github.com/restic/restic/internal/backend"
"github.com/restic/restic/internal/backend/mem"
"github.com/restic/restic/internal/errors"
"github.com/restic/restic/internal/repository/crypto"
"github.com/restic/restic/internal/repository/index"
@@ -576,3 +577,50 @@ func TestStreamPackFallback(t *testing.T) {
test(t, true)
})
}
// A key file is just JSON in the repository, so its "data" field can be any
// length an attacker with write access to the backend picks. Make sure a
// short one is rejected instead of tripping a slice bounds panic.
func TestOpenKeyShortData(t *testing.T) {
for _, data := range [][]byte{nil, {}, make([]byte, 1), make([]byte, crypto.CiphertextLength(0)-1)} {
be := mem.New()
repo, err := New(be, Options{})
rtest.OK(t, err)
key := Key{
KDF: "scrypt",
N: 1024,
R: 8,
P: 1,
Salt: make([]byte, 64),
Data: data,
}
buf, err := json.Marshal(key)
rtest.OK(t, err)
id := restic.Hash(buf)
h := backend.Handle{Type: backend.KeyFile, Name: id.String()}
rtest.OK(t, be.Save(context.TODO(), h, backend.NewByteReader(buf, be.Hasher())))
_, err = openKey(context.TODO(), repo, id, "geheim")
rtest.Assert(t, err != nil, "expected an error for key data of length %d", len(data))
rtest.Assert(t, strings.Contains(err.Error(), "too short"),
"expected a 'too short' error, got %v", err)
}
}
// The config file is exempt from the ID check in LoadRaw, so a truncated one
// reaches the decryption path unfiltered.
func TestLoadUnpackedShortData(t *testing.T) {
be := mem.New()
repo, err := New(be, Options{})
rtest.OK(t, err)
h := backend.Handle{Type: backend.ConfigFile, Name: restic.ID{}.String()}
rtest.OK(t, be.Save(context.TODO(), h, backend.NewByteReader([]byte{}, be.Hasher())))
repo.key = crypto.NewRandomKey()
_, err = repo.LoadUnpacked(context.TODO(), restic.ConfigFile, restic.ID{})
rtest.Assert(t, err != nil && strings.Contains(err.Error(), "too short"),
"expected a 'too short' error, got %v", err)
}