Repository navigation
fix(ssh): run SFTP as requested user #1756
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
f78792e
fix(ssh): run SFTP as requested user
skevetter bcfa511
test(ssh): avoid shadowing copy in SFTP regression
skevetter 3b9dd76
test(ssh): run SFTP regressions without lint exceptions
skevetter 19aa6e9
fix(ssh): preserve current-user groups in SFTP
skevetter File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,36 @@ | ||
| package agentcontainer | ||
|
|
||
| import ( | ||
| "fmt" | ||
| "io" | ||
| "os" | ||
|
|
||
| "github.com/devsy-org/devsy/pkg/ssh/server" | ||
| "github.com/spf13/cobra" | ||
| ) | ||
|
|
||
| func NewSFTPServerCmd() *cobra.Command { | ||
| var home string | ||
| cmd := &cobra.Command{ | ||
| Use: "sftp-server", | ||
| Hidden: true, | ||
| Args: cobra.NoArgs, | ||
| RunE: func(_ *cobra.Command, _ []string) error { | ||
| if home == "" { | ||
| return fmt.Errorf("home directory is required") | ||
| } | ||
| return server.ServeSFTP(sftpStdio{Reader: os.Stdin, Writer: os.Stdout}, home) | ||
| }, | ||
| } | ||
| cmd.Flags().StringVar(&home, "home", "", "Home directory for SFTP paths") | ||
| return cmd | ||
| } | ||
|
|
||
| type sftpStdio struct { | ||
| io.Reader | ||
| io.Writer | ||
| } | ||
|
|
||
| func (sftpStdio) Close() error { | ||
| return nil | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,48 +1,181 @@ | ||
| package server | ||
|
|
||
| import ( | ||
| "context" | ||
| "errors" | ||
| "fmt" | ||
| "io" | ||
| "os" | ||
| "os/exec" | ||
| "os/user" | ||
| "runtime" | ||
| "strconv" | ||
|
|
||
| "github.com/devsy-org/devsy/pkg/command" | ||
| "github.com/devsy-org/devsy/pkg/log" | ||
| "github.com/devsy-org/ssh" | ||
| "github.com/pkg/sftp" | ||
| ) | ||
|
|
||
| func sftpHandler(sess ssh.Session, currentUser string) { | ||
| writer := log.Writer(log.LevelDebug) | ||
| defer func() { _ = writer.Close() }() | ||
| var newSFTPCommand = func(_ context.Context, home string) (*exec.Cmd, error) { | ||
| executable, err := os.Executable() | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
| return &exec.Cmd{ | ||
| Path: executable, | ||
| Args: []string{executable, "internal", "agent", "container", "sftp-server", "--home", home}, | ||
| }, nil | ||
| } | ||
|
|
||
| user := sess.User() | ||
| if user == currentUser { | ||
| user = "" | ||
| type sftpExecIdentity struct { | ||
| home string | ||
| credential string | ||
| account *user.User | ||
| hasGroupSpec bool | ||
| } | ||
|
|
||
| func sftpHandler(sess ssh.Session) { | ||
| err := runSFTP(sess) | ||
| if err != nil { | ||
| log.Debugf("sftp session failed: %v (exit %d)", err, exitCode(err)) | ||
| } | ||
| if err := sess.Exit(exitCode(err)); err != nil { | ||
| log.Debugf("sftp session exit failed: %T", err) | ||
| } | ||
| } | ||
|
|
||
| workingDir, _ := command.GetHome(user) | ||
| serverOptions := []sftp.ServerOption{ | ||
| sftp.WithDebug(writer), | ||
| sftp.WithServerWorkingDirectory(workingDir), | ||
| func runSFTP(sess ssh.Session) error { | ||
| identity, err := resolveSFTPIdentity(sess.User()) | ||
| if err != nil { | ||
| return err | ||
| } | ||
| server, err := sftp.NewServer( | ||
| sess, | ||
| serverOptions..., | ||
| ) | ||
| cmd, err := newSFTPCommand(sess.Context(), identity.home) | ||
| if err != nil { | ||
| log.Debugf("sftp server init error: %s\n", err) | ||
| return | ||
| return err | ||
| } | ||
| defer func() { _ = server.Close() }() | ||
| if cmd == nil { | ||
| return errors.New("missing SFTP command") | ||
| } | ||
| if err := prepareSFTPCommand(cmd, identity); err != nil { | ||
| return err | ||
| } | ||
| cmd.Stdout = sess | ||
| cmd.Stderr = sess.Stderr() | ||
| stdin, err := cmd.StdinPipe() | ||
| if err != nil { | ||
| return err | ||
| } | ||
| if err := cmd.Start(); err != nil { | ||
| _ = stdin.Close() | ||
| return err | ||
| } | ||
| stopCancellation := context.AfterFunc(sess.Context(), func() { _ = cmd.Process.Kill() }) | ||
| defer stopCancellation() | ||
| go func() { | ||
| _, _ = io.Copy(stdin, sess) | ||
| _ = stdin.Close() | ||
| }() | ||
| return cmd.Wait() | ||
| } | ||
|
|
||
| // serve | ||
| err = server.Serve() | ||
| if errors.Is(err, io.EOF) { | ||
| _ = sess.Exit(0) | ||
| return | ||
| func resolveSFTPIdentity(spec string) (sftpExecIdentity, error) { | ||
| if spec == "" { | ||
| return sftpExecIdentity{}, errors.New("missing SFTP user") | ||
| } | ||
| requested, handled, err := parseRequestedExecIdentity(spec) | ||
| if err != nil { | ||
| return sftpExecIdentity{}, err | ||
| } | ||
| if !handled { | ||
| requested.user = spec | ||
| } | ||
| account, err := lookupSFTPAccount(requested) | ||
| if err != nil { | ||
| return sftpExecIdentity{}, err | ||
| } | ||
| identity := sftpExecIdentity{ | ||
| home: "/", | ||
| credential: spec, | ||
| account: account, | ||
| hasGroupSpec: requested.hasGroupSpec, | ||
| } | ||
| if account != nil { | ||
| if account.HomeDir != "" { | ||
| identity.home = account.HomeDir | ||
| } | ||
| if !requested.hasGroupSpec { | ||
| identity.credential = account.Uid | ||
| } | ||
| } | ||
| return identity, nil | ||
| } | ||
|
|
||
| func lookupSFTPAccount(requested requestedExecIdentity) (*user.User, error) { | ||
| if !requested.userIsID { | ||
| return user.Lookup(requested.user) | ||
| } | ||
| uid, err := parseExecID(requested.user) | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
| account, err := user.LookupId(strconv.FormatUint(uint64(uid), 10)) | ||
| var unknown user.UnknownUserIdError | ||
| if err != nil && !errors.As(err, &unknown) { | ||
| return nil, err | ||
| } | ||
| return account, nil | ||
| } | ||
|
|
||
| func prepareSFTPCommand(cmd *exec.Cmd, identity sftpExecIdentity) error { | ||
| handled, err := applySFTPCredentials(cmd, identity) | ||
| if err != nil { | ||
| return err | ||
| } | ||
| if !handled { | ||
| return fmt.Errorf("SFTP identity %q cannot be applied", identity.credential) | ||
| } | ||
| if runtime.GOOS != "windows" { | ||
| cmd.Dir = "/" | ||
| } | ||
| return nil | ||
| } | ||
|
|
||
| func applySFTPCredentials(cmd *exec.Cmd, identity sftpExecIdentity) (bool, error) { | ||
| if identity.account != nil && !identity.hasGroupSpec { | ||
| current, err := user.Current() | ||
| if err != nil { | ||
| return true, err | ||
| } | ||
| if identity.account.Uid == current.Uid && identity.account.Username == current.Username { | ||
| prepareCurrentSFTPUser(cmd, identity) | ||
| return true, nil | ||
| } | ||
| if runtime.GOOS == "windows" { | ||
| return true, errors.New("SFTP user switching is not supported") | ||
| } | ||
| return prepareExecIdentityForAccount(cmd, identity.credential, identity.account) | ||
| } | ||
| return prepareExecIdentity(cmd, identity.credential) | ||
| } | ||
|
|
||
| func prepareCurrentSFTPUser(cmd *exec.Cmd, identity sftpExecIdentity) { | ||
| cmd.Env = mergeSessionEnvironment(cmd.Environ(), []string{ | ||
| "HOME=" + identity.home, | ||
| "USER=" + identity.account.Username, | ||
| "LOGNAME=" + identity.account.Username, | ||
| }, nil) | ||
| } | ||
|
|
||
| func ServeSFTP(input io.ReadWriteCloser, home string) error { | ||
| server, err := sftp.NewServer(input, sftp.WithServerWorkingDirectory(home)) | ||
| if err != nil { | ||
| log.Debugf("sftp server completed with error: %v", err) | ||
| return err | ||
| } | ||
| defer func() { _ = server.Close() }() | ||
|
|
||
| err = server.Serve() | ||
| if errors.Is(err, io.EOF) { | ||
| return nil | ||
| } | ||
| _ = sess.Exit(1) | ||
| return err | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.