mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-05 02:27:26 +01:00
* sftp: create uploaded files with mode 0644 The upload writer carried a 0644 mode that never reached the filer, so the PUT fell back to the filer default of 0660. Pass the mode on the PUT, as OpenSSH's sftp-server creates new files 0666 minus a 022 umask. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * sftp: keep an existing file's mode when an upload overwrites it An overwrite went through the same PUT as a new file, so a 0600 file came back with the default mode. Send the stored mode instead, as open(2) on an existing file keeps it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * sftp: apply an fsetstat sent while an upload is still buffering "put -p" sets the mode and times on the open handle before closing it, but the upload only reaches the filer on close, so the setstat found no entry and the client failed with "No such file or directory". Keep such attributes on the open upload: a size cuts the buffered bytes, the mode goes on the PUT, and the rest is set once the file is stored. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * sftp: clear the sub-second part of an mtime a setstat replaces SFTP times are whole seconds, but the stored nanoseconds of the old mtime stayed, so a touched or "put -p" file showed a time the client never set. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * sftp: set the attributes queued on an upload in its post-upload update A new file can be under its bucket's default retention as soon as the PUT stores it, and a setstat after that is refused, so "put -p" into such a bucket stored the file and then failed the close. Apply the queued attributes in the update that already sets the owner after the upload. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * sftp: leave a setstat alone when two uploads share its path A setstat carries only the path, so with two uploads of one path open in a session it went to whichever opened last, and a size cut the other upload's bytes. Route it to an upload only when that upload is the only one open. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * sftp: fail the close when an upload's queued attributes are not stored The setstat already answered success, so a failed post-upload update was only logged and "put -p" lost the times without the client knowing. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
277 lines
10 KiB
Go
277 lines
10 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 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 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()
|
|
}
|