mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-04 18:17:16 +01:00
* sftp: add -stdio to run as an OpenSSH Subsystem
weed sftp -stdio serves one SFTP session on stdin/stdout, so sshd can run it
as its sftp subsystem and handle authentication itself (PAM, SSSD, 2FA,
AllowUsers, Match blocks):
Subsystem sftp /usr/local/bin/weed sftp -stdio -filer=filer:8888
The session belongs to the OS user sshd started it as. With -userStoreFile
that user must be in the store, and its HomeDir and Permissions apply as
over SSH; without one, the session reaches the whole filer, which the
process's filer access allows anyway. The SSH listener options are ignored
and nothing but SFTP is written to stdout.
Checked with OpenSSH's sftp -D: put/ls/rm on the whole filer without a
store; with a store the user is jailed to its home, and a user missing from
the store is refused.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* sftp -stdio: explain an unreadable user store, test the stream
The session runs as the logged-in OS user, who must read the store; a
store without passwords or keys can be shared with them. Tell that user
why the store is refused instead of a bare permission error.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* sftp: stdio sessions reuse handleSFTP
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* sftp: a refused -stdio session exits 1 without printing usage
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* sftp -stdio: give up after 30s when the filer is unreachable
The listener keeps waiting for the filer; a stdio session is one login and
should not hold a process for the whole outage.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* sftp -stdio: bound the filer configuration request by the wait
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* sftpd: skip the unreadable-store test on Windows
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* sftp: detect the sshd Subsystem launch instead of a -stdio flag
weed sftp serves one session on stdin/stdout when sshd starts it: SSH_CONNECTION
is set and stdin and stdout are both pipes or sockets. A listener started by
systemd, a container, nohup or a shell has a terminal, /dev/null or a file
there, so it keeps listening.
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>
311 lines
13 KiB
Go
311 lines
13 KiB
Go
package command
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"os"
|
|
"os/user"
|
|
"runtime"
|
|
"time"
|
|
|
|
"github.com/seaweedfs/seaweedfs/weed/glog"
|
|
"github.com/seaweedfs/seaweedfs/weed/pb"
|
|
filer_pb "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
|
"github.com/seaweedfs/seaweedfs/weed/security"
|
|
"github.com/seaweedfs/seaweedfs/weed/sftpd"
|
|
stats_collect "github.com/seaweedfs/seaweedfs/weed/stats"
|
|
"github.com/seaweedfs/seaweedfs/weed/util"
|
|
"github.com/seaweedfs/seaweedfs/weed/util/grace"
|
|
"github.com/seaweedfs/seaweedfs/weed/util/version"
|
|
)
|
|
|
|
var (
|
|
sftpOptionsStandalone SftpOptions
|
|
)
|
|
|
|
// SftpOptions holds configuration options for the SFTP server.
|
|
type SftpOptions struct {
|
|
filer *string
|
|
bindIp *string
|
|
listenOnLocalhost *bool
|
|
port *int
|
|
idleTimeout *int
|
|
sshPrivateKey *string
|
|
hostKeysFolder *string
|
|
authMethods *string
|
|
maxAuthTries *int
|
|
bannerMessage *string
|
|
loginGraceTime *time.Duration
|
|
clientAliveInterval *time.Duration
|
|
clientAliveCountMax *int
|
|
userStoreFile *string
|
|
trustedUserCAKeysFile *string
|
|
dataCenter *string
|
|
metricsHttpPort *int
|
|
metricsHttpIp *string
|
|
localSocket *string
|
|
stdio bool
|
|
}
|
|
|
|
// cmdSftp defines the SFTP command similar to the S3 command.
|
|
var cmdSftp = &Command{
|
|
UsageLine: "sftp [-port=2022] [-filer=<ip:port>] [-sshPrivateKey=</path/to/private_key>]",
|
|
Short: "start an SFTP server that is backed by a SeaweedFS filer",
|
|
Long: `Start an SFTP server that leverages the SeaweedFS filer service to handle file operations.
|
|
|
|
Instead of reading from or writing to a local filesystem, all file operations
|
|
are routed through the filer (filer_pb) gRPC API. This allows you to centralize
|
|
your file management in SeaweedFS.
|
|
|
|
When OpenSSH sshd runs it as the sftp Subsystem, it serves that one session on
|
|
stdin/stdout instead of listening, and the SSH options are ignored:
|
|
|
|
Subsystem sftp /usr/local/bin/weed sftp -filer=filer:8888
|
|
|
|
sshd authenticates, and the session belongs to the logged-in OS user. With
|
|
-userStoreFile that user must be in the store, which the user must be able to
|
|
read (keep passwords and keys out of it), and its home and permissions apply;
|
|
without a store the session can reach the whole filer.
|
|
`,
|
|
}
|
|
|
|
func init() {
|
|
// Register the command to avoid cyclic dependencies.
|
|
cmdSftp.Run = runSftp
|
|
|
|
sftpOptionsStandalone.filer = cmdSftp.Flag.String("filer", "localhost:8888", "filer server address (ip:port)")
|
|
sftpOptionsStandalone.bindIp = cmdSftp.Flag.String("ip.bind", "", "ip address to bind to. If empty, default to 0.0.0.0.")
|
|
sftpOptionsStandalone.port = cmdSftp.Flag.Int("port", 2022, "SFTP server listen port")
|
|
sftpOptionsStandalone.idleTimeout = cmdSftp.Flag.Int("idleTimeout", 10, "connection idle seconds")
|
|
sftpOptionsStandalone.sshPrivateKey = cmdSftp.Flag.String("sshPrivateKey", "", "path to the SSH private key file for host authentication")
|
|
sftpOptionsStandalone.hostKeysFolder = cmdSftp.Flag.String("hostKeysFolder", "", "path to folder containing SSH private key files for host authentication")
|
|
sftpOptionsStandalone.authMethods = cmdSftp.Flag.String("authMethods", "password,publickey", "comma-separated list of allowed auth methods: password, publickey, certificate")
|
|
sftpOptionsStandalone.maxAuthTries = cmdSftp.Flag.Int("maxAuthTries", 6, "maximum number of authentication attempts per connection")
|
|
sftpOptionsStandalone.bannerMessage = cmdSftp.Flag.String("bannerMessage", "SeaweedFS SFTP Server - Unauthorized access is prohibited", "message displayed before authentication")
|
|
sftpOptionsStandalone.loginGraceTime = cmdSftp.Flag.Duration("loginGraceTime", 2*time.Minute, "timeout for authentication")
|
|
sftpOptionsStandalone.clientAliveInterval = cmdSftp.Flag.Duration("clientAliveInterval", 5*time.Second, "interval for sending keep-alive messages")
|
|
sftpOptionsStandalone.clientAliveCountMax = cmdSftp.Flag.Int("clientAliveCountMax", 3, "maximum number of missed keep-alive messages before disconnecting")
|
|
sftpOptionsStandalone.userStoreFile = cmdSftp.Flag.String("userStoreFile", "", "path to JSON file containing user credentials and permissions")
|
|
sftpOptionsStandalone.trustedUserCAKeysFile = cmdSftp.Flag.String("trustedUserCAKeysFile", "", "path to a file with trusted user CA public keys (OpenSSH authorized_keys format); required when 'certificate' is in -authMethods. Analogous to OpenSSH TrustedUserCAKeys and MinIO --sftp=trusted-user-ca-key")
|
|
sftpOptionsStandalone.dataCenter = cmdSftp.Flag.String("dataCenter", "", "prefer to read and write to volumes in this data center")
|
|
sftpOptionsStandalone.metricsHttpPort = cmdSftp.Flag.Int("metricsPort", 0, "Prometheus metrics listen port")
|
|
sftpOptionsStandalone.metricsHttpIp = cmdSftp.Flag.String("metricsIp", "", "metrics listen ip. If empty, default to same as -ip.bind option.")
|
|
sftpOptionsStandalone.localSocket = cmdSftp.Flag.String("localSocket", "", "default to /tmp/seaweedfs-sftp-<port>.sock")
|
|
}
|
|
|
|
// stdioFilerWait bounds how long an sshd subsystem session waits for the filer.
|
|
const stdioFilerWait = 30 * time.Second
|
|
|
|
// runSftp is the command entry point.
|
|
func runSftp(cmd *Command, args []string) bool {
|
|
sftpOptionsStandalone.resolvePaths()
|
|
// Load security configuration as done in other SeaweedFS services.
|
|
util.LoadSecurityConfiguration()
|
|
|
|
// Configure metrics
|
|
switch {
|
|
case *sftpOptionsStandalone.metricsHttpIp != "":
|
|
// nothing to do, use sftpOptionsStandalone.metricsHttpIp
|
|
case *sftpOptionsStandalone.bindIp != "":
|
|
*sftpOptionsStandalone.metricsHttpIp = *sftpOptionsStandalone.bindIp
|
|
}
|
|
sftpOptionsStandalone.stdio = launchedAsSshSubsystem()
|
|
if !sftpOptionsStandalone.stdio {
|
|
go stats_collect.StartMetricsServer(*sftpOptionsStandalone.metricsHttpIp, *sftpOptionsStandalone.metricsHttpPort)
|
|
}
|
|
|
|
return sftpOptionsStandalone.startSftpServer()
|
|
}
|
|
|
|
// resolvePaths expands "~" in every user-supplied path flag.
|
|
// Idempotent — safe to call from any entry point.
|
|
func (sftpOpt *SftpOptions) resolvePaths() {
|
|
*sftpOpt.sshPrivateKey = util.ResolvePath(*sftpOpt.sshPrivateKey)
|
|
*sftpOpt.hostKeysFolder = util.ResolvePath(*sftpOpt.hostKeysFolder)
|
|
*sftpOpt.userStoreFile = util.ResolvePath(*sftpOpt.userStoreFile)
|
|
*sftpOpt.trustedUserCAKeysFile = util.ResolvePath(*sftpOpt.trustedUserCAKeysFile)
|
|
}
|
|
|
|
func (sftpOpt *SftpOptions) startSftpServer() bool {
|
|
// The loopback companion listener is only kept while -ip.bind is unset.
|
|
// An explicit -ip.bind pins the port to exactly that address.
|
|
listenOnLocalhost := *sftpOpt.bindIp == ""
|
|
if sftpOpt.listenOnLocalhost != nil {
|
|
listenOnLocalhost = *sftpOpt.listenOnLocalhost
|
|
}
|
|
idleTimeout := idleTimeoutSeconds(sftpOpt.idleTimeout)
|
|
if *sftpOpt.bindIp == "" {
|
|
*sftpOpt.bindIp = "0.0.0.0"
|
|
}
|
|
util.SetOutboundLocalIP(*sftpOpt.bindIp)
|
|
filerAddress := pb.ServerAddress(*sftpOpt.filer)
|
|
grpcDialOption := security.LoadClientTLS(util.GetViper(), "grpc.client")
|
|
|
|
// Load JWT configuration for filer signing
|
|
v := util.GetViper()
|
|
filerSigningKey := v.GetString("jwt.filer_signing.key")
|
|
v.SetDefault("jwt.filer_signing.expires_after_seconds", 600)
|
|
filerSigningExpiresAfter := v.GetInt("jwt.filer_signing.expires_after_seconds")
|
|
|
|
// metrics read from the filer
|
|
var metricsAddress string
|
|
var metricsIntervalSec int
|
|
var bucketsDir string
|
|
var filerGroup string
|
|
var digest string
|
|
|
|
// Connect to the filer service and try to retrieve basic configuration.
|
|
// The listener waits for the filer; a subsystem session is one login, so it
|
|
// gives up instead of holding the process for the whole outage.
|
|
stdio := sftpOpt.stdio
|
|
discoveryCtx := context.Background()
|
|
if stdio {
|
|
var cancel context.CancelFunc
|
|
discoveryCtx, cancel = context.WithTimeout(discoveryCtx, stdioFilerWait)
|
|
defer cancel()
|
|
}
|
|
for {
|
|
err := pb.WithGrpcFilerClient(false, 0, filerAddress, grpcDialOption, security.FilerAdminToken, func(client filer_pb.SeaweedFilerClient) error {
|
|
resp, err := client.GetFilerConfiguration(discoveryCtx, &filer_pb.GetFilerConfigurationRequest{})
|
|
if err != nil {
|
|
return fmt.Errorf("get filer %s configuration: %v", filerAddress, err)
|
|
}
|
|
metricsAddress, metricsIntervalSec = resp.MetricsAddress, int(resp.MetricsIntervalSec)
|
|
bucketsDir = resp.DirBuckets
|
|
filerGroup = resp.FilerGroup
|
|
digest = resp.Digest
|
|
glog.V(0).Infof("SFTP read filer configuration, using filer at: %s", filerAddress)
|
|
return nil
|
|
})
|
|
if err != nil {
|
|
if discoveryCtx.Err() != nil {
|
|
glog.Errorf("sftp subsystem: filer %s unreachable: %v", filerAddress.ToGrpcAddress(), err)
|
|
SetCommandExitStatus(1)
|
|
return true
|
|
}
|
|
glog.V(0).Infof("Waiting to connect to filer %s grpc address %s...", *sftpOpt.filer, filerAddress.ToGrpcAddress())
|
|
time.Sleep(time.Second)
|
|
} else {
|
|
glog.V(0).Infof("Connected to filer %s grpc address %s", *sftpOpt.filer, filerAddress.ToGrpcAddress())
|
|
break
|
|
}
|
|
}
|
|
adoptFilerDigest(*sftpOpt.filer, digest)
|
|
|
|
if stdio {
|
|
if err := sftpOpt.serveStdio(&sftpd.SFTPServiceOptions{
|
|
GrpcDialOption: grpcDialOption,
|
|
DataCenter: *sftpOpt.dataCenter,
|
|
FilerGroup: filerGroup,
|
|
Filer: filerAddress,
|
|
FilerSigningKey: []byte(filerSigningKey),
|
|
FilerSigningExpiresAfter: filerSigningExpiresAfter,
|
|
BucketsDir: bucketsDir,
|
|
}); err != nil {
|
|
glog.Errorf("sftp subsystem: %v", err)
|
|
SetCommandExitStatus(1)
|
|
}
|
|
return true
|
|
}
|
|
|
|
go stats_collect.LoopPushingMetric("sftp", stats_collect.SourceName(uint32(*sftpOpt.port)), metricsAddress, metricsIntervalSec)
|
|
|
|
// Parse auth methods
|
|
var authMethods []string
|
|
if *sftpOpt.authMethods != "" {
|
|
authMethods = util.StringSplit(*sftpOpt.authMethods, ",")
|
|
}
|
|
|
|
// Create a new SFTP service instance with all options
|
|
service := sftpd.NewSFTPService(&sftpd.SFTPServiceOptions{
|
|
GrpcDialOption: grpcDialOption,
|
|
DataCenter: *sftpOpt.dataCenter,
|
|
FilerGroup: filerGroup,
|
|
Filer: filerAddress,
|
|
SshPrivateKey: *sftpOpt.sshPrivateKey,
|
|
HostKeysFolder: *sftpOpt.hostKeysFolder,
|
|
AuthMethods: authMethods,
|
|
MaxAuthTries: *sftpOpt.maxAuthTries,
|
|
BannerMessage: *sftpOpt.bannerMessage,
|
|
LoginGraceTime: *sftpOpt.loginGraceTime,
|
|
ClientAliveInterval: *sftpOpt.clientAliveInterval,
|
|
ClientAliveCountMax: *sftpOpt.clientAliveCountMax,
|
|
UserStoreFile: *sftpOpt.userStoreFile,
|
|
TrustedUserCAKeysFile: *sftpOpt.trustedUserCAKeysFile,
|
|
FilerSigningKey: []byte(filerSigningKey),
|
|
FilerSigningExpiresAfter: filerSigningExpiresAfter,
|
|
BucketsDir: bucketsDir,
|
|
})
|
|
|
|
// Register reload hook for HUP signal
|
|
grace.OnReload(service.Reload)
|
|
|
|
// Set up Unix socket if on non-Windows platforms
|
|
if runtime.GOOS != "windows" {
|
|
localSocket := *sftpOpt.localSocket
|
|
explicit := localSocket != ""
|
|
if !explicit {
|
|
localSocket = fmt.Sprintf("/tmp/seaweedfs-sftp-%d.sock", *sftpOpt.port)
|
|
}
|
|
if sftpSocketListener := pb.ListenOnLocalSocket(localSocket); sftpSocketListener != nil {
|
|
sftpSocketListener = &util.Listener{Listener: sftpSocketListener, Timeout: idleTimeout}
|
|
go func() {
|
|
// start on local unix socket
|
|
if err := service.Serve(sftpSocketListener); err != nil {
|
|
glog.Fatalf("Failed to serve SFTP on socket %s: %v", localSocket, err)
|
|
}
|
|
}()
|
|
}
|
|
}
|
|
|
|
// Start the SFTP service on TCP
|
|
listenAddress := fmt.Sprintf("%s:%d", *sftpOpt.bindIp, *sftpOpt.port)
|
|
sftpListener, sftpLocalListener, err := util.NewIpAndLocalListeners(*sftpOpt.bindIp, *sftpOpt.port, idleTimeout, listenOnLocalhost)
|
|
if err != nil {
|
|
glog.Fatalf("SFTP server listener on %s error: %v", listenAddress, err)
|
|
}
|
|
|
|
glog.V(0).Infof("Start Seaweed SFTP Server %s at %s", version.Version(), listenAddress)
|
|
|
|
if sftpLocalListener != nil {
|
|
go func() {
|
|
if err := service.Serve(sftpLocalListener); err != nil {
|
|
glog.Fatalf("SFTP Server failed to serve on local listener: %v", err)
|
|
}
|
|
}()
|
|
}
|
|
|
|
if err := service.Serve(sftpListener); err != nil {
|
|
glog.Fatalf("SFTP Server failed to serve: %v", err)
|
|
}
|
|
|
|
return true
|
|
}
|
|
|
|
// serveStdio serves one SFTP session on stdin/stdout for the OS user running
|
|
// the command, which sshd has already authenticated
|
|
func (sftpOpt *SftpOptions) serveStdio(options *sftpd.SFTPServiceOptions) error {
|
|
osUser, err := user.Current()
|
|
if err != nil {
|
|
return fmt.Errorf("current user: %w", err)
|
|
}
|
|
u, err := sftpd.StdioUser(*sftpOpt.userStoreFile, osUser.Username, uint32(os.Getuid()), uint32(os.Getgid()))
|
|
if err != nil {
|
|
return err
|
|
}
|
|
glog.V(0).Infof("SFTP session on stdio for %s", u.Username)
|
|
return sftpd.ServeStdio(options, u, sftpd.Stdio{})
|
|
}
|
|
|
|
// launchedAsSshSubsystem reports whether sshd started this process as its sftp
|
|
// Subsystem: sshd sets SSH_CONNECTION and wires stdin and stdout to the channel,
|
|
// while a listener has a terminal, /dev/null or a file there.
|
|
func launchedAsSshSubsystem() bool {
|
|
return os.Getenv("SSH_CONNECTION") != "" && isPipeOrSocket(os.Stdin) && isPipeOrSocket(os.Stdout)
|
|
}
|
|
|
|
func isPipeOrSocket(f *os.File) bool {
|
|
fi, err := f.Stat()
|
|
return err == nil && fi.Mode()&(os.ModeNamedPipe|os.ModeSocket) != 0
|
|
}
|