// Package sshtest provides an in-process SSH/SFTP server and a fault-injecting // TCP proxy for tests. It is a regular (non _test) package so that tests in // different packages can share it. // // The server serves the real OS filesystem over the "sftp" subsystem and runs // "exec" requests through `sh -c`, reporting exit-status and stderr. Every // goroutine it starts is stopped by t.Cleanup. package sshtest import ( "context" "encoding/binary" "errors" "fmt" "net" "os/exec" "sync" "testing" "time" "github.com/pkg/sftp" "golang.org/x/crypto/ssh" ) // DefaultPassword is accepted when Options.Password is empty and no // AuthorizedKeys are configured. const DefaultPassword = "pw" // Options configures Start. type Options struct { // Password accepted for any user. Empty means DefaultPassword (unless // AuthorizedKeys is set, in which case password auth is disabled). Password string // AuthorizedKeys enables public-key auth for these keys. AuthorizedKeys []ssh.PublicKey // HostKeys the server offers. Empty means a fresh ed25519 + ECDSA pair. HostKeys []ssh.Signer // NoExec rejects "exec" requests, like `ForceCommand internal-sftp`. NoExec bool // Chroot sets the SFTP working directory and the cwd of exec commands. // Relative paths resolve against it. It is NOT a security boundary: // absolute paths still reach the whole filesystem. Chroot string } // Server is a running in-process SSH server. type Server struct { // Addr is host:port to dial. Addr string // HostKeys the server offers. HostKeys []ssh.Signer // Root is the directory relative paths resolve against ("/" by default). Root string // Password accepted by the server ("" when password auth is disabled). Password string opts Options cfg *ssh.ServerConfig ln net.Listener ctx context.Context cancel context.CancelFunc wg sync.WaitGroup mu sync.Mutex conns map[net.Conn]struct{} closed bool } // Start launches a server on 127.0.0.1 and registers its shutdown with // t.Cleanup. func Start(t testing.TB, o Options) *Server { t.Helper() if len(o.HostKeys) == 0 { ed, ec := GenKeys(t) o.HostKeys = []ssh.Signer{ed, ec} } pass := o.Password if pass == "" && len(o.AuthorizedKeys) == 0 { pass = DefaultPassword } cfg := &ssh.ServerConfig{} if pass != "" { cfg.PasswordCallback = func(_ ssh.ConnMetadata, p []byte) (*ssh.Permissions, error) { if string(p) == pass { return nil, nil } return nil, errors.New("password rejected") } } if len(o.AuthorizedKeys) > 0 { keys := o.AuthorizedKeys cfg.PublicKeyCallback = func(_ ssh.ConnMetadata, k ssh.PublicKey) (*ssh.Permissions, error) { for _, ak := range keys { if ak.Type() == k.Type() && string(ak.Marshal()) == string(k.Marshal()) { return nil, nil } } return nil, errors.New("key rejected") } } for _, k := range o.HostKeys { cfg.AddHostKey(k) } ln, err := net.Listen("tcp", "127.0.0.1:0") if err != nil { t.Fatalf("sshtest: listen: %v", err) } ctx, cancel := context.WithCancel(context.Background()) root := o.Chroot if root == "" { root = "/" } s := &Server{ Addr: ln.Addr().String(), HostKeys: o.HostKeys, Root: root, Password: pass, opts: o, cfg: cfg, ln: ln, ctx: ctx, cancel: cancel, conns: map[net.Conn]struct{}{}, } s.wg.Add(1) go s.acceptLoop() t.Cleanup(s.Close) return s } // Port returns the TCP port of Addr. func (s *Server) Port() string { _, p, _ := net.SplitHostPort(s.Addr) return p } // Close stops the server, drops all connections and waits for every // goroutine to exit. It is idempotent and called automatically by Cleanup. func (s *Server) Close() { s.mu.Lock() if s.closed { s.mu.Unlock() return } s.closed = true for c := range s.conns { c.Close() } s.mu.Unlock() s.cancel() s.ln.Close() s.wg.Wait() } // DropConnections closes every live client connection, leaving the server // listening (simulates a server-side disconnect). func (s *Server) DropConnections() { s.mu.Lock() defer s.mu.Unlock() for c := range s.conns { c.Close() } } func (s *Server) track(c net.Conn) bool { s.mu.Lock() defer s.mu.Unlock() if s.closed { return false } s.conns[c] = struct{}{} return true } func (s *Server) untrack(c net.Conn) { s.mu.Lock() delete(s.conns, c) s.mu.Unlock() } func (s *Server) acceptLoop() { defer s.wg.Done() for { nc, err := s.ln.Accept() if err != nil { return } if !s.track(nc) { nc.Close() return } s.wg.Add(1) go func() { defer s.wg.Done() defer s.untrack(nc) defer nc.Close() s.handle(nc) }() } } func (s *Server) handle(nc net.Conn) { sconn, chans, reqs, err := ssh.NewServerConn(nc, s.cfg) if err != nil { return } defer sconn.Close() s.wg.Add(1) go func() { defer s.wg.Done() ssh.DiscardRequests(reqs) }() for nch := range chans { if nch.ChannelType() != "session" { nch.Reject(ssh.UnknownChannelType, "only session channels") continue } ch, creqs, err := nch.Accept() if err != nil { continue } s.wg.Add(1) go func() { defer s.wg.Done() s.session(ch, creqs) }() } } func (s *Server) session(ch ssh.Channel, reqs <-chan *ssh.Request) { defer ch.Close() started := false var work sync.WaitGroup defer work.Wait() for req := range reqs { switch { case req.Type == "subsystem" && !started: name, ok := parseString(req.Payload) if !ok || name != "sftp" { req.Reply(false, nil) continue } var opts []sftp.ServerOption if s.opts.Chroot != "" { opts = append(opts, sftp.WithServerWorkingDirectory(s.opts.Chroot)) } srv, err := sftp.NewServer(ch, opts...) if err != nil { req.Reply(false, nil) continue } started = true req.Reply(true, nil) work.Add(1) go func() { defer work.Done() srv.Serve() srv.Close() ch.Close() }() case req.Type == "exec" && !started: if s.opts.NoExec { req.Reply(false, nil) continue } cmdStr, ok := parseString(req.Payload) if !ok { req.Reply(false, nil) continue } started = true req.Reply(true, nil) work.Add(1) go func() { defer work.Done() s.runExec(ch, cmdStr) }() default: if req.WantReply { req.Reply(false, nil) } } } } func (s *Server) runExec(ch ssh.Channel, cmdStr string) { c := exec.CommandContext(s.ctx, "sh", "-c", cmdStr) c.WaitDelay = time.Second if s.opts.Chroot != "" { c.Dir = s.opts.Chroot } c.Stdout = ch c.Stderr = ch.Stderr() code := 0 if err := c.Run(); err != nil { code = 127 var ee *exec.ExitError if errors.As(err, &ee) && ee.ExitCode() >= 0 { code = ee.ExitCode() } } st := make([]byte, 4) binary.BigEndian.PutUint32(st, uint32(code)) ch.SendRequest("exit-status", false, st) ch.Close() } // parseString decodes an SSH wire-format string (uint32 length + bytes). func parseString(b []byte) (string, bool) { if len(b) < 4 { return "", false } n := binary.BigEndian.Uint32(b) if uint64(len(b)-4) < uint64(n) { return "", false } return string(b[4 : 4+n]), true } // ClientConfig returns an ssh.ClientConfig that authenticates to s with its // password and pins its first host key. func (s *Server) ClientConfig(user string) *ssh.ClientConfig { if user == "" { user = "u" } cfg := &ssh.ClientConfig{ User: user, Timeout: 5 * time.Second, HostKeyCallback: func(_ string, _ net.Addr, key ssh.PublicKey) error { for _, hk := range s.HostKeys { if string(hk.PublicKey().Marshal()) == string(key.Marshal()) { return nil } } return fmt.Errorf("sshtest: unexpected host key %s", key.Type()) }, } if s.Password != "" { cfg.Auth = []ssh.AuthMethod{ssh.Password(s.Password)} } return cfg } // Dial connects to addr (s.Addr or a proxy in front of it) with // ClientConfig and closes the client on Cleanup. func (s *Server) Dial(t testing.TB, addr string) *ssh.Client { t.Helper() if addr == "" { addr = s.Addr } c, err := ssh.Dial("tcp", addr, s.ClientConfig("")) if err != nil { t.Fatalf("sshtest: dial %s: %v", addr, err) } t.Cleanup(func() { c.Close() }) return c }