From 3bb31554f1bd0cb74c0905e7d57dcce1697a3c60 Mon Sep 17 00:00:00 2001 From: Chris Lu Date: Fri, 4 Dec 2026 02:10:53 -0800 Subject: [PATCH] sftp: fail the hash of an out-of-range size Co-Authored-By: Claude Opus 5.5 --- weed/sftpd/sftp_exec.go | 7 ++++++- weed/sftpd/sftp_exec_test.go | 14 ++++++++++---- 2 files changed, 16 insertions(+), 5 deletions(-) diff --git a/weed/sftpd/sftp_exec.go b/weed/sftpd/sftp_exec.go index 934f1b1028..fd511e16fe 100644 --- a/weed/sftpd/sftp_exec.go +++ b/weed/sftpd/sftp_exec.go @@ -9,6 +9,7 @@ import ( "fmt" "hash" "io" + "math" "path" "regexp" "strings" @@ -168,8 +169,12 @@ func (fs *SftpServer) fileHash(ctx context.Context, kind, userPath string) (stri if kind == "md5" && entry.Attributes != nil && len(entry.Attributes.Md5) > 0 { return hex.EncodeToString(entry.Attributes.Md5), nil } + size := filer.FileSize(entry) + if size > math.MaxInt64 { + return "", fmt.Errorf("size %d is out of range", size) + } h := newHash(kind) - if err := fs.writeContent(ctx, absPath, entry, int64(filer.FileSize(entry)), ctxWriter{ctx, h}); err != nil { + if err := fs.writeContent(ctx, absPath, entry, int64(size), ctxWriter{ctx, h}); err != nil { return "", err } return hex.EncodeToString(h.Sum(nil)), nil diff --git a/weed/sftpd/sftp_exec_test.go b/weed/sftpd/sftp_exec_test.go index 6eba3258e5..b0fcd604bb 100644 --- a/weed/sftpd/sftp_exec_test.go +++ b/weed/sftpd/sftp_exec_test.go @@ -180,14 +180,20 @@ func TestFileHashStopsWhenCanceled(t *testing.T) { } } -// A stored size past the largest file offset does not crash the hash. +// A stored size past the largest file offset fails the hash instead of +// crashing it or reporting the digest of empty input. func TestFileHashOutOfRangeSize(t *testing.T) { fs := newCopyTestServer(t, "127.0.0.1:1", map[string]*filer_pb.Entry{ - "/home/huge.txt": {Name: "huge.txt", Content: []byte("x"), Attributes: &filer_pb.FuseAttributes{FileSize: 1 << 63}}, + "/home/huge.txt": {Name: "huge.txt", Content: []byte("x"), Attributes: &filer_pb.FuseAttributes{FileSize: 1 << 63}}, + "/home/empty.txt": {Name: "empty.txt", Attributes: &filer_pb.FuseAttributes{}}, }) fs.user.Permissions = map[string][]string{"/": {"read"}} - if _, err := fs.fileHash(context.Background(), "sha1", "/home/huge.txt"); err != nil { - t.Fatalf("hash: %v", err) + if sum, err := fs.fileHash(context.Background(), "sha1", "/home/huge.txt"); err == nil { + t.Fatalf("hash of an out-of-range size = %s, want an error", sum) + } + empty := sha1.Sum(nil) + if sum, err := fs.fileHash(context.Background(), "sha1", "/home/empty.txt"); err != nil || sum != hex.EncodeToString(empty[:]) { + t.Fatalf("hash of an empty file = %s, %v", sum, err) } }