mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-04 18:17:16 +01:00
* 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>
211 lines
6.2 KiB
Go
211 lines
6.2 KiB
Go
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 <text> prints text (clients use it to detect the shell type)
|
|
// md5sum [path] "<hex> <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 "<hex> <name>" 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
|
|
}
|