diff --git a/docs/amcd-bootstrap.md b/docs/amcd-bootstrap.md index 2af81ce..197a6dc 100644 --- a/docs/amcd-bootstrap.md +++ b/docs/amcd-bootstrap.md @@ -5,6 +5,14 @@ task launches the local WSL `amcd` process automatically without storing a passw token. It is host-control infrastructure; it does not select, enroll, start, stop, or otherwise mutate a virtual machine. +For Linux-local state, the automatic listener prefers IPv6 loopback with IPv4 fallback. Shared +Windows-backed state and native Windows keep IPv4 so both environments can reach the daemon. +This avoids IPv4 loopback relays for local WSL clients while preserving shared-state compatibility. +Clients discover the selected address from the protected endpoint record; an explicit +`amcd run --listen` address remains exact. The generated bootstrap wrapper leaves this selection +automatic. Existing installations retain their exact IPv4 wrapper and matching old controller +until the explicit package-upgrade procedure below. + ## Package companion WSL bootstrap requires the matching architecture's `amcd-launcher.exe` beside the immutable Linux @@ -119,7 +127,7 @@ so its initial process does not allocate a console or activate Windows Terminal. Windows PowerShell through `GetSystemDirectoryW` and starts it with `CREATE_NO_WINDOW` and fixed non-interactive `-File` arguments. The wrapper uses `ProcessStartInfo` with `UseShellExecute=false` and `CreateNoWindow=true` for the exact Windows `wsl.exe` path, validated WSL distribution and Linux -user, exact Linux `amcd` path, state directory, loopback listen address, and fixed daemon flags. +user, exact Linux `amcd` path, state directory, optional explicit loopback address, and fixed daemon flags. Both launchers wait and return the child's exit code. No Terminal preferences or unrelated windows or processes are changed. The three files and their directory have a canonical protected DACL with exactly two explicit FullControl allow diff --git a/docs/guest-operations.md b/docs/guest-operations.md index d08020c..a393159 100644 --- a/docs/guest-operations.md +++ b/docs/guest-operations.md @@ -111,3 +111,9 @@ installed revision and intended Windows target. Measure cold preparation separat commands, upload, download and owned deletion. Include payload size, digest verification, durable commit, final receipt and cleanup time. Report RPC overhead separately from guest execution where the evidence permits; retain compact receipts and remove owned fixtures after each run. + +Measure any host TCP forwarding separately from the guest's direct, operator-provisioned SSH +endpoint. A forwarding service can limit throughput even when guest disk writes and hashing are +fast. Verify the exact enrolled VM and its existing SSH host-key pin before changing the protected +endpoint. Retire the original worker under its original configuration first; a changed route starts +a new authority generation. Existing authenticated terminal connections can retain their own route. diff --git a/internal/app/bootstrap_types.go b/internal/app/bootstrap_types.go index 67de367..0267cd4 100644 --- a/internal/app/bootstrap_types.go +++ b/internal/app/bootstrap_types.go @@ -137,7 +137,7 @@ func (s BootstrapSpec) validateSettings() error { if s.ExecutionTimeLimit != "PT0S" || !s.AllowStartOnBatteries || !s.DontStopOnBatteries { return fmt.Errorf("%w: task settings can interrupt the daemon", ErrBootstrapDrift) } - if s.ListenAddress != "127.0.0.1:0" { + if s.ListenAddress != "" && s.ListenAddress != "127.0.0.1:0" { return fmt.Errorf("%w: daemon listen address must be ephemeral loopback", ErrBootstrapDrift) } return nil diff --git a/internal/bootstrap/adapter.go b/internal/bootstrap/adapter.go index e5732a0..09e74cb 100644 --- a/internal/bootstrap/adapter.go +++ b/internal/bootstrap/adapter.go @@ -339,7 +339,7 @@ func buildSpec(host hostContext, identity app.BootstrapIdentity, distro, linuxUs Distro: distro, LinuxUser: linuxUser, StateDir: stateRoot, WrapperPath: wrapperPath, MetadataPath: metadataPath, BinaryPath: binaryPath, BinarySHA256: binaryHash, - WSLExecutable: host.WSLExecutable, ListenAddress: "127.0.0.1:0", + WSLExecutable: host.WSLExecutable, } wrapper, err := wrapperBytes(spec) if err != nil { @@ -366,6 +366,10 @@ func wrapperBytes(spec app.BootstrapSpec) ([]byte, error) { return nil, fmt.Errorf("%w: unsafe %s", app.ErrBootstrapUnsupported, label) } } + listenArguments := "" + if spec.ListenAddress != "" { + listenArguments = fmt.Sprintf(" '--listen',\n '%s',\n", quoteWindowsArgument(spec.ListenAddress)) + } launcher := fmt.Sprintf(`$ErrorActionPreference = 'Stop' $arguments = @( '-d', @@ -377,9 +381,7 @@ $arguments = @( 'run', '--state-dir', '%s', - '--listen', - '%s', - '--json' +%s '--json' ) $start = [Diagnostics.ProcessStartInfo]::new() $start.FileName = '%s' @@ -389,7 +391,7 @@ $start.CreateNoWindow = $true $child = [Diagnostics.Process]::Start($start) $child.WaitForExit() exit $child.ExitCode -`, quoteWindowsArgument(spec.Distro), quoteWindowsArgument(spec.LinuxUser), quoteWindowsArgument(spec.BinaryPath), quoteWindowsArgument(spec.StateDir), quoteWindowsArgument(spec.ListenAddress), spec.WSLExecutable) +`, quoteWindowsArgument(spec.Distro), quoteWindowsArgument(spec.LinuxUser), quoteWindowsArgument(spec.BinaryPath), quoteWindowsArgument(spec.StateDir), listenArguments, spec.WSLExecutable) return []byte(launcher), nil } diff --git a/internal/bootstrap/adapter_test.go b/internal/bootstrap/adapter_test.go index fe257e0..10409fd 100644 --- a/internal/bootstrap/adapter_test.go +++ b/internal/bootstrap/adapter_test.go @@ -321,6 +321,9 @@ func TestBuildSpecProducesExactInteractiveLimitedFingerprint(t *testing.T) { if spec.MultipleInstances != "IgnoreNew" || spec.ExecutionTimeLimit != "PT0S" { t.Fatalf("unsafe lifecycle settings: %#v", spec) } + if spec.ListenAddress != "" { + t.Fatalf("bootstrap must leave listener selection automatic: %q", spec.ListenAddress) + } if err := spec.Validate(identity); err != nil { t.Fatalf("spec.Validate() error = %v", err) } diff --git a/internal/bootstrap/wrapper_listen_test.go b/internal/bootstrap/wrapper_listen_test.go new file mode 100644 index 0000000..ef2148e --- /dev/null +++ b/internal/bootstrap/wrapper_listen_test.go @@ -0,0 +1,25 @@ +package bootstrap + +import ( + "strings" + "testing" + + "github.com/Horcag/agent-machine-control/internal/app" +) + +func TestWrapperAutomaticListenerOmitsAddressArguments(t *testing.T) { + spec := app.BootstrapSpec{WSLExecutable: `C:\Windows\System32\wsl.exe`, Distro: "Synthetic-WSL", LinuxUser: "operator", BinaryPath: "/bin/amcd", StateDir: "/state"} + for _, address := range []string{"", "127.0.0.1:0"} { + spec.ListenAddress = address + body, err := wrapperBytes(spec) + if err != nil { + t.Fatal(err) + } + if strings.Contains(string(body), "'--listen'") != (address != "") { + t.Fatalf("wrong automatic/explicit listener arguments for %q", address) + } + if !strings.Contains(string(body), "'--state-dir',\n '/state',") || !strings.Contains(string(body), "'--json'") { + t.Fatal("automatic listener lost adjacent native arguments") + } + } +} diff --git a/internal/bootstrap/wrapper_test.go b/internal/bootstrap/wrapper_test.go index 681672c..508018d 100644 --- a/internal/bootstrap/wrapper_test.go +++ b/internal/bootstrap/wrapper_test.go @@ -33,8 +33,15 @@ func TestWrapperStartsConsolelessChildAndPreservesExitAndArguments(t *testing.T) return strings.TrimSpace(string(out)) } dir, binary, launcher := buildWindowsTestExecutables(t) + for _, address := range []string{"", "127.0.0.1:0"} { + t.Run("listen="+address, func(t *testing.T) { checkWrapperInvocation(t, dir, binary, launcher, address, winPath) }) + } +} + +func checkWrapperInvocation(t *testing.T, dir, binary, launcher, address string, winPath func(string) string) { + t.Helper() output := filepath.Join(dir, "child observation.json") - spec := app.BootstrapSpec{WSLExecutable: winPath(binary), Distro: "Synthetic WSL", LinuxUser: "operator", BinaryPath: "/synthetic path/amcd", StateDir: winPath(output), ListenAddress: "127.0.0.1:0"} + spec := app.BootstrapSpec{WSLExecutable: winPath(binary), Distro: "Synthetic WSL", LinuxUser: "operator", BinaryPath: "/synthetic path/amcd", StateDir: winPath(output), ListenAddress: address} wrapper, err := wrapperBytes(spec) if err != nil { t.Fatal(err) @@ -46,6 +53,7 @@ func TestWrapperStartsConsolelessChildAndPreservesExitAndArguments(t *testing.T) if _, _, err := launcherArtifact(filepath.Join(dir, "amcd"), "Synthetic-WSL"); err != nil { t.Fatal(err) } + // #nosec G204 -- launcher is built from repository-owned source in this test's private directory. command := exec.CommandContext(t.Context(), launcher, "-NoLogo", "-NoProfile", "-NonInteractive", "-WindowStyle", "Hidden", "-ExecutionPolicy", "Bypass", "-File", winPath(wrapperPath)) out, err := command.CombinedOutput() var exit *exec.ExitError @@ -66,7 +74,11 @@ func TestWrapperStartsConsolelessChildAndPreservesExitAndArguments(t *testing.T) if observation.Console != 0 { t.Fatal("launcher allocated a console for its child") } - want := []string{"-d", spec.Distro, "--user", spec.LinuxUser, "--exec", spec.BinaryPath, "run", "--state-dir", spec.StateDir, "--listen", spec.ListenAddress, "--json"} + want := []string{"-d", spec.Distro, "--user", spec.LinuxUser, "--exec", spec.BinaryPath, "run", "--state-dir", spec.StateDir} + if address != "" { + want = append(want, "--listen", address) + } + want = append(want, "--json") if !reflect.DeepEqual(observation.Args, want) { t.Fatalf("child arguments: %q, want %q", observation.Args, want) } diff --git a/internal/daemon/handlers_internal_test.go b/internal/daemon/handlers_internal_test.go index 07f652f..9652c83 100644 --- a/internal/daemon/handlers_internal_test.go +++ b/internal/daemon/handlers_internal_test.go @@ -140,7 +140,7 @@ func TestServer_StartDefaultListenAddr(t *testing.T) { dir := missingDaemonStateRoot(t) srv, err := NewServer(Config{ StateDir: dir, - ListenAddr: "", // tests default 127.0.0.1:0 + ListenAddr: "", // tests automatic IPv6/IPv4 loopback selection }) if err != nil { t.Fatalf("NewServer failed: %v", err) diff --git a/internal/daemon/listen.go b/internal/daemon/listen.go new file mode 100644 index 0000000..48865ff --- /dev/null +++ b/internal/daemon/listen.go @@ -0,0 +1,48 @@ +package daemon + +import ( + "errors" + "fmt" + "net" +) + +// Shared Windows/WSL state retains IPv4 reachability across both environments. +// Only positively identified Linux-local state opts into the faster local path. +func preferIPv6Loopback(platform, statePath string, inspect func(string) (bool, error)) bool { + if platform != "linux" { + return false + } + shared, err := inspect(statePath) + return err == nil && !shared +} + +// Explicit addresses remain exact and never fall back to another endpoint. +func listenLoopback(addr string, preferIPv6 bool, bind func(string, string) (net.Listener, error)) (net.Listener, error) { + if addr == "" { + var ipv6Err error + if preferIPv6 { + var listener net.Listener + listener, ipv6Err = bind("tcp6", "[::1]:0") + if ipv6Err == nil { + return listener, nil + } + } + listener, ipv4Err := bind("tcp4", "127.0.0.1:0") + if ipv4Err != nil { + return nil, fmt.Errorf("daemon: failed to listen on loopback: %w", errors.Join(ipv6Err, ipv4Err)) + } + return listener, nil + } + host, _, err := net.SplitHostPort(addr) + if err != nil { + return nil, fmt.Errorf("daemon: invalid listen address %q: %w", addr, err) + } + if ip := net.ParseIP(host); ip == nil || !ip.IsLoopback() { + return nil, fmt.Errorf("daemon: listen address host %q must be a loopback IP literal", host) + } + listener, err := bind("tcp", addr) + if err != nil { + return nil, fmt.Errorf("daemon: failed to listen on %s: %w", addr, err) + } + return listener, nil +} diff --git a/internal/daemon/listen_test.go b/internal/daemon/listen_test.go new file mode 100644 index 0000000..84a1a7f --- /dev/null +++ b/internal/daemon/listen_test.go @@ -0,0 +1,109 @@ +package daemon + +import ( + "errors" + "net" + "reflect" + "testing" +) + +type loopbackSelectionCase struct { + name, address string + preferIPv6 bool + failures []error + want []string +} + +func TestLoopbackListenerSelection(t *testing.T) { + available, err := net.Listen("tcp4", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + defer available.Close() + v6, v4 := errors.New("IPv6 unavailable"), errors.New("IPv4 unavailable") + cases := []loopbackSelectionCase{ + {"automatic_ipv6", "", true, []error{nil}, []string{"tcp6 [::1]:0"}}, + {"shared_ipv4", "", false, []error{nil}, []string{"tcp4 127.0.0.1:0"}}, + {"automatic_ipv4_fallback", "", true, []error{v6, nil}, []string{"tcp6 [::1]:0", "tcp4 127.0.0.1:0"}}, + {"automatic_both_fail", "", true, []error{v6, v4}, []string{"tcp6 [::1]:0", "tcp4 127.0.0.1:0"}}, + {"explicit_ipv4", "127.0.0.1:42", true, []error{nil}, []string{"tcp 127.0.0.1:42"}}, + {"explicit_ipv6", "[::1]:42", false, []error{nil}, []string{"tcp [::1]:42"}}, + {"explicit_failure_never_falls_back", "127.0.0.1:42", true, []error{v4}, []string{"tcp 127.0.0.1:42"}}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { checkLoopbackSelection(t, tc, available) }) + } +} + +func checkLoopbackSelection(t *testing.T, tc loopbackSelectionCase, available net.Listener) { + t.Helper() + var calls []string + listener, gotErr := listenLoopback(tc.address, tc.preferIPv6, func(network, address string) (net.Listener, error) { + calls = append(calls, network+" "+address) + failure := tc.failures[len(calls)-1] + if failure != nil { + return nil, failure + } + return available, nil + }) + if !reflect.DeepEqual(calls, tc.want) { + t.Fatalf("bound %v; want %v", calls, tc.want) + } + if tc.failures[len(tc.failures)-1] == nil { + if gotErr != nil || listener != available { + t.Fatalf("successful bind lost: %v", gotErr) + } + return + } + if listener != nil { + t.Fatal("failed bind returned listener") + } + for _, wantErr := range tc.failures { + if wantErr != nil && !errors.Is(gotErr, wantErr) { + t.Fatalf("bind failure %v lost: %v", wantErr, gotErr) + } + } +} + +func TestIPv6PreferenceRequiresLinuxLocalState(t *testing.T) { + for _, tc := range []struct { + name, platform string + shared bool + err error + want bool + }{ + {"windows", "windows", false, nil, false}, + {"other_platform", "darwin", false, nil, false}, + {"linux_local", "linux", false, nil, true}, + {"shared_windows_mount", "linux", true, nil, false}, + {"unknown_mount", "linux", false, errors.New("mount inspection failed"), false}, + } { + t.Run(tc.name, func(t *testing.T) { + called := false + got := preferIPv6Loopback(tc.platform, "/synthetic/state", func(path string) (bool, error) { + called = true + if path != "/synthetic/state" { + t.Fatal("wrong state inspected") + } + return tc.shared, tc.err + }) + if got != tc.want || called != (tc.platform == "linux") { + t.Fatalf("preference=%v inspection=%v", got, called) + } + }) + } +} + +func TestLoopbackListenerRejectsUnsafeAddressesBeforeBind(t *testing.T) { + for _, address := range []string{"0.0.0.0:0", "[::]:0", "192.0.2.10:0", "localhost:0", "malformed"} { + t.Run(address, func(t *testing.T) { + _, err := listenLoopback(address, true, func(string, string) (net.Listener, error) { + t.Fatal("unsafe address reached bind") + return nil, nil + }) + if err == nil { + t.Fatal("unsafe address accepted") + } + }) + } +} diff --git a/internal/daemon/server.go b/internal/daemon/server.go index 1452c41..4984152 100644 --- a/internal/daemon/server.go +++ b/internal/daemon/server.go @@ -9,6 +9,7 @@ import ( "net" "net/http" "path/filepath" + "runtime" "strings" "sync" "sync/atomic" @@ -28,6 +29,7 @@ import ( "github.com/Horcag/agent-machine-control/internal/receipt" "github.com/Horcag/agent-machine-control/internal/sessions" "github.com/Horcag/agent-machine-control/internal/statedir" + "github.com/Horcag/agent-machine-control/internal/wslruntime" ) type contextKey string @@ -365,32 +367,13 @@ func (s *Server) dispatchReceiptSubroute(w http.ResponseWriter, r *http.Request, // Start opens the network listener and records the daemon endpoint. func (s *Server) Start() error { - addr := s.cfg.ListenAddr - if addr == "" { - addr = "127.0.0.1:0" - } - - host, _, err := net.SplitHostPort(addr) - if err != nil { - if s.singletonLock != nil { - _ = s.singletonLock.Release() - } - return fmt.Errorf("daemon: invalid listen address %q: %w", addr, err) - } - ip := net.ParseIP(host) - if ip == nil || !ip.IsLoopback() { - if s.singletonLock != nil { - _ = s.singletonLock.Release() - } - return fmt.Errorf("daemon: listen address host %q must be a loopback IP literal", host) - } - - ln, err := net.Listen("tcp", addr) + preferIPv6 := preferIPv6Loopback(runtime.GOOS, s.stateDir.Root(), wslruntime.IsWindowsHostPath) + ln, err := listenLoopback(s.cfg.ListenAddr, preferIPv6, net.Listen) if err != nil { if s.singletonLock != nil { _ = s.singletonLock.Release() } - return fmt.Errorf("daemon: failed to listen on %s: %w", addr, err) + return err } s.listener = ln diff --git a/internal/daemoncli/cli.go b/internal/daemoncli/cli.go index 75ece11..2e171e4 100644 --- a/internal/daemoncli/cli.go +++ b/internal/daemoncli/cli.go @@ -60,7 +60,7 @@ func runDaemon(args []string, stdout, stderr io.Writer) int { fs.SetOutput(stderr) stateDir := fs.String("state-dir", "", "state directory path") - listenAddr := fs.String("listen", "127.0.0.1:0", "HTTP listen address") + listenAddr := fs.String("listen", "", "HTTP loopback address (automatic; shared Windows state uses IPv4)") jsonOutput := fs.Bool("json", false, "emit machine-readable JSON") if err := fs.Parse(args); err != nil { @@ -225,7 +225,7 @@ func printDaemonUsage(w io.Writer) { fmt.Fprintln(w, "") fmt.Fprintln(w, "Flags:") fmt.Fprintln(w, " --state-dir Override state directory path") - fmt.Fprintln(w, " --listen Listen address (default 127.0.0.1:0)") + fmt.Fprintln(w, " --listen Exact loopback address (default: automatic; shared Windows state uses IPv4)") fmt.Fprintln(w, " --json Emit machine-readable JSON") fmt.Fprintln(w, " --help, -h Show help") fmt.Fprintln(w, " --version, -v Show version") diff --git a/internal/guest/ssh/duplex_bench_test.go b/internal/guest/ssh/duplex_bench_test.go new file mode 100644 index 0000000..d04fc67 --- /dev/null +++ b/internal/guest/ssh/duplex_bench_test.go @@ -0,0 +1,185 @@ +package ssh_test + +import ( + "bytes" + "context" + "crypto/ed25519" + "crypto/rand" + "crypto/sha256" + "encoding/base64" + "fmt" + "io" + "net" + "sync" + "testing" + "time" + + "github.com/Horcag/agent-machine-control/internal/guest/ssh" + gossh "golang.org/x/crypto/ssh" +) + +const duplexBenchmarkPayloadSize = 64 << 20 +const duplexBenchmarkChunkSize = 64 << 10 + +// BenchmarkDuplexStreaming64MiB compares binary SSH channel throughput over +// IPv4 and IPv6 loopback using the normal x/crypto/ssh algorithm preferences. +// The server echoes concurrently so neither channel window can deadlock. +func BenchmarkDuplexStreaming64MiB(b *testing.B) { + for _, tc := range []struct { + name, listenAddress string + }{ + {name: "IPv4", listenAddress: "127.0.0.1:0"}, + {name: "IPv6", listenAddress: "[::1]:0"}, + } { + b.Run(tc.name, func(b *testing.B) { + benchmarkDuplexStreaming(b, tc.listenAddress) + }) + } +} + +func benchmarkDuplexStreaming(b *testing.B, listenAddress string) { + + clientSigner := newDuplexBenchmarkSigner(b) + hostSigner := newDuplexBenchmarkSigner(b) + serverConfig := &gossh.ServerConfig{NoClientAuth: true} + serverConfig.AddHostKey(hostSigner) + listener, err := net.Listen("tcp", listenAddress) + if err != nil { + b.Fatal(err) + } + var serverWG sync.WaitGroup + negotiated := make(chan gossh.NegotiatedAlgorithms, 1) + serverWG.Go(func() { + for { + conn, acceptErr := listener.Accept() + if acceptErr != nil { + return + } + serverWG.Go(func() { serveDuplexBenchmarkConn(conn, serverConfig, negotiated) }) + } + }) + defer func() { + _ = listener.Close() + serverWG.Wait() + }() + + hostHash := sha256.Sum256(hostSigner.PublicKey().Marshal()) + provider := &ssh.MockKeyProvider{ + Signer: clientSigner, + PinnedKeySHA256: base64.StdEncoding.EncodeToString(hostHash[:]), + Endpoint: listener.Addr().String(), + User: "synthetic-benchmark-user", + } + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) + duplex, err := ssh.NewTransport(provider).OpenDuplex(ctx, "synthetic-benchmark-target", "synthetic-benchmark-worker") + if err != nil { + cancel() + b.Fatal(err) + } + stopClose := context.AfterFunc(ctx, func() { _ = duplex.Close() }) + defer func() { + stopClose() + cancel() + _ = duplex.Close() + }() + algorithms := <-negotiated + b.Logf("negotiated SSH write cipher: %s", algorithms.Write.Cipher) + + payload := make([]byte, duplexBenchmarkPayloadSize) + for i := range payload { + payload[i] = byte(i*31 + i/251) + } + writeDone := make(chan error, 1) + reader := make([]byte, duplexBenchmarkChunkSize) + b.SetBytes(int64(len(payload))) + b.ReportAllocs() + b.ResetTimer() + for range b.N { + go func() { writeDone <- writeDuplexBenchmarkPayload(duplex, payload) }() + if err = verifyDuplexBenchmarkPayload(duplex, payload, reader); err != nil { + b.Fatal(err) + } + + if err = <-writeDone; err != nil { + b.Fatal(err) + } + } + b.StopTimer() + b.ReportMetric(float64(duplexBenchmarkPayloadSize*b.N)/b.Elapsed().Seconds()/(1<<20), "MiB/s") +} + +func serveDuplexBenchmarkConn(conn net.Conn, config *gossh.ServerConfig, negotiated chan<- gossh.NegotiatedAlgorithms) { + server, channels, requests, err := gossh.NewServerConn(conn, config) + if err != nil { + _ = conn.Close() + return + } + defer server.Close() + negotiated <- server.Conn.(gossh.AlgorithmsConnMetadata).Algorithms() + go gossh.DiscardRequests(requests) + var sessionWG sync.WaitGroup + for newChannel := range channels { + channel, requests, acceptErr := newChannel.Accept() + if acceptErr != nil { + return + } + sessionWG.Go(func() { + defer channel.Close() + for request := range requests { + if request.Type == "exec" { + _ = request.Reply(true, nil) + _, _ = io.Copy(channel, channel) + return + } + _ = request.Reply(false, nil) + } + }) + } + sessionWG.Wait() +} + +func newDuplexBenchmarkSigner(b *testing.B) gossh.Signer { + b.Helper() + _, privateKey, err := ed25519.GenerateKey(rand.Reader) + if err != nil { + b.Fatal(err) + } + signer, err := gossh.NewSignerFromKey(privateKey) + if err != nil { + b.Fatal(err) + } + return signer +} + +func writeDuplexBenchmarkPayload(writer io.Writer, payload []byte) error { + for offset := 0; offset < len(payload); { + end := min(offset+duplexBenchmarkChunkSize, len(payload)) + chunk := payload[offset:end] + for len(chunk) > 0 { + n, err := writer.Write(chunk) + if err != nil { + return err + } + if n == 0 { + return io.ErrShortWrite + } + chunk = chunk[n:] + } + offset = end + } + return nil +} + +func verifyDuplexBenchmarkPayload(reader io.Reader, payload, buffer []byte) error { + for offset := 0; offset < len(payload); { + end := min(offset+len(buffer), len(payload)) + if _, err := io.ReadFull(reader, buffer[:end-offset]); err != nil { + return err + } + if !bytes.Equal(buffer[:end-offset], payload[offset:end]) { + return fmt.Errorf("echo differs at byte %d", offset) + } + offset = end + } + return nil +}