mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-05 18:47:20 +01:00
* sftp: copy only the stored bytes on a non-truncating open A size set by a truncate that grows a file stores nothing, but opening the file for writing without O_TRUNC copied its whole logical size into the temp file as zeros. Copy up to the last stored byte and extend the temp file to the size, which leaves the rest sparse. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * sftp: upload only up to the written data on close Close streamed the whole temp file, so a hole after the data, from a truncate that grew the file before or during the open, was read back and uploaded as zeros. Track where the copied and written bytes end, upload up to there, and keep the rest as the file's size. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * sftp: leave the data end alone on an empty write A zero-length WRITE far past the data moved the data end there, so Close uploaded the hole before it as zeros. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * sftp: cap what the test filer reads from an upload An upload that wrongly carries a large hole now fails the test instead of filling memory. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * sftp: hash nothing past an out-of-range size A stored size past the largest file offset turned negative and sliced the inline content out of range. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * sftp: refuse a setstat size past the largest file offset Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * sftp: fail the hash of an out-of-range size Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * sftp: check the size before returning a stored md5 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
309 lines
12 KiB
Go
309 lines
12 KiB
Go
package sftpd
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"crypto/ed25519"
|
|
"crypto/md5"
|
|
"crypto/rand"
|
|
"crypto/sha1"
|
|
"encoding/binary"
|
|
"encoding/hex"
|
|
"errors"
|
|
"net"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"strings"
|
|
"testing"
|
|
|
|
"github.com/pkg/sftp"
|
|
"github.com/seaweedfs/seaweedfs/weed/pb"
|
|
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
|
"github.com/seaweedfs/seaweedfs/weed/sftpd/user"
|
|
"golang.org/x/crypto/ssh"
|
|
"google.golang.org/grpc"
|
|
"google.golang.org/grpc/credentials/insecure"
|
|
)
|
|
|
|
type execTestFiler struct {
|
|
permissionTestFiler
|
|
}
|
|
|
|
func (f *execTestFiler) Statistics(context.Context, *filer_pb.StatisticsRequest) (*filer_pb.StatisticsResponse, error) {
|
|
return &filer_pb.StatisticsResponse{TotalSize: 4 << 30, UsedSize: 1 << 30}, nil
|
|
}
|
|
|
|
func newExecTestServer(t *testing.T) *SftpServer {
|
|
t.Helper()
|
|
lis, err := net.Listen("tcp", "127.0.0.1:0")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
attr := func(mode uint32) *filer_pb.FuseAttributes {
|
|
return &filer_pb.FuseAttributes{Uid: 1000, FileMode: mode}
|
|
}
|
|
filer := &execTestFiler{permissionTestFiler{entries: map[string]*filer_pb.Entry{
|
|
"/": {IsDirectory: true, Attributes: &filer_pb.FuseAttributes{FileMode: 0755}},
|
|
"/home": {IsDirectory: true, Attributes: &filer_pb.FuseAttributes{FileMode: 0755}},
|
|
"/home/alice": {IsDirectory: true, Attributes: attr(0755)},
|
|
"/home/alice/dir": {IsDirectory: true, Attributes: attr(0755)},
|
|
"/home/alice/a b": {Attributes: &filer_pb.FuseAttributes{Uid: 1000, FileMode: 0644, FileSize: 5}, Content: []byte("hello")},
|
|
"/home/alice/a ": {Attributes: &filer_pb.FuseAttributes{Uid: 1000, FileMode: 0644, FileSize: 1}, Content: []byte("x")},
|
|
"/home/alice/sum": {Attributes: &filer_pb.FuseAttributes{Uid: 1000, FileMode: 0644, FileSize: 3, Md5: []byte{0xab, 0xcd}}},
|
|
"/home/alice/drop": {Attributes: attr(0644), Content: []byte("x")},
|
|
"/home/bob": {IsDirectory: true, Attributes: &filer_pb.FuseAttributes{Uid: 1001, FileMode: 0755}},
|
|
"/home/bob/private": {Attributes: &filer_pb.FuseAttributes{Uid: 1001, FileMode: 0644}, Content: []byte("x")},
|
|
}}}
|
|
srv := grpc.NewServer()
|
|
filer_pb.RegisterSeaweedFilerServer(srv, filer)
|
|
go func() { _ = srv.Serve(lis) }()
|
|
t.Cleanup(srv.Stop)
|
|
_, port, _ := net.SplitHostPort(lis.Addr().String())
|
|
return &SftpServer{
|
|
filerAddr: pb.ServerAddress("127.0.0.1:0." + port),
|
|
grpcDialOption: grpc.WithTransportCredentials(insecure.NewCredentials()),
|
|
user: &user.User{
|
|
Username: "alice", Uid: 1000, Gid: 1000, HomeDir: "/home/alice",
|
|
Permissions: map[string][]string{
|
|
"/home/alice": {"readwrite"},
|
|
"/home/alice/drop": {"write"},
|
|
},
|
|
},
|
|
}
|
|
}
|
|
|
|
func TestExecCommands(t *testing.T) {
|
|
fs := newExecTestServer(t)
|
|
for _, tc := range []struct {
|
|
command, want string
|
|
}{
|
|
{"echo ${ShellId}%ComSpec%", "${ShellId}%ComSpec%\n"},
|
|
{"md5sum", "d41d8cd98f00b204e9800998ecf8427e -\n"},
|
|
{"sha1sum", "da39a3ee5e6b4b0d3255bfef95601890afd80709 -\n"},
|
|
{`md5sum /a\ b`, "5d41402abc4b2a76b9719d911017c592 /a b\n"},
|
|
{`sha1sum a\ b`, "aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d a b\n"},
|
|
{"md5sum /sum", "abcd /sum\n"},
|
|
{"md5sum a\\ \n", "9dd4e461268c8034f5c8564e155c67a6 a \n"},
|
|
{"md5sum a\\ ", "9dd4e461268c8034f5c8564e155c67a6 a \n"},
|
|
{"df -k ../..", "Filesystem 1K-blocks Used Available Use% Mounted on\nseaweedfs 4194304 1048576 3145728 25% /\n"}, // stays in the home, as over SFTP
|
|
{"df -k dir", "Filesystem 1K-blocks Used Available Use% Mounted on\nseaweedfs 4194304 1048576 3145728 25% /\n"},
|
|
{"df -k /", "Filesystem 1K-blocks Used Available Use% Mounted on\nseaweedfs 4194304 1048576 3145728 25% /\n"},
|
|
} {
|
|
var out bytes.Buffer
|
|
if err := fs.execCommand(context.Background(), &out, tc.command); err != nil {
|
|
t.Errorf("%s: %v", tc.command, err)
|
|
continue
|
|
}
|
|
if out.String() != tc.want {
|
|
t.Errorf("%s = %q, want %q", tc.command, out.String(), tc.want)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestExecCommandsRefused(t *testing.T) {
|
|
fs := newExecTestServer(t)
|
|
for command, why := range map[string]string{
|
|
"md5sum /drop": "a file without read permission",
|
|
"md5sum ../bob/private": "a path outside the home",
|
|
"sha1sum /dir": "a directory",
|
|
"md5sum /missing": "a missing file",
|
|
"cat /a\\ b": "an unsupported command",
|
|
"md5sum /a\\ b; rm -rf /": "a path that does not exist (no shell)",
|
|
"df -k /missing": "a missing path",
|
|
"df -kdir": "an option glued to a path",
|
|
} {
|
|
var out bytes.Buffer
|
|
if err := fs.execCommand(context.Background(), &out, command); err == nil {
|
|
t.Errorf("%q succeeded on %s: %q", command, why, out.String())
|
|
} else if strings.Contains(out.String(), " ") {
|
|
t.Errorf("%q printed a hash on %s", command, why)
|
|
}
|
|
}
|
|
}
|
|
|
|
// A file's holes and unstored tail are zeros, and they count toward its hash.
|
|
func TestFileHashIncludesSparseGaps(t *testing.T) {
|
|
chunkA := []byte("AAAAAAAAAA")
|
|
chunkB := []byte("BBBBBBBBBB")
|
|
objects := map[string][]byte{"3,01": chunkA, "3,02": chunkB}
|
|
volume := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
data, ok := objects[r.URL.Path[1:]]
|
|
if !ok {
|
|
http.Error(w, "not found", http.StatusNotFound)
|
|
return
|
|
}
|
|
_, _ = w.Write(data)
|
|
}))
|
|
t.Cleanup(volume.Close)
|
|
|
|
fs := newCopyTestServer(t, volume.Listener.Addr().String(), map[string]*filer_pb.Entry{
|
|
"/home/sparse.bin": chunkedEntry(120, fileChunk("3,01", 0, 10), fileChunk("3,02", 90, 10)),
|
|
"/home/holes.bin": chunkedEntry(10),
|
|
})
|
|
fs.user.Permissions = map[string][]string{"/": {"read"}}
|
|
// a relative operand is relative to the user's home, here "/"
|
|
var out bytes.Buffer
|
|
if err := fs.execCommand(context.Background(), &out, "sha1sum home/holes.bin"); err != nil || !strings.HasPrefix(out.String(), "9694c4ebd673a5e2fd26e4b2e64f92e914ebd95f ") {
|
|
t.Errorf("relative sha1sum = %q, %v", out.String(), err)
|
|
}
|
|
if err := fs.execCommand(context.Background(), &out, "df -k missing"); err == nil {
|
|
t.Error("df of a missing relative path succeeded")
|
|
}
|
|
sparse := append(append(append(append([]byte{}, chunkA...), make([]byte, 80)...), chunkB...), make([]byte, 20)...)
|
|
for path, content := range map[string][]byte{"/home/sparse.bin": sparse, "/home/holes.bin": make([]byte, 10)} {
|
|
md5Want, sha1Want := md5.Sum(content), sha1.Sum(content)
|
|
for kind, want := range map[string]string{"md5": hex.EncodeToString(md5Want[:]), "sha1": hex.EncodeToString(sha1Want[:])} {
|
|
got, err := fs.fileHash(context.Background(), kind, path)
|
|
if err != nil {
|
|
t.Fatalf("%s %s: %v", kind, path, err)
|
|
}
|
|
if got != want {
|
|
t.Errorf("%s %s = %s, want %s", kind, path, got, want)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// Once the connection is gone, a hash stops instead of reading on.
|
|
func TestFileHashStopsWhenCanceled(t *testing.T) {
|
|
fs := newCopyTestServer(t, "127.0.0.1:1", map[string]*filer_pb.Entry{
|
|
"/home/big.bin": chunkedEntry(10, fileChunk("3,01", 0, 10)),
|
|
"/home/holes.bin": chunkedEntry(1 << 40),
|
|
})
|
|
fs.user.Permissions = map[string][]string{"/": {"read"}}
|
|
ctx, cancel := context.WithCancel(context.Background())
|
|
cancel()
|
|
for _, p := range []string{"/home/big.bin", "/home/holes.bin"} {
|
|
if _, err := fs.fileHash(ctx, "sha1", p); !errors.Is(err, context.Canceled) {
|
|
t.Fatalf("hash of %s with a canceled context: err = %v, want context.Canceled", p, err)
|
|
}
|
|
}
|
|
}
|
|
|
|
// 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, Md5: []byte{0xab}}},
|
|
"/home/empty.txt": {Name: "empty.txt", Attributes: &filer_pb.FuseAttributes{}},
|
|
})
|
|
fs.user.Permissions = map[string][]string{"/": {"read"}}
|
|
for _, kind := range []string{"md5", "sha1"} {
|
|
if sum, err := fs.fileHash(context.Background(), kind, "/home/huge.txt"); err == nil {
|
|
t.Fatalf("%s of an out-of-range size = %s, want an error", kind, 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)
|
|
}
|
|
}
|
|
|
|
// A size change through SFTP drops the stored MD5, which md5sum would report;
|
|
// other attribute changes keep it.
|
|
func TestSetstatSizeClearsMd5(t *testing.T) {
|
|
sum := []byte{0xab, 0xcd}
|
|
fs, fake := newLockTestServer(t, map[string]*filer_pb.Entry{
|
|
"/buckets/b": {Name: "b", IsDirectory: true},
|
|
"/buckets/b/f": {Name: "f", Attributes: &filer_pb.FuseAttributes{FileSize: 1, Md5: sum}},
|
|
})
|
|
for size, keep := range map[uint64]bool{2: false, 1: true} {
|
|
req := sftp.NewRequest("Setstat", "/b/f")
|
|
req.Flags = 1 // SSH_FILEXFER_ATTR_SIZE
|
|
req.Attrs = binary.BigEndian.AppendUint64(nil, size)
|
|
if err := fs.setFileStat("/buckets/b/f", req.AttrFlags(), req.Attributes()); err != nil {
|
|
t.Fatalf("setstat size %d: %v", size, err)
|
|
}
|
|
got := fake.lastUpdate.Entry.Attributes
|
|
if got.FileSize != size || (len(got.Md5) > 0) != keep {
|
|
t.Errorf("setstat size %d: FileSize=%d Md5=%x, want Md5 kept=%v", size, got.FileSize, got.Md5, keep)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestSetstatRejectsOutOfRangeSize(t *testing.T) {
|
|
fs, fake := newLockTestServer(t, map[string]*filer_pb.Entry{
|
|
"/buckets/b": {Name: "b", IsDirectory: true},
|
|
"/buckets/b/f": {Name: "f", Content: []byte("x"), Attributes: &filer_pb.FuseAttributes{FileSize: 1}},
|
|
})
|
|
if err := fs.setFileStat("/buckets/b/f", sftp.FileAttrFlags{Size: true}, &sftp.FileStat{Size: 1 << 63}); err == nil {
|
|
t.Fatal("setstat of a size past the largest file offset succeeded")
|
|
}
|
|
if fake.lastUpdate != nil {
|
|
t.Fatalf("stored %v", fake.lastUpdate.Entry)
|
|
}
|
|
}
|
|
|
|
func openTestSession(t *testing.T, fs *SftpServer) ssh.Channel {
|
|
t.Helper()
|
|
_, key, err := ed25519.GenerateKey(rand.Reader)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
signer, err := ssh.NewSignerFromKey(key)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
config := &ssh.ServerConfig{NoClientAuth: true}
|
|
config.AddHostKey(signer)
|
|
lis, err := net.Listen("tcp", "127.0.0.1:0")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
t.Cleanup(func() { _ = lis.Close() })
|
|
go func() {
|
|
serverSide, err := lis.Accept()
|
|
if err != nil {
|
|
return
|
|
}
|
|
_, chans, reqs, err := ssh.NewServerConn(serverSide, config)
|
|
if err != nil {
|
|
return
|
|
}
|
|
go ssh.DiscardRequests(reqs)
|
|
for newChannel := range chans {
|
|
(&SFTPService{}).handleChannel(context.Background(), newChannel, fs)
|
|
}
|
|
}()
|
|
client, err := ssh.Dial("tcp", lis.Addr().String(), &ssh.ClientConfig{
|
|
User: "alice", HostKeyCallback: ssh.InsecureIgnoreHostKey(),
|
|
})
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
t.Cleanup(func() { _ = client.Close() })
|
|
channel, requests, err := client.OpenChannel("session", nil)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
go ssh.DiscardRequests(requests)
|
|
return channel
|
|
}
|
|
|
|
// A subsystem request has to name the sftp subsystem.
|
|
func TestSubsystemRequestNeedsSftpName(t *testing.T) {
|
|
channel := openTestSession(t, newExecTestServer(t))
|
|
for _, payload := range [][]byte{nil, {0, 0}, ssh.Marshal(subsystemRequest{Name: "shell"})} {
|
|
if ok, err := channel.SendRequest("subsystem", true, payload); ok || err != nil {
|
|
t.Fatalf("subsystem %q: ok = %v, err = %v; want refused", payload, ok, err)
|
|
}
|
|
}
|
|
}
|
|
|
|
// A channel runs one exec or subsystem, so an sftp subsystem asked for while
|
|
// an exec runs is refused.
|
|
func TestChannelRefusesSecondStartup(t *testing.T) {
|
|
fs := newCopyTestServer(t, "127.0.0.1:1", map[string]*filer_pb.Entry{
|
|
"/home/holes.bin": chunkedEntry(1 << 40),
|
|
})
|
|
fs.user.Permissions = map[string][]string{"/": {"read"}}
|
|
channel := openTestSession(t, fs)
|
|
if ok, err := channel.SendRequest("exec", true, ssh.Marshal(execRequest{Command: "sha1sum /home/holes.bin"})); !ok || err != nil {
|
|
t.Fatalf("exec: ok = %v, err = %v", ok, err)
|
|
}
|
|
if ok, err := channel.SendRequest("subsystem", true, ssh.Marshal(subsystemRequest{Name: "sftp"})); ok || err != nil {
|
|
t.Fatalf("sftp subsystem during an exec: ok = %v, err = %v; want refused", ok, err)
|
|
}
|
|
_ = channel.Close()
|
|
}
|