Files
seaweedfs/weed/sftpd/sftp_exec_test.go
T
f88ca328da sftp: answer md5sum, sha1sum, df and echo exec requests (#13277)
* sftp: answer md5sum, sha1sum, df and echo exec requests

SFTP clients such as rclone verify transfers and show free space by running
md5sum/sha1sum/df over an SSH exec request. weed sftp rejected every exec
request, so rclone fell back to comparing sizes and could not report usage.

Answer the few commands those clients send, without a shell:

- echo <text>: prints text (rclone's shell detection)
- md5sum/sha1sum [path]: the file's hash in coreutils format, or the
  empty-input hash without a path (the support probe). The path is resolved
  inside the user's home and needs read permission. MD5 uses the hash the
  filer stored when there is one, otherwise the content is read.
- df [-k] [path]: the filer's volume capacity in df -k format

Anything else fails with exit status 1. Checked with rclone: hashes md5 and
sha1 detected, md5sum/sha1sum match local files, `rclone about` works.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* sftp: describe exec commands without naming one client

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* sftp: exec hashes cover sparse files and stop with the connection

- md5sum/sha1sum read a file's whole logical content, with zeros for the
  holes and tail no chunk stores, through the same sparse-aware stream an
  in-place SFTP write uses; it ends with the SSH connection
- a trailing escaped space stays part of the file name
- df checks that the path exists

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* sftp: relative exec operands, hashes of holes stop, setstat size clears MD5

- a command's relative path is relative to the home, as over SFTP, so df
  and the hashes of a root-home user look up the right entry
- writes into the hash check the connection, so a large file that is all
  holes stops too
- a size change through SETSTAT drops the stored MD5, which md5sum reports

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* sftp: an exec ends when the client closes its channel

The command's context ended only with the SSH connection, so a client that
closed one exec channel and kept the connection left a hash running. The
channel's request stream closes with the channel, which now cancels it.
A second exec on the same channel is refused, as OpenSSH does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* sftp: a channel runs one exec or one SFTP session

With the exec running beside the request loop, a subsystem request after
it would have started SFTP on the same channel while the command was still
writing to it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* sftp: refuse a subsystem request without a name instead of panicking

The subsystem name was read as Payload[4:], so a request with fewer than
four payload bytes panicked the channel goroutine and stopped the server.
Decode the name like the exec command.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* sftp: test that a running exec keeps its channel from starting sftp

Also say in handleExec that its context ends with the channel.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* sftp: df drops -k only as a whole option

"df -kfoo" was read as "df foo"; now -kfoo is the path, which fails
unless such a file exists.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Denis Maier <denis@dAir.lab>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
2026-12-02 03:54:26 -08:00

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.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()
}