mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-06 02:57:37 +01:00
Stat, lstat and directory listings always showed uid 0 and gid 0, although the filer stores the uploader's Uid and Gid. pkg/sftp only sends the owner when the os.FileInfo implements its FileInfoUidGid interface (Uid() and Gid()). EnhancedFileInfo exposed the owner through an Owner() method and a custom Sys() struct instead, which pkg/sftp never reads. Implement Uid() and Gid() on EnhancedFileInfo and drop the unused Owner(), Sys() and FileStat. Add a test that serves a session over in-memory pipes and checks the owner returned by Stat and ReadDir. Co-authored-by: Denis Maier <denis@dAir.lab> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
448 lines
15 KiB
Go
448 lines
15 KiB
Go
package sftpd
|
|
|
|
import (
|
|
"context"
|
|
"crypto/rand"
|
|
"encoding/binary"
|
|
"encoding/hex"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"net"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"os"
|
|
"path"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/pkg/sftp"
|
|
"github.com/seaweedfs/seaweedfs/weed/pb"
|
|
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
|
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
|
"github.com/seaweedfs/seaweedfs/weed/security"
|
|
"github.com/seaweedfs/seaweedfs/weed/sftpd/user"
|
|
"google.golang.org/grpc"
|
|
"google.golang.org/grpc/codes"
|
|
"google.golang.org/grpc/credentials/insecure"
|
|
"google.golang.org/grpc/metadata"
|
|
"google.golang.org/grpc/status"
|
|
)
|
|
|
|
// TestPutFileEscapesQueryInjection ensures a filename containing "?" cannot be
|
|
// reinterpreted by the filer as a query string that injects cp.from/mv.from
|
|
// commands, which would let an SFTP user escape their home directory.
|
|
func TestPutFileEscapesQueryInjection(t *testing.T) {
|
|
var gotPath, gotRawQuery string
|
|
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
gotPath = r.URL.Path
|
|
gotRawQuery = r.URL.RawQuery
|
|
if _, err := w.Write([]byte(`{}`)); err != nil {
|
|
t.Errorf("write response: %v", err)
|
|
}
|
|
}))
|
|
defer ts.Close()
|
|
|
|
fs := &SftpServer{filerAddr: pb.ServerAddress(strings.TrimPrefix(ts.URL, "http://"))}
|
|
|
|
malicious := "/home/alice/steal?cp.from=/home/bob/secret.txt"
|
|
if err := fs.putFile(malicious, strings.NewReader("dummy"), nil, 0644, nil); err != nil {
|
|
t.Fatalf("putFile: %v", err)
|
|
}
|
|
|
|
if gotRawQuery != "mode=644" {
|
|
t.Errorf("filename leaked into query string: RawQuery=%q", gotRawQuery)
|
|
}
|
|
if gotPath != malicious {
|
|
t.Errorf("path not delivered literally: got %q, want %q", gotPath, malicious)
|
|
}
|
|
}
|
|
|
|
type fakeListFiler struct {
|
|
filer_pb.UnimplementedSeaweedFilerServer
|
|
names []string
|
|
failFrom int // ListEntries fails after sending this many entries, when > 0
|
|
authKey security.SigningKey
|
|
authResultChan chan bool
|
|
}
|
|
|
|
func (f *fakeListFiler) checkAuth(ctx context.Context) error {
|
|
if len(f.authKey) == 0 {
|
|
return nil
|
|
}
|
|
md, _ := metadata.FromIncomingContext(ctx)
|
|
values := md.Get("authorization")
|
|
valid := len(values) == 1 && strings.HasPrefix(values[0], security.BearerPrefix) &&
|
|
security.IsFilerAdminToken(f.authKey, security.EncodedJwt(strings.TrimPrefix(values[0], security.BearerPrefix)))
|
|
if f.authResultChan != nil {
|
|
f.authResultChan <- valid
|
|
}
|
|
if !valid {
|
|
return status.Error(codes.Unauthenticated, "missing or invalid filer authorization")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (f *fakeListFiler) ListEntries(req *filer_pb.ListEntriesRequest, stream grpc.ServerStreamingServer[filer_pb.ListEntriesResponse]) error {
|
|
if err := f.checkAuth(stream.Context()); err != nil {
|
|
return err
|
|
}
|
|
sent := 0
|
|
for _, name := range f.names {
|
|
if name <= req.StartFromFileName || sent >= int(req.Limit) {
|
|
continue
|
|
}
|
|
if f.failFrom > 0 && sent == f.failFrom {
|
|
return status.Error(codes.Unavailable, "filer went away")
|
|
}
|
|
if err := stream.Send(&filer_pb.ListEntriesResponse{Entry: &filer_pb.Entry{Name: name, Attributes: &filer_pb.FuseAttributes{}}}); err != nil {
|
|
return err
|
|
}
|
|
sent++
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (f *fakeListFiler) LookupDirectoryEntry(ctx context.Context, req *filer_pb.LookupDirectoryEntryRequest) (*filer_pb.LookupDirectoryEntryResponse, error) {
|
|
if err := f.checkAuth(ctx); err != nil {
|
|
return nil, err
|
|
}
|
|
return &filer_pb.LookupDirectoryEntryResponse{Entry: &filer_pb.Entry{Name: req.Name, Attributes: &filer_pb.FuseAttributes{}}}, nil
|
|
}
|
|
|
|
func sftpTestSigningKey(t *testing.T) security.SigningKey {
|
|
t.Helper()
|
|
bytes := make([]byte, 32)
|
|
if _, err := rand.Read(bytes); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
return security.SigningKey(hex.EncodeToString(bytes))
|
|
}
|
|
|
|
func newListTestServer(t *testing.T, filer *fakeListFiler) *SftpServer {
|
|
t.Helper()
|
|
lis, err := net.Listen("tcp", "127.0.0.1:0")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
srv := grpc.NewServer()
|
|
filer_pb.RegisterSeaweedFilerServer(srv, filer)
|
|
go srv.Serve(lis)
|
|
t.Cleanup(srv.Stop)
|
|
return &SftpServer{
|
|
filerAddr: pb.ServerAddress(fmt.Sprintf("127.0.0.1:1.%d", lis.Addr().(*net.TCPAddr).Port)),
|
|
grpcDialOption: grpc.WithTransportCredentials(insecure.NewCredentials()),
|
|
user: &user.User{
|
|
Username: "alice",
|
|
HomeDir: "/",
|
|
Uid: 1001,
|
|
Gid: 1001,
|
|
// every entry under /d is listable except f00000
|
|
Permissions: map[string][]string{"/d": {"list"}, "/d/f00000": {}},
|
|
},
|
|
}
|
|
}
|
|
|
|
func listNames(t *testing.T, fs *SftpServer) ([]string, error) {
|
|
t.Helper()
|
|
type result struct {
|
|
lister sftp.ListerAt
|
|
err error
|
|
}
|
|
done := make(chan result, 1)
|
|
go func() {
|
|
lister, err := fs.listAllPages("/d")
|
|
done <- result{lister, err}
|
|
}()
|
|
select {
|
|
case r := <-done:
|
|
if r.err != nil {
|
|
return nil, r.err
|
|
}
|
|
infos := make([]os.FileInfo, 10000)
|
|
n, _ := r.lister.ListAt(infos, 0)
|
|
var names []string
|
|
for _, fi := range infos[:n] {
|
|
names = append(names, fi.Name())
|
|
}
|
|
return names, nil
|
|
case <-time.After(10 * time.Second):
|
|
t.Fatal("listing did not return")
|
|
return nil, nil
|
|
}
|
|
}
|
|
|
|
func fileNames(n int) []string {
|
|
names := make([]string, n)
|
|
for i := range names {
|
|
names[i] = fmt.Sprintf("f%05d", i)
|
|
}
|
|
return names
|
|
}
|
|
|
|
func TestListAllPagesReturnsStreamError(t *testing.T) {
|
|
fs := newListTestServer(t, &fakeListFiler{names: fileNames(10), failFrom: 3})
|
|
_, err := listNames(t, fs)
|
|
if status.Code(err) != codes.Unavailable {
|
|
t.Fatalf("expected the stream error, got %v", err)
|
|
}
|
|
}
|
|
|
|
func TestListAllPagesContinuesPastHiddenEntries(t *testing.T) {
|
|
fs := newListTestServer(t, &fakeListFiler{names: fileNames(defaultListLimit + 500)})
|
|
names, err := listNames(t, fs)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if len(names) != defaultListLimit+499 {
|
|
t.Fatalf("expected %d entries, got %d", defaultListLimit+499, len(names))
|
|
}
|
|
if names[0] != "f00001" || names[len(names)-1] != fmt.Sprintf("f%05d", defaultListLimit+499) {
|
|
t.Fatalf("unexpected first/last entries %q, %q", names[0], names[len(names)-1])
|
|
}
|
|
}
|
|
|
|
func TestListAllPagesContinuesPastFullyHiddenPage(t *testing.T) {
|
|
const tail = 10
|
|
fs := newListTestServer(t, &fakeListFiler{names: fileNames(defaultListLimit + tail)})
|
|
// The whole first page is hidden from the user; only the tail is listable.
|
|
for i := 0; i < defaultListLimit; i++ {
|
|
fs.user.Permissions[fmt.Sprintf("/d/f%05d", i)] = []string{}
|
|
}
|
|
names, err := listNames(t, fs)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if len(names) != tail {
|
|
t.Fatalf("expected the %d entries after the hidden page, got %d", tail, len(names))
|
|
}
|
|
if names[0] != fmt.Sprintf("f%05d", defaultListLimit) {
|
|
t.Fatalf("unexpected first entry %q", names[0])
|
|
}
|
|
}
|
|
|
|
func TestWithFilerClientSendsAdminToken(t *testing.T) {
|
|
key := sftpTestSigningKey(t)
|
|
t.Setenv("WEED_JWT_FILER_SIGNING_GRPC_KEY", string(key))
|
|
t.Setenv("WEED_JWT_FILER_SIGNING_KEY", "")
|
|
|
|
filer := &fakeListFiler{authKey: key, authResultChan: make(chan bool, 1)}
|
|
fs := newListTestServer(t, filer)
|
|
err := fs.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
|
|
_, err := client.LookupDirectoryEntry(context.Background(), &filer_pb.LookupDirectoryEntryRequest{Directory: "/", Name: "entry"})
|
|
return err
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("WithFilerClient: %v", err)
|
|
}
|
|
select {
|
|
case valid := <-filer.authResultChan:
|
|
if !valid {
|
|
t.Fatal("filer rejected the per-call admin token")
|
|
}
|
|
case <-time.After(time.Second):
|
|
t.Fatal("filer did not receive the request")
|
|
}
|
|
}
|
|
|
|
// The filer lists a missing directory, or a file, as empty; sftp must report it as missing.
|
|
func TestListAllPagesMissingDirectory(t *testing.T) {
|
|
fs := newCopyTestServer(t, "", map[string]*filer_pb.Entry{
|
|
"/home/d": {Name: "d", IsDirectory: true, Attributes: &filer_pb.FuseAttributes{}},
|
|
"/home/d/a.txt": {Name: "a.txt", Attributes: &filer_pb.FuseAttributes{}},
|
|
"/home/empty": {Name: "empty", IsDirectory: true, Attributes: &filer_pb.FuseAttributes{}},
|
|
})
|
|
fs.user.Permissions = map[string][]string{"/home": {"list"}}
|
|
|
|
if _, err := fs.listAllPages("/home/missing"); err != os.ErrNotExist {
|
|
t.Fatalf("missing directory: got %v, want os.ErrNotExist", err)
|
|
}
|
|
if _, err := fs.listAllPages("/home/d/a.txt"); err != os.ErrNotExist {
|
|
t.Fatalf("file: got %v, want os.ErrNotExist", err)
|
|
}
|
|
lister, err := fs.listAllPages("/home/empty")
|
|
if err != nil {
|
|
t.Fatalf("empty directory: %v", err)
|
|
}
|
|
if n, _ := lister.ListAt(make([]os.FileInfo, 1), 0); n != 0 {
|
|
t.Fatalf("empty directory: got %d entries, want 0", n)
|
|
}
|
|
lister, err = fs.listAllPages("/home/d")
|
|
if err != nil {
|
|
t.Fatalf("directory: %v", err)
|
|
}
|
|
infos := make([]os.FileInfo, 2)
|
|
if n, _ := lister.ListAt(infos, 0); n != 1 || infos[0].Name() != "a.txt" {
|
|
t.Fatalf("directory: got %d entries, want a.txt", n)
|
|
}
|
|
}
|
|
|
|
func TestUploadFileMode(t *testing.T) {
|
|
fs, _ := newLockTestServer(t, map[string]*filer_pb.Entry{
|
|
"/buckets/plain": {Name: "plain", IsDirectory: true},
|
|
"/buckets/plain/private": {Name: "private", Attributes: &filer_pb.FuseAttributes{FileMode: 0600}},
|
|
"/buckets/plain/shared": {Name: "shared", Attributes: &filer_pb.FuseAttributes{FileMode: 0664}},
|
|
"/buckets/plain/unset": {Name: "unset", Attributes: &filer_pb.FuseAttributes{}},
|
|
})
|
|
var gotMode string
|
|
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
gotMode = r.URL.Query().Get("mode")
|
|
_, _ = w.Write([]byte(`{}`))
|
|
}))
|
|
t.Cleanup(ts.Close)
|
|
_, grpcPort, _ := net.SplitHostPort(fs.filerAddr.ToGrpcAddress())
|
|
fs.filerAddr = pb.ServerAddress(strings.TrimPrefix(ts.URL, "http://") + "." + grpcPort)
|
|
|
|
tests := []struct {
|
|
name string
|
|
req *sftp.Request
|
|
want string
|
|
}{
|
|
{"default", sftp.NewRequest("Put", "/plain/new"), "644"},
|
|
{"overwrite keeps private mode", sftp.NewRequest("Put", "/plain/private"), "600"},
|
|
{"overwrite keeps shared mode", sftp.NewRequest("Put", "/plain/shared"), "664"},
|
|
{"overwrite of a file without a mode", sftp.NewRequest("Put", "/plain/unset"), "644"},
|
|
}
|
|
for _, tt := range tests {
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
tt.req.Flags |= 0x1a // write, create, truncate
|
|
gotMode = ""
|
|
w, err := fs.newFileWriter(tt.req)
|
|
if err != nil {
|
|
t.Fatalf("newFileWriter: %v", err)
|
|
}
|
|
if _, err := w.WriteAt([]byte("data"), 0); err != nil {
|
|
t.Fatalf("write: %v", err)
|
|
}
|
|
if err := w.(io.Closer).Close(); err != nil {
|
|
t.Fatalf("close: %v", err)
|
|
}
|
|
if gotMode != tt.want {
|
|
t.Errorf("mode = %q, want %q", gotMode, tt.want)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
// An fsetstat on an upload's handle, as "put -p" sends before closing, finds
|
|
// no entry yet: it has to wait for the upload and apply then, even when the
|
|
// upload took the bucket's default retention.
|
|
func TestSetstatOnBufferingUpload(t *testing.T) {
|
|
fs, fake := newLockTestServer(t, map[string]*filer_pb.Entry{
|
|
"/buckets/plain": {Name: "plain", IsDirectory: true},
|
|
})
|
|
var gotMode, gotBody string
|
|
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
body, _ := io.ReadAll(r.Body)
|
|
gotMode, gotBody = r.URL.Query().Get("mode"), string(body)
|
|
fake.mu.Lock()
|
|
entry := lockedEntry(path.Base(r.URL.Path), map[string]string{s3_constants.ExtObjectLockModeKey: s3_constants.RetentionModeCompliance, s3_constants.ExtRetentionUntilDateKey: retainUntil(time.Hour)})
|
|
entry.Attributes = &filer_pb.FuseAttributes{FileMode: 0644, FileSize: uint64(len(body)), MtimeNs: 123}
|
|
fake.entries[r.URL.Path] = entry
|
|
fake.mu.Unlock()
|
|
_, _ = w.Write([]byte(`{}`))
|
|
}))
|
|
t.Cleanup(ts.Close)
|
|
_, grpcPort, _ := net.SplitHostPort(fs.filerAddr.ToGrpcAddress())
|
|
fs.filerAddr = pb.ServerAddress(strings.TrimPrefix(ts.URL, "http://") + "." + grpcPort)
|
|
|
|
open := sftp.NewRequest("Put", "/plain/new")
|
|
open.Flags = 0x1a // write, create, truncate
|
|
w, err := fs.newFileWriter(open)
|
|
if err != nil {
|
|
t.Fatalf("newFileWriter: %v", err)
|
|
}
|
|
if _, err := w.WriteAt([]byte("hello world"), 0); err != nil {
|
|
t.Fatalf("write: %v", err)
|
|
}
|
|
const mtime = 1700000000
|
|
setstat := sftp.NewRequest("Setstat", "/plain/new")
|
|
setstat.Flags = 0x1 | 0x4 | 0x8 // size, permissions, times
|
|
setstat.Attrs = binary.BigEndian.AppendUint64(nil, 5)
|
|
setstat.Attrs = binary.BigEndian.AppendUint32(setstat.Attrs, 0100600)
|
|
setstat.Attrs = binary.BigEndian.AppendUint32(setstat.Attrs, mtime)
|
|
setstat.Attrs = binary.BigEndian.AppendUint32(setstat.Attrs, mtime)
|
|
if err := fs.dispatchCmd(setstat); err != nil {
|
|
t.Fatalf("setstat before close: %v", err)
|
|
}
|
|
if err := w.(io.Closer).Close(); err != nil {
|
|
t.Fatalf("close: %v", err)
|
|
}
|
|
if gotMode != "600" || gotBody != "hello" {
|
|
t.Errorf("uploaded mode %q body %q, want 600 and the body cut to 5 bytes", gotMode, gotBody)
|
|
}
|
|
got := fake.lastUpdate.GetEntry().GetAttributes()
|
|
if got.GetMtime() != mtime || got.GetMtimeNs() != 0 || os.FileMode(got.GetFileMode()).Perm() != 0600 {
|
|
t.Errorf("stored mtime %d.%09d mode %o, want %d.000000000 and 600", got.GetMtime(), got.GetMtimeNs(), got.GetFileMode(), mtime)
|
|
}
|
|
if fs.openUpload("/buckets/plain/new") != nil {
|
|
t.Error("closed upload is still tracked")
|
|
}
|
|
|
|
// The client was told the setstat worked, so losing it must fail the close.
|
|
fake.mu.Lock()
|
|
fake.updateErr = errors.New("update refused")
|
|
fake.mu.Unlock()
|
|
open.Filepath, setstat.Filepath = "/plain/other", "/plain/other"
|
|
w, err = fs.newFileWriter(open)
|
|
if err != nil {
|
|
t.Fatalf("newFileWriter: %v", err)
|
|
}
|
|
if err := fs.dispatchCmd(setstat); err != nil {
|
|
t.Fatalf("setstat before close: %v", err)
|
|
}
|
|
if err := w.(io.Closer).Close(); err == nil {
|
|
t.Error("close succeeded although the queued attributes were not stored")
|
|
}
|
|
}
|
|
|
|
// A setstat names only the path, so it can't pick between two uploads open
|
|
// on the same one and goes to the stored entry instead.
|
|
func TestSetstatWithTwoUploadsOnOnePath(t *testing.T) {
|
|
fs, _ := newLockTestServer(t, map[string]*filer_pb.Entry{
|
|
"/buckets/plain": {Name: "plain", IsDirectory: true},
|
|
})
|
|
open := func() io.WriteCloser {
|
|
req := sftp.NewRequest("Put", "/plain/new")
|
|
req.Flags = 0x1a // write, create, truncate
|
|
w, err := fs.newFileWriter(req)
|
|
if err != nil {
|
|
t.Fatalf("newFileWriter: %v", err)
|
|
}
|
|
return w.(io.WriteCloser)
|
|
}
|
|
first, second := open(), open()
|
|
if fs.openUpload("/buckets/plain/new") != nil {
|
|
t.Fatal("setstat routed to one of two open uploads")
|
|
}
|
|
_ = second.Close()
|
|
if got := fs.openUpload("/buckets/plain/new"); got != first {
|
|
t.Fatalf("open upload = %p, want the remaining one %p", got, first)
|
|
}
|
|
_ = first.Close()
|
|
}
|
|
|
|
// Stat and listings must report the uid/gid stored in the filer.
|
|
func TestStatAndListReportOwner(t *testing.T) {
|
|
fs := newCopyTestServer(t, "", map[string]*filer_pb.Entry{
|
|
"//home": {Name: "home", IsDirectory: true, Attributes: &filer_pb.FuseAttributes{FileMode: 0o755}},
|
|
"/home/f": {Name: "f", Attributes: &filer_pb.FuseAttributes{FileMode: 0o644, Uid: 1234, Gid: 5678}},
|
|
})
|
|
fs.user.Permissions = map[string][]string{"/": {"read", "list"}}
|
|
for _, req := range []*sftp.Request{sftp.NewRequest("Stat", "/home/f"), sftp.NewRequest("List", "/home")} {
|
|
lister, err := fs.listDir(req)
|
|
if err != nil {
|
|
t.Fatalf("%s: %v", req.Method, err)
|
|
}
|
|
infos := make([]os.FileInfo, 1)
|
|
if n, _ := lister.ListAt(infos, 0); n != 1 {
|
|
t.Fatalf("%s returned %d entries, want 1", req.Method, n)
|
|
}
|
|
owner, ok := infos[0].(sftp.FileInfoUidGid)
|
|
if !ok || owner.Uid() != 1234 || owner.Gid() != 5678 {
|
|
t.Errorf("%s: owner not reported as 1234/5678 (%T)", req.Method, infos[0])
|
|
}
|
|
}
|
|
}
|