diff --git a/weed/sftpd/sftp_exec.go b/weed/sftpd/sftp_exec.go new file mode 100644 index 0000000000..3a74580c25 --- /dev/null +++ b/weed/sftpd/sftp_exec.go @@ -0,0 +1,210 @@ +package sftpd + +import ( + "context" + "crypto/md5" + "crypto/sha1" + "encoding/hex" + "errors" + "fmt" + "hash" + "io" + "path" + "regexp" + "strings" + + "github.com/seaweedfs/seaweedfs/weed/glog" + filer_pb "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" + "golang.org/x/crypto/ssh" +) + +// The SSH "exec" requests answered here are the few that SFTP clients and +// scripts commonly run over the same connection to verify transfers by hash +// and show free space. +// There is no shell: each command is matched by name and its single path +// argument is resolved inside the user's home, with the user's permissions. +// +// echo prints text (clients use it to detect the shell type) +// md5sum [path] " ", or the empty-input hash without a path +// sha1sum [path] likewise +// df [-k] [path] one df -k style line for the filer's volume capacity + +// shellUnEscapeRegex undoes the backslash escaping clients apply to paths +var shellUnEscapeRegex = regexp.MustCompile(`\\(.)`) + +func shellUnEscape(s string) string { + s = strings.ReplaceAll(s, "'\n'", "\n") + return shellUnEscapeRegex.ReplaceAllString(s, `$1`) +} + +// trimCommand drops surrounding whitespace but keeps a trailing space that is +// escaped, since it is part of the last file name (`md5sum a\ `) +func trimCommand(command string) string { + command = strings.TrimLeft(command, " \t") + for len(command) > 0 && strings.ContainsRune(" \t\r\n", rune(command[len(command)-1])) { + backslashes := 0 + for i := len(command) - 2; i >= 0 && command[i] == '\\'; i-- { + backslashes++ + } + if backslashes%2 == 1 { + break + } + command = command[:len(command)-1] + } + return command +} + +// operandPath makes a command's path operand absolute in the user's view, +// where a relative name is relative to the home ("/"), as an SFTP client sees +// it; toAbsolutePath expects such a path +func operandPath(p string) string { + return path.Join("/", p) +} + +// ctxWriter fails writes once ctx is done, so a hash of a large sparse file +// stops writing zeros when the connection ends +type ctxWriter struct { + ctx context.Context + w io.Writer +} + +func (c ctxWriter) Write(p []byte) (int, error) { + if err := c.ctx.Err(); err != nil { + return 0, err + } + return c.w.Write(p) +} + +type execRequest struct { + Command string +} + +type subsystemRequest struct { + Name string +} + +type exitStatus struct { + Status uint32 +} + +// handleExec runs one exec request on channel and closes it, reporting the +// exit status the way a shell would. ctx ends with the channel, so a hash of a +// large file stops reading once the client closes the session. +func (s *SFTPService) handleExec(ctx context.Context, channel ssh.Channel, fs *SftpServer, command string) { + defer channel.Close() + status := uint32(0) + if err := fs.execCommand(ctx, channel, command); err != nil { + status = 1 + fmt.Fprintf(channel.Stderr(), "%v\n", err) + glog.V(1).Infof("sftp exec %q for %s: %v", command, fs.user.Username, err) + } + if _, err := channel.SendRequest("exit-status", false, ssh.Marshal(exitStatus{Status: status})); err != nil { + glog.V(1).Infof("sftp exec exit-status: %v", err) + } +} + +func (fs *SftpServer) execCommand(ctx context.Context, out io.Writer, command string) error { + name, args, _ := strings.Cut(trimCommand(command), " ") + args = strings.TrimLeft(args, " ") + switch name { + case "echo": + _, err := fmt.Fprintf(out, "%s\n", args) + return err + case "md5sum": + return fs.hashsum(ctx, out, "md5", shellUnEscape(args)) + case "sha1sum": + return fs.hashsum(ctx, out, "sha1", shellUnEscape(args)) + case "df": + if args == "-k" || strings.HasPrefix(args, "-k ") { + args = strings.TrimLeft(args[2:], " ") + } + return fs.df(ctx, out, shellUnEscape(args)) + default: + return fmt.Errorf("%s: command not supported", name) + } +} + +func newHash(kind string) hash.Hash { + if kind == "sha1" { + return sha1.New() + } + return md5.New() +} + +// hashsum prints the hash of the file at userPath, or of empty input when +// there is none, in the coreutils " " format +func (fs *SftpServer) hashsum(ctx context.Context, out io.Writer, kind, userPath string) error { + if userPath == "" { + _, err := fmt.Fprintf(out, "%s -\n", hex.EncodeToString(newHash(kind).Sum(nil))) + return err + } + sum, err := fs.fileHash(ctx, kind, userPath) + if err != nil { + return fmt.Errorf("%s: %s: %w", kind+"sum", userPath, err) + } + _, err = fmt.Fprintf(out, "%s %s\n", sum, userPath) + return err +} + +func (fs *SftpServer) fileHash(ctx context.Context, kind, userPath string) (string, error) { + absPath, err := fs.toAbsolutePath(operandPath(userPath)) + if err != nil { + return "", err + } + if err := fs.checkFilePermission(absPath, "read"); err != nil { + return "", err + } + entry, err := fs.getEntry(absPath) + if err != nil { + return "", err + } + if entry.IsDirectory { + return "", errors.New("is a directory") + } + // the filer keeps the MD5 of files uploaded in one piece, and writers + // clear it when they change the content; it is the same MD5 the S3 and + // WebDAV ETags report + if kind == "md5" && entry.Attributes != nil && len(entry.Attributes.Md5) > 0 { + return hex.EncodeToString(entry.Attributes.Md5), nil + } + h := newHash(kind) + if err := fs.writeContent(ctx, absPath, entry, ctxWriter{ctx, h}); err != nil { + return "", err + } + return hex.EncodeToString(h.Sum(nil)), nil +} + +// df prints the filer's volume capacity in df -k format; the path has to +// exist inside the user's home +func (fs *SftpServer) df(ctx context.Context, out io.Writer, userPath string) error { + if userPath == "" { + userPath = "/" + } + absPath, err := fs.toAbsolutePath(operandPath(userPath)) + if err == nil { + _, err = fs.getEntry(absPath) + } + if err != nil { + return fmt.Errorf("df: %s: %w", userPath, err) + } + var resp *filer_pb.StatisticsResponse + err = fs.callWithClient(false, func(ctx context.Context, client filer_pb.SeaweedFilerClient) error { + var err error + resp, err = client.Statistics(ctx, &filer_pb.StatisticsRequest{}) + return err + }) + if err != nil { + return fmt.Errorf("df: %w", err) + } + total, used := resp.TotalSize/1024, resp.UsedSize/1024 + avail := uint64(0) + if total > used { + avail = total - used + } + percent := uint64(0) + if total > 0 { + percent = (100*used + total - 1) / total + } + _, err = fmt.Fprintf(out, "Filesystem 1K-blocks Used Available Use%% Mounted on\nseaweedfs %d %d %d %d%% /\n", total, used, avail, percent) + return err +} diff --git a/weed/sftpd/sftp_exec_test.go b/weed/sftpd/sftp_exec_test.go new file mode 100644 index 0000000000..e5d43846f0 --- /dev/null +++ b/weed/sftpd/sftp_exec_test.go @@ -0,0 +1,276 @@ +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.setFileStatWithRequest("/buckets/b/f", req); 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() +} diff --git a/weed/sftpd/sftp_filer.go b/weed/sftpd/sftp_filer.go index 582f4d2a91..978edadfc0 100644 --- a/weed/sftpd/sftp_filer.go +++ b/weed/sftpd/sftp_filer.go @@ -218,6 +218,12 @@ func (fs *SftpServer) copyExistingContent(absPath string, dst io.Writer) error { if entry.IsDirectory { return nil } + return fs.writeContent(context.Background(), absPath, entry, dst) +} + +// writeContent writes the file's whole logical content to dst: inline bytes, +// then chunks, with zeros for the gaps and tail no chunk stores. +func (fs *SftpServer) writeContent(ctx context.Context, absPath string, entry *filer_pb.Entry, dst io.Writer) error { size := int64(filer.FileSize(entry)) remote := entry.GetRemoteEntry() if len(entry.Content) == 0 && len(entry.GetChunks()) == 0 { @@ -241,7 +247,7 @@ func (fs *SftpServer) copyExistingContent(absPath string, dst io.Writer) error { } return nil } - streamFn, err := filer.PrepareStreamContent(lookupFileIdFn(filer.LookupFn(fs)), filer.JwtForVolumeServer, entry.GetChunks(), 0, size) + streamFn, err := filer.PrepareStreamContentWithThrottler(ctx, lookupFileIdFn(filer.LookupFn(fs)), filer.JwtForVolumeServer, entry.GetChunks(), 0, size, 0) if err != nil { return fmt.Errorf("read existing content of %s: %w", absPath, err) } @@ -475,7 +481,11 @@ func (fs *SftpServer) setFileStatWithRequest(absPath string, r *sftp.Request) er entry.Attributes.Mtime = int64(r.Attributes().Mtime) } if r.AttrFlags().Size { - entry.Attributes.FileSize = uint64(r.Attributes().Size) + if size := uint64(r.Attributes().Size); size != entry.Attributes.FileSize { + entry.Attributes.FileSize = size + // the stored MD5 described the old content + entry.Attributes.Md5 = nil + } } return fs.updateEntry(dir, entry) } diff --git a/weed/sftpd/sftp_service.go b/weed/sftpd/sftp_service.go index e5c9501e66..97c28a5b89 100644 --- a/weed/sftpd/sftp_service.go +++ b/weed/sftpd/sftp_service.go @@ -228,7 +228,7 @@ func (s *SFTPService) handleSSHConnection(conn net.Conn, config *ssh.ServerConfi // Handle SSH requests and channels go ssh.DiscardRequests(reqs) for newChannel := range chans { - go s.handleChannel(newChannel, &userFs) + go s.handleChannel(ctx, newChannel, &userFs) } } @@ -268,7 +268,7 @@ func (s *SFTPService) monitorConnection(ctx context.Context, sshConn *ssh.Server } // handleChannel handles a single SSH channel. -func (s *SFTPService) handleChannel(newChannel ssh.NewChannel, fs *SftpServer) { +func (s *SFTPService) handleChannel(ctx context.Context, newChannel ssh.NewChannel, fs *SftpServer) { if newChannel.ChannelType() != "session" { _ = newChannel.Reject(ssh.UnknownChannelType, "unknown channel type") return @@ -281,16 +281,32 @@ func (s *SFTPService) handleChannel(newChannel ssh.NewChannel, fs *SftpServer) { } go func(in <-chan *ssh.Request) { + // in closes when the client closes the channel, which ends this + // channel's exec even while the connection stays open + channelCtx, cancel := context.WithCancel(ctx) + defer cancel() + // a channel runs one command or one SFTP session, as with OpenSSH + started := false for req := range in { switch req.Type { case "subsystem": - // Check that the subsystem is "sftp". - if string(req.Payload[4:]) == "sftp" { + var sub subsystemRequest + if !started && ssh.Unmarshal(req.Payload, &sub) == nil && sub.Name == "sftp" { + started = true _ = req.Reply(true, nil) s.handleSFTP(channel, fs) } else { _ = req.Reply(false, nil) } + case "exec": + var exec execRequest + if started || ssh.Unmarshal(req.Payload, &exec) != nil { + _ = req.Reply(false, nil) + continue + } + started = true + _ = req.Reply(true, nil) + go s.handleExec(channelCtx, channel, fs, exec.Command) default: _ = req.Reply(false, nil) }