test: add in-process SSH/SFTP server and fault proxy (internal/testutil/sshtest)
Ports the analysts' testbed into a reusable package: Start(Options{Password,
AuthorizedKeys, HostKeys, NoExec, Chroot}), NewProxy with SetDelay/Freeze/
CutAfter/KillAll, IsolatedHome, GenKeys. Exec reports exit-status and
stderr; NoExec rejects exec like ForceCommand internal-sftp. All goroutines
stop on t.Cleanup (checked via runtime.NumGoroutine).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
407d758fa3
commit
05da3c0d30
4 changed files with 910 additions and 0 deletions
67
internal/testutil/sshtest/home.go
Normal file
67
internal/testutil/sshtest/home.go
Normal file
|
|
@ -0,0 +1,67 @@
|
||||||
|
package sshtest
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/ecdsa"
|
||||||
|
"crypto/ed25519"
|
||||||
|
"crypto/elliptic"
|
||||||
|
"crypto/rand"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"golang.org/x/crypto/ssh"
|
||||||
|
)
|
||||||
|
|
||||||
|
// IsolatedHome points HOME at a fresh temp dir (with ~/.ssh, mode 0700),
|
||||||
|
// clears SSH_AUTH_SOCK so no real agent is used, and returns the new HOME.
|
||||||
|
// Uses t.Setenv, so the test must not be parallel.
|
||||||
|
func IsolatedHome(t testing.TB) string {
|
||||||
|
t.Helper()
|
||||||
|
home := t.TempDir()
|
||||||
|
t.Setenv("HOME", home)
|
||||||
|
t.Setenv("SSH_AUTH_SOCK", "")
|
||||||
|
t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config"))
|
||||||
|
if err := os.MkdirAll(filepath.Join(home, ".ssh"), 0o700); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return home
|
||||||
|
}
|
||||||
|
|
||||||
|
// GenKeys returns a fresh ed25519 signer and a fresh ECDSA P-256 signer.
|
||||||
|
func GenKeys(t testing.TB) (ed, ec ssh.Signer) {
|
||||||
|
t.Helper()
|
||||||
|
_, edPriv, err := ed25519.GenerateKey(rand.Reader)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if ed, err = ssh.NewSignerFromKey(edPriv); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
ecPriv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if ec, err = ssh.NewSignerFromKey(ecPriv); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return ed, ec
|
||||||
|
}
|
||||||
|
|
||||||
|
// WriteRandom creates p (and parents) with size random bytes and mode.
|
||||||
|
func WriteRandom(t testing.TB, p string, size int, mode os.FileMode) []byte {
|
||||||
|
t.Helper()
|
||||||
|
if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
b := make([]byte, size)
|
||||||
|
if _, err := rand.Read(b); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := os.WriteFile(p, b, mode); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := os.Chmod(p, mode); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return b
|
||||||
|
}
|
||||||
222
internal/testutil/sshtest/proxy.go
Normal file
222
internal/testutil/sshtest/proxy.go
Normal file
|
|
@ -0,0 +1,222 @@
|
||||||
|
package sshtest
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net"
|
||||||
|
"sync"
|
||||||
|
"sync/atomic"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Proxy is a TCP proxy in front of a target address that can inject latency,
|
||||||
|
// freeze traffic, or cut connections after a number of bytes.
|
||||||
|
type Proxy struct {
|
||||||
|
// Addr is host:port to dial instead of the target.
|
||||||
|
Addr string
|
||||||
|
|
||||||
|
target string
|
||||||
|
ln net.Listener
|
||||||
|
|
||||||
|
delay atomic.Int64 // one-way delay in nanoseconds, applied both ways
|
||||||
|
frozen atomic.Bool
|
||||||
|
sent atomic.Int64 // client->server bytes, all connections
|
||||||
|
cutAt atomic.Int64 // 0 = disabled; kill all when sent exceeds it
|
||||||
|
|
||||||
|
mu sync.Mutex
|
||||||
|
links map[*link]struct{}
|
||||||
|
closed bool
|
||||||
|
wg sync.WaitGroup
|
||||||
|
}
|
||||||
|
|
||||||
|
type link struct {
|
||||||
|
client, upstream net.Conn
|
||||||
|
done chan struct{}
|
||||||
|
once sync.Once
|
||||||
|
}
|
||||||
|
|
||||||
|
func (l *link) kill() {
|
||||||
|
l.once.Do(func() {
|
||||||
|
close(l.done)
|
||||||
|
l.client.Close()
|
||||||
|
l.upstream.Close()
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewProxy starts a proxy to target and registers its shutdown with
|
||||||
|
// t.Cleanup.
|
||||||
|
func NewProxy(t testing.TB, target string) *Proxy {
|
||||||
|
t.Helper()
|
||||||
|
ln, err := net.Listen("tcp", "127.0.0.1:0")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("sshtest: proxy listen: %v", err)
|
||||||
|
}
|
||||||
|
p := &Proxy{Addr: ln.Addr().String(), target: target, ln: ln, links: map[*link]struct{}{}}
|
||||||
|
p.wg.Add(1)
|
||||||
|
go p.acceptLoop()
|
||||||
|
t.Cleanup(p.Close)
|
||||||
|
return p
|
||||||
|
}
|
||||||
|
|
||||||
|
// Port returns the TCP port of Addr.
|
||||||
|
func (p *Proxy) Port() string {
|
||||||
|
_, port, _ := net.SplitHostPort(p.Addr)
|
||||||
|
return port
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetDelay sets the one-way latency applied to every chunk in both
|
||||||
|
// directions (RTT grows by about 2*d).
|
||||||
|
func (p *Proxy) SetDelay(d time.Duration) { p.delay.Store(int64(d)) }
|
||||||
|
|
||||||
|
// Freeze stops (on=true) or resumes forwarding in both directions. Data is
|
||||||
|
// buffered while frozen, connections stay open.
|
||||||
|
func (p *Proxy) Freeze(on bool) { p.frozen.Store(on) }
|
||||||
|
|
||||||
|
// CutAfter kills all current connections once n more bytes have been sent
|
||||||
|
// client->server (counted across connections). The trigger fires once;
|
||||||
|
// n <= 0 disarms it.
|
||||||
|
func (p *Proxy) CutAfter(n int64) {
|
||||||
|
if n <= 0 {
|
||||||
|
p.cutAt.Store(0)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
p.cutAt.Store(p.sent.Load() + n)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Sent reports the total client->server bytes forwarded so far.
|
||||||
|
func (p *Proxy) Sent() int64 { return p.sent.Load() }
|
||||||
|
|
||||||
|
// KillAll closes every current connection; the proxy keeps accepting new
|
||||||
|
// ones.
|
||||||
|
func (p *Proxy) KillAll() {
|
||||||
|
p.mu.Lock()
|
||||||
|
ls := make([]*link, 0, len(p.links))
|
||||||
|
for l := range p.links {
|
||||||
|
ls = append(ls, l)
|
||||||
|
}
|
||||||
|
p.mu.Unlock()
|
||||||
|
for _, l := range ls {
|
||||||
|
l.kill()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Close stops the proxy and waits for all its goroutines. Idempotent.
|
||||||
|
func (p *Proxy) Close() {
|
||||||
|
p.mu.Lock()
|
||||||
|
if p.closed {
|
||||||
|
p.mu.Unlock()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
p.closed = true
|
||||||
|
p.mu.Unlock()
|
||||||
|
p.ln.Close()
|
||||||
|
p.KillAll()
|
||||||
|
p.wg.Wait()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *Proxy) acceptLoop() {
|
||||||
|
defer p.wg.Done()
|
||||||
|
for {
|
||||||
|
c, err := p.ln.Accept()
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
u, err := net.DialTimeout("tcp", p.target, 5*time.Second)
|
||||||
|
if err != nil {
|
||||||
|
c.Close()
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
l := &link{client: c, upstream: u, done: make(chan struct{})}
|
||||||
|
p.mu.Lock()
|
||||||
|
if p.closed {
|
||||||
|
p.mu.Unlock()
|
||||||
|
l.kill()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
p.links[l] = struct{}{}
|
||||||
|
p.mu.Unlock()
|
||||||
|
var lw sync.WaitGroup
|
||||||
|
lw.Add(2)
|
||||||
|
p.wg.Add(1)
|
||||||
|
go func() {
|
||||||
|
defer p.wg.Done()
|
||||||
|
lw.Wait()
|
||||||
|
l.kill()
|
||||||
|
p.mu.Lock()
|
||||||
|
delete(p.links, l)
|
||||||
|
p.mu.Unlock()
|
||||||
|
}()
|
||||||
|
go func() { defer lw.Done(); p.pipe(l, c, u, true) }()
|
||||||
|
go func() { defer lw.Done(); p.pipe(l, u, c, false) }()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type chunk struct {
|
||||||
|
b []byte
|
||||||
|
at time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
// pipe forwards src -> dst through a delay queue. Returning from either
|
||||||
|
// direction kills the whole link.
|
||||||
|
func (p *Proxy) pipe(l *link, src, dst net.Conn, upstream bool) {
|
||||||
|
defer l.kill()
|
||||||
|
q := make(chan chunk, 1024)
|
||||||
|
writerDone := make(chan struct{})
|
||||||
|
go func() {
|
||||||
|
defer close(writerDone)
|
||||||
|
defer l.kill()
|
||||||
|
for {
|
||||||
|
var c chunk
|
||||||
|
var ok bool
|
||||||
|
select {
|
||||||
|
case c, ok = <-q:
|
||||||
|
if !ok {
|
||||||
|
return // reader finished and queue drained
|
||||||
|
}
|
||||||
|
case <-l.done:
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if d := time.Until(c.at); d > 0 {
|
||||||
|
t := time.NewTimer(d)
|
||||||
|
select {
|
||||||
|
case <-t.C:
|
||||||
|
case <-l.done:
|
||||||
|
t.Stop()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for p.frozen.Load() {
|
||||||
|
select {
|
||||||
|
case <-time.After(5 * time.Millisecond):
|
||||||
|
case <-l.done:
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if _, err := dst.Write(c.b); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
defer func() { close(q); <-writerDone }()
|
||||||
|
buf := make([]byte, 32*1024)
|
||||||
|
for {
|
||||||
|
n, err := src.Read(buf)
|
||||||
|
if n > 0 {
|
||||||
|
if upstream {
|
||||||
|
total := p.sent.Add(int64(n))
|
||||||
|
if lim := p.cutAt.Load(); lim > 0 && total > lim && p.cutAt.CompareAndSwap(lim, 0) {
|
||||||
|
p.KillAll()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
c := chunk{b: append([]byte(nil), buf[:n]...), at: time.Now().Add(time.Duration(p.delay.Load()))}
|
||||||
|
select {
|
||||||
|
case q <- c:
|
||||||
|
case <-l.done:
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
357
internal/testutil/sshtest/server.go
Normal file
357
internal/testutil/sshtest/server.go
Normal file
|
|
@ -0,0 +1,357 @@
|
||||||
|
// 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
|
||||||
|
}
|
||||||
264
internal/testutil/sshtest/sshtest_test.go
Normal file
264
internal/testutil/sshtest/sshtest_test.go
Normal file
|
|
@ -0,0 +1,264 @@
|
||||||
|
package sshtest
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"errors"
|
||||||
|
"io"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"runtime"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/pkg/sftp"
|
||||||
|
"golang.org/x/crypto/ssh"
|
||||||
|
)
|
||||||
|
|
||||||
|
// noLeak runs fn as a subtest (so its Cleanups run) and then checks that the
|
||||||
|
// goroutine count returns to the baseline within ±2.
|
||||||
|
func noLeak(t *testing.T, fn func(t *testing.T)) {
|
||||||
|
t.Helper()
|
||||||
|
runtime.GC()
|
||||||
|
base := runtime.NumGoroutine()
|
||||||
|
t.Run("body", fn)
|
||||||
|
deadline := time.Now().Add(3 * time.Second)
|
||||||
|
var n int
|
||||||
|
for time.Now().Before(deadline) {
|
||||||
|
n = runtime.NumGoroutine()
|
||||||
|
if n <= base+2 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
time.Sleep(20 * time.Millisecond)
|
||||||
|
}
|
||||||
|
buf := make([]byte, 1<<20)
|
||||||
|
buf = buf[:runtime.Stack(buf, true)]
|
||||||
|
t.Errorf("goroutines: base=%d after cleanup=%d\n%s", base, n, buf)
|
||||||
|
}
|
||||||
|
|
||||||
|
func sftpClient(t *testing.T, c *ssh.Client) *sftp.Client {
|
||||||
|
t.Helper()
|
||||||
|
sc, err := sftp.NewClient(c)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Cleanup(func() { sc.Close() })
|
||||||
|
return sc
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestServerSFTPRoundTrip(t *testing.T) {
|
||||||
|
noLeak(t, func(t *testing.T) {
|
||||||
|
srv := Start(t, Options{})
|
||||||
|
sc := sftpClient(t, srv.Dial(t, ""))
|
||||||
|
dir := t.TempDir()
|
||||||
|
p := filepath.Join(dir, "sub", "f.bin")
|
||||||
|
if err := sc.MkdirAll(filepath.Dir(p)); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
want := bytes.Repeat([]byte("vcom"), 50000)
|
||||||
|
f, err := sc.Create(p)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := f.Write(want); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := f.Close(); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
got, err := os.ReadFile(p)
|
||||||
|
if err != nil || !bytes.Equal(got, want) {
|
||||||
|
t.Fatalf("disk content mismatch: err=%v len=%d", err, len(got))
|
||||||
|
}
|
||||||
|
r, err := sc.Open(p)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
back, err := io.ReadAll(r)
|
||||||
|
r.Close()
|
||||||
|
if err != nil || !bytes.Equal(back, want) {
|
||||||
|
t.Fatalf("read back mismatch: err=%v len=%d", err, len(back))
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestServerChrootWorkingDir(t *testing.T) {
|
||||||
|
root := t.TempDir()
|
||||||
|
WriteRandom(t, filepath.Join(root, "x.bin"), 10, 0o644)
|
||||||
|
srv := Start(t, Options{Chroot: root})
|
||||||
|
sc := sftpClient(t, srv.Dial(t, ""))
|
||||||
|
if _, err := sc.Stat("x.bin"); err != nil {
|
||||||
|
t.Fatalf("relative path should resolve inside Chroot: %v", err)
|
||||||
|
}
|
||||||
|
if srv.Root != root {
|
||||||
|
t.Fatalf("Root=%q want %q", srv.Root, root)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestServerExecStatusAndStderr(t *testing.T) {
|
||||||
|
noLeak(t, func(t *testing.T) {
|
||||||
|
srv := Start(t, Options{})
|
||||||
|
c := srv.Dial(t, "")
|
||||||
|
s, err := c.NewSession()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var out, errb bytes.Buffer
|
||||||
|
s.Stdout, s.Stderr = &out, &errb
|
||||||
|
err = s.Run("echo hi; echo oops >&2; exit 3")
|
||||||
|
s.Close()
|
||||||
|
var ee *ssh.ExitError
|
||||||
|
if !errors.As(err, &ee) || ee.ExitStatus() != 3 {
|
||||||
|
t.Fatalf("want exit status 3, got %v", err)
|
||||||
|
}
|
||||||
|
if out.String() != "hi\n" || errb.String() != "oops\n" {
|
||||||
|
t.Fatalf("stdout=%q stderr=%q", out.String(), errb.String())
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestServerNoExec(t *testing.T) {
|
||||||
|
srv := Start(t, Options{NoExec: true})
|
||||||
|
c := srv.Dial(t, "")
|
||||||
|
s, err := c.NewSession()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
defer s.Close()
|
||||||
|
if err := s.Run("true"); err == nil {
|
||||||
|
t.Fatal("exec must be rejected with NoExec")
|
||||||
|
}
|
||||||
|
sftpClient(t, c) // sftp still works
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestServerPublicKeyAuth(t *testing.T) {
|
||||||
|
ed, _ := GenKeys(t)
|
||||||
|
srv := Start(t, Options{AuthorizedKeys: []ssh.PublicKey{ed.PublicKey()}})
|
||||||
|
cfg := srv.ClientConfig("")
|
||||||
|
if _, err := ssh.Dial("tcp", srv.Addr, cfg); err == nil {
|
||||||
|
t.Fatal("password auth must be disabled when only keys are configured")
|
||||||
|
}
|
||||||
|
cfg.Auth = []ssh.AuthMethod{ssh.PublicKeys(ed)}
|
||||||
|
c, err := ssh.Dial("tcp", srv.Addr, cfg)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
c.Close()
|
||||||
|
}
|
||||||
|
|
||||||
|
func rtt(t *testing.T, sc *sftp.Client, p string) time.Duration {
|
||||||
|
t0 := time.Now()
|
||||||
|
if _, err := sc.Stat(p); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return time.Since(t0)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestProxyDelay(t *testing.T) {
|
||||||
|
noLeak(t, func(t *testing.T) {
|
||||||
|
srv := Start(t, Options{})
|
||||||
|
px := NewProxy(t, srv.Addr)
|
||||||
|
sc := sftpClient(t, srv.Dial(t, px.Addr))
|
||||||
|
dir := t.TempDir()
|
||||||
|
base := rtt(t, sc, dir)
|
||||||
|
const d = 40 * time.Millisecond
|
||||||
|
px.SetDelay(d)
|
||||||
|
got := rtt(t, sc, dir)
|
||||||
|
t.Logf("rtt without delay=%v with %v one-way delay=%v", base, d, got)
|
||||||
|
if got < d {
|
||||||
|
t.Fatalf("rtt %v < delay %v", got, d)
|
||||||
|
}
|
||||||
|
px.SetDelay(0)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestProxyFreeze(t *testing.T) {
|
||||||
|
noLeak(t, func(t *testing.T) {
|
||||||
|
srv := Start(t, Options{})
|
||||||
|
px := NewProxy(t, srv.Addr)
|
||||||
|
sc := sftpClient(t, srv.Dial(t, px.Addr))
|
||||||
|
dir := t.TempDir()
|
||||||
|
px.Freeze(true)
|
||||||
|
res := make(chan error, 1)
|
||||||
|
go func() { _, err := sc.ReadDir(dir); res <- err }()
|
||||||
|
select {
|
||||||
|
case err := <-res:
|
||||||
|
t.Fatalf("request completed while frozen: %v", err)
|
||||||
|
case <-time.After(300 * time.Millisecond):
|
||||||
|
}
|
||||||
|
px.Freeze(false)
|
||||||
|
select {
|
||||||
|
case err := <-res:
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("request failed after unfreeze: %v", err)
|
||||||
|
}
|
||||||
|
case <-time.After(5 * time.Second):
|
||||||
|
t.Fatal("request did not complete after unfreeze")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestProxyCut(t *testing.T) {
|
||||||
|
noLeak(t, func(t *testing.T) {
|
||||||
|
srv := Start(t, Options{})
|
||||||
|
px := NewProxy(t, srv.Addr)
|
||||||
|
c := srv.Dial(t, px.Addr)
|
||||||
|
sc := sftpClient(t, c)
|
||||||
|
dir := t.TempDir()
|
||||||
|
before := px.Sent()
|
||||||
|
px.CutAfter(256 << 10)
|
||||||
|
f, err := sc.Create(filepath.Join(dir, "big.bin"))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
_, werr := f.Write(make([]byte, 4<<20))
|
||||||
|
f.Close()
|
||||||
|
if werr == nil {
|
||||||
|
t.Fatal("write of 4 MiB should fail after cut at 256 KiB")
|
||||||
|
}
|
||||||
|
sent := px.Sent() - before
|
||||||
|
if sent > 1<<20 {
|
||||||
|
t.Fatalf("proxy forwarded %d bytes after a 256 KiB cut", sent)
|
||||||
|
}
|
||||||
|
done := make(chan struct{})
|
||||||
|
go func() { c.Wait(); close(done) }()
|
||||||
|
select {
|
||||||
|
case <-done:
|
||||||
|
case <-time.After(5 * time.Second):
|
||||||
|
t.Fatal("ssh connection still alive after cut")
|
||||||
|
}
|
||||||
|
// The proxy keeps accepting connections after a cut.
|
||||||
|
sc2 := sftpClient(t, srv.Dial(t, px.Addr))
|
||||||
|
if _, err := sc2.Stat(dir); err != nil {
|
||||||
|
t.Fatalf("new connection after cut: %v", err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestProxyKillAll(t *testing.T) {
|
||||||
|
srv := Start(t, Options{})
|
||||||
|
px := NewProxy(t, srv.Addr)
|
||||||
|
c := srv.Dial(t, px.Addr)
|
||||||
|
px.KillAll()
|
||||||
|
done := make(chan error, 1)
|
||||||
|
go func() { done <- c.Wait() }()
|
||||||
|
select {
|
||||||
|
case <-done:
|
||||||
|
case <-time.After(5 * time.Second):
|
||||||
|
t.Fatal("connection survived KillAll")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestIsolatedHome(t *testing.T) {
|
||||||
|
h := IsolatedHome(t)
|
||||||
|
if os.Getenv("HOME") != h || os.Getenv("SSH_AUTH_SOCK") != "" {
|
||||||
|
t.Fatal("env not isolated")
|
||||||
|
}
|
||||||
|
st, err := os.Stat(filepath.Join(h, ".ssh"))
|
||||||
|
if err != nil || st.Mode().Perm() != 0o700 {
|
||||||
|
t.Fatalf(".ssh: %v %v", st, err)
|
||||||
|
}
|
||||||
|
if !strings.HasPrefix(h, os.TempDir()) {
|
||||||
|
t.Logf("home outside TMPDIR: %s", h)
|
||||||
|
}
|
||||||
|
}
|
||||||
Loading…
Add table
Add a link
Reference in a new issue