diff --git a/README.md b/README.md index b7e2679..a53dee6 100644 --- a/README.md +++ b/README.md @@ -140,7 +140,7 @@ Windows release executables and installers are currently unsigned. See the [Code > xattr -dr com.apple.quarantine ssh-keyselect > ``` > -> These commands remove the download quarantine attribute; they do not add a trusted code signature. Once Developer ID signing and notarization are enabled, you can skip them but should continue verifying downloads. See the [Code signing policy](#code-signing-policy) for the current status. +> These commands remove the download quarantine attribute. They do not add a trusted code signature. Once Developer ID signing and notarization are enabled, you can skip them but should continue verifying downloads. See the [Code signing policy](#code-signing-policy) for the current status. ### Linux @@ -209,7 +209,7 @@ apk add --allow-untrusted "./$apk_file" Start the GUI first, then set `SSH_AUTH_SOCK` to the Listen endpoint shown in its main window. On macOS and Linux, the default endpoint is `$HOME/.ssh/ssh-keyselect-agent.sock`. -`Upstream` is the endpoint for your existing SSH agent; `Listen` is where SSH clients connect to KeySelect. The cards show these paths, and their `Copy export command` buttons copy POSIX `export` assignments with shell-quoted paths. +`Upstream` is the endpoint for your existing SSH agent. `Listen` is where SSH clients connect to KeySelect. The cards show these paths, and their `Copy export command` buttons copy POSIX `export` assignments with shell-quoted paths. The GUI can start without an upstream agent. Configure its endpoints in Settings. @@ -225,7 +225,7 @@ ssh user@example.org #### VS Code on Windows -Configure VS Code's [terminal profile](https://code.visualstudio.com/docs/terminal/profiles) to use Git Bash. The `bash.exe` path below is for the Scoop `git-with-openssh` package; replace it with the path to your Git Bash executable if you installed Git Bash another way. Start the GUI with Listen mode set to `cygwin` and a Listen endpoint that matches `SSH_AUTH_SOCK` below. See the [Git Bash configuration example](#configuration) for setting the endpoint. Open User Settings (JSON) and add the following properties inside the existing top-level object. Keep your other settings. If any of these keys already exist, update them instead of adding duplicates; merge the `Git Bash` profile and `SSH_AUTH_SOCK` into the existing profile and environment objects. Replace `USERNAME` with your Windows account name: +Configure VS Code's [terminal profile](https://code.visualstudio.com/docs/terminal/profiles) to use Git Bash. The `bash.exe` path below is for the Scoop `git-with-openssh` package. Replace it with the path to your Git Bash executable if you installed Git Bash another way. Start the GUI with Listen mode set to `cygwin` and a Listen endpoint that matches `SSH_AUTH_SOCK` below. See the [Git Bash configuration example](#configuration) for setting the endpoint. Open User Settings (JSON) and add the following properties inside the existing top-level object. Keep your other settings. If any of these keys already exist, update them instead of adding duplicates. Merge the `Git Bash` profile and `SSH_AUTH_SOCK` into the existing profile and environment objects. Replace `USERNAME` with your Windows account name: ```json "terminal.integrated.profiles.windows": { @@ -305,7 +305,7 @@ Long comments in CLI tables are shortened with an ellipsis for display. The orig ### Options and environment -The wrapper options go before `--`; arguments after it are passed to OpenSSH. +The wrapper options go before `--`. Arguments after it are passed to OpenSSH. - `ssh-keyselect ssh`: `--upstream`, `--upstream-mode`, `--listen`, `--listen-mode`, `--selection-timeout`, `--allow-unbound-signing-on-bind-failure`, `--log-level`, `--log-file` - `ssh-keyselect list` and `ssh-keyselect test`: `--upstream`, `--upstream-mode` @@ -324,7 +324,7 @@ For an SSH session, pass `--log-file FILE` to write KeySelect diagnostic logs to ssh-keyselect ssh --log-level debug --log-file ~/ssh-keyselect.log -- user@example.org ``` -The log file is replaced on each run and uses mode `0600` on Unix-like systems. OpenSSH output remains in the terminal. Review logs before sharing them; they can include SSH host key fingerprints and request metadata. +The log file is replaced on each run and uses mode `0600` on Unix-like systems. OpenSSH output remains in the terminal. Review logs before sharing them. They can include SSH host key fingerprints and request metadata. ### Terminal picker @@ -363,19 +363,19 @@ If `XDG_CONFIG_HOME` is set, it must be an absolute path and the GUI reads TOML | Linux | `~/.config/ssh-keyselect/config.toml` | | macOS | `~/Library/Application Support/ssh-keyselect/config.toml` | -On Windows and Linux, use `--config FILE` to select another file; command-line values override file values. On macOS, open or save configuration files through the GUI's File menu. The following environment variables also affect endpoint paths: +On Windows and Linux, use `--config FILE` to select another file. Command-line values override file values. On macOS, open or save configuration files through the GUI's File menu. The following environment variables also affect endpoint paths: - `SSH_KEYSELECT_LISTEN` overrides `agent.listen`. - When `agent.upstream` is empty, `UPSTREAM_SSH_AUTH_SOCK` takes precedence over `SSH_AUTH_SOCK`. If neither is set, the GUI uses the native OpenSSH agent endpoint: `\\.\pipe\openssh-ssh-agent` on Windows and `~/.ssh/ssh-agent.sock` on macOS and Linux. - To keep the upstream endpoint tied to a changing environment variable, set `agent.upstream = "env:SSH_AUTH_SOCK"`, or choose Environment variable in GUI Settings and enter its name. The GUI resolves this reference at startup and when Settings are applied, while saving the `env:NAME` reference in the config file. The variable must be set and non-empty. - Environment variables in ordinary paths and a leading `~` are expanded using the GUI process environment. -- `[history].path` selects the selection-history database when set. If omitted or empty, the GUI uses `history.sqlite` in the application data folder; relative paths are resolved from that folder. GUI Settings leaves the field blank and shows the resolved default path as its placeholder. It saves `history.path` only when you enter or choose a path. +- `[history].path` selects the selection-history database when set. If omitted or empty, the GUI uses `history.sqlite` in the application data folder. Relative paths are resolved from that folder. GUI Settings leaves the field blank and shows the resolved default path as its placeholder. It saves `history.path` only when you enter or choose a path. - `[history].enabled` controls whether the GUI records and shows selection history. `[history].remember_selection` controls whether it remembers the last selected key for each verified target host. Both default to `true`, can be changed in GUI Settings, and are written to the config only when set to `false`. When both are `false`, the GUI does not create or open the SQLite database. - If the configured Listen endpoint is active or blocked by a non-socket file, the GUI starts with the proxy `Not configured`. A stale socket owned by the current user is replaced when KeySelect confirms that it is no longer listening. The configuration loader rejects unknown keys. Logging is off by default. Set `log.level` to enable it and optionally set `log.file` to append logs to a file. When `log.file` is empty, logs go to standard error. -The key selection timeout defaults to 120 seconds. In GUI Settings, set `agent.selection_timeout`; for `ssh-keyselect ssh`, pass `--selection-timeout SECONDS`. +The key selection timeout defaults to 120 seconds. In GUI Settings, set `agent.selection_timeout`. For `ssh-keyselect ssh`, pass `--selection-timeout SECONDS`. If, after a timeout, the SSH client prints the errors below and the server's `/var/log/secure` contains `penalty: exceeded LoginGraceTime`, set the Key selection Timeout to match that server's `LoginGraceTime` value in seconds. @@ -433,7 +433,7 @@ When `history.remember_selection` is enabled and the request includes a verified When `history.enabled` is enabled and the request includes a verified target host key, the picker displays a `First selection` badge if no earlier selection matches the same Target Host and Forwarded path. It applies to the request context, not an individual key, and does not indicate whether a prior key authenticated successfully. The badge is omitted when the target host or forwarded path cannot be verified, or history cannot be read. -When `history.enabled` is enabled, choose `File > History…` or press Ctrl+Shift+H (Cmd+Shift+H on macOS) to review request time, target host and forwarded hops, selected key, selection time, and whether the picker completed, was canceled, or timed out. Right-click a row to copy its displayed information or delete it. Use `Export CSV` to save the full history and host paths. The result describes the picker interaction; it does not indicate whether the SSH server accepted authentication. +When `history.enabled` is enabled, choose `File > History…` or press Ctrl+Shift+H (Cmd+Shift+H on macOS) to review request time, target host and forwarded hops, selected key, selection time, and whether the picker completed, was canceled, or timed out. Right-click a row to copy its displayed information or delete it. Use `Export CSV` to save the full history and host paths. The result describes the picker interaction. It does not indicate whether the SSH server accepted authentication. Right-click a key row and choose `Copy`, or press Ctrl+C, to copy its Comment, Type, Size, and Fingerprint as tab-separated text. @@ -486,10 +486,10 @@ The agent protocol does not provide a hostname. Names matched from the default l 1. Quit the GUI and finish SSH sessions started through the CLI wrapper. 2. Restore shell and Git changes: - - Restore the previous `SSH_AUTH_SOCK` value or remove the setting from shell startup files and VS Code User Settings (JSON). If you changed VS Code's default profile for this setup, restore its previous value; remove the Git Bash profile if you added it only for KeySelect and no longer need it. + - Restore the previous `SSH_AUTH_SOCK` value or remove the setting from shell startup files and VS Code User Settings (JSON). If you changed VS Code's default profile for this setup, restore its previous value. Remove the Git Bash profile if you added it only for KeySelect and no longer need it. - Restore earlier `ssh`, `GIT_SSH_COMMAND`, and `core.sshCommand` values. If you added only this README's examples, run `unalias ssh` and, in each affected repository, `git config --local --unset core.sshCommand`. 3. Remove KeySelect wrappers, `PATH` entries, shortcuts, and program files. For archive installs, delete the distribution directory with its `LICENSE` and `CREDITS` files, plus any copied `SSH KeySelect.app`. For package installs, remove the package with the package manager you used to install it. -4. Optionally delete the GUI configuration files (see [Configuration](#configuration)), including files saved with Save As or `--config`, and diagnostic logs created with `--log-file`. Keep your upstream agent and SSH keys; they belong to your SSH setup. +4. Optionally delete the GUI configuration files (see [Configuration](#configuration)), including files saved with Save As or `--config`, and diagnostic logs created with `--log-file`. Keep your upstream agent and SSH keys. They belong to your SSH setup. For RHEL-compatible Linux distributions: diff --git a/cmd/ssh-keyselect-gui/gui_history.go b/cmd/ssh-keyselect-gui/gui_history.go index 9fda63f..0d6e974 100644 --- a/cmd/ssh-keyselect-gui/gui_history.go +++ b/cmd/ssh-keyselect-gui/gui_history.go @@ -60,8 +60,11 @@ type guiHistoryState struct { total int events []selectionhistory.Event allEvents []selectionhistory.Event - sortedAllEvents []selectionhistory.Event + sortedAllIndices []int sortedAllOrder ui.SortOrder + allEventsPage []selectionhistory.Event + allEventsPageNo int + allEventsPageSet bool allEventsLoaded bool allEventsLoadFail bool observedSort ui.SortOrder @@ -175,7 +178,9 @@ func (a *guiApp) syncHistoryView() { func (s *guiHistoryState) clearAllEvents() { s.allEvents = nil - s.sortedAllEvents = nil + s.sortedAllIndices = nil + s.allEventsPage = nil + s.allEventsPageSet = false s.allEventsLoaded = false s.allEventsLoadFail = false } @@ -286,7 +291,9 @@ func (s *guiHistoryState) loadAllEvents() { return } s.allEvents = events - s.sortedAllEvents = nil + s.sortedAllIndices = nil + s.allEventsPage = nil + s.allEventsPageSet = false s.allEventsLoaded = true s.allEventsLoadFail = false s.events = nil @@ -426,17 +433,46 @@ func (s *guiHistoryState) pageEvents() []selectionhistory.Event { s.loadError = "" } if s.allEventsLoaded { - if s.sortedAllEvents == nil || s.sortedAllOrder != s.sort { - s.sortedAllEvents = sortHistoryEvents(s.allEvents, s.sort) + if s.sortedAllIndices == nil || s.sortedAllOrder != s.sort { + s.sortedAllIndices = sortHistoryEventIndices(s.allEvents, s.sort) s.sortedAllOrder = s.sort + s.allEventsPageSet = false } - start := min(s.page*selectionHistoryPageSize, len(s.sortedAllEvents)) - end := min(start+selectionHistoryPageSize, len(s.sortedAllEvents)) - return s.sortedAllEvents[start:end] + if s.allEventsPageSet && s.allEventsPageNo == s.page { + return s.allEventsPage + } + start := min(s.page*selectionHistoryPageSize, len(s.sortedAllIndices)) + end := min(start+selectionHistoryPageSize, len(s.sortedAllIndices)) + s.allEventsPage = make([]selectionhistory.Event, end-start) + for index, eventIndex := range s.sortedAllIndices[start:end] { + s.allEventsPage[index] = s.allEvents[eventIndex] + } + s.allEventsPageNo = s.page + s.allEventsPageSet = true + return s.allEventsPage } return sortHistoryEvents(s.events, s.sort) } +// sortHistoryEventIndices keeps the complete-history sort index smaller than a duplicate event slice. +func sortHistoryEventIndices(events []selectionhistory.Event, order ui.SortOrder) []int { + indices := make([]int, len(events)) + for index := range indices { + indices[index] = index + } + if order.Column == "" { + return indices + } + sort.SliceStable(indices, func(i, j int) bool { + comparison := compareHistoryEvents(events[indices[i]], events[indices[j]], order.Column) + if order.Descending { + return comparison > 0 + } + return comparison < 0 + }) + return indices +} + func sortHistoryEvents(source []selectionhistory.Event, order ui.SortOrder) []selectionhistory.Event { events := append([]selectionhistory.Event(nil), source...) if order.Column == "" { @@ -734,7 +770,7 @@ func writeGUIHistoryCSV(path string, store *selectionhistory.Store) error { return fmt.Errorf("create CSV temporary file: %w", err) } temporaryPath := temporary.Name() - defer os.Remove(temporaryPath) + defer func() { _ = os.Remove(temporaryPath) }() if err := temporary.Chmod(0o600); err != nil { _ = temporary.Close() return fmt.Errorf("set CSV file permissions: %w", err) diff --git a/cmd/ssh-keyselect-gui/gui_runtime.go b/cmd/ssh-keyselect-gui/gui_runtime.go index bfb8d40..4d730d0 100644 --- a/cmd/ssh-keyselect-gui/gui_runtime.go +++ b/cmd/ssh-keyselect-gui/gui_runtime.go @@ -95,7 +95,7 @@ func (a *guiEndpointAgent) OpenSession(ctx context.Context) (upstream.AgentSessi type guiListenerState struct { cleanup func() cancel context.CancelFunc - done chan error + done chan struct{} active atomic.Bool } @@ -232,14 +232,14 @@ func (r *guiRuntime) Apply(cfg config.Config) (string, transport.Mode, error) { func (r *guiRuntime) startListener(ln net.Listener, cleanup func()) { serveCtx, cancel := context.WithCancel(r.ctx) - state := &guiListenerState{cleanup: cleanup, cancel: cancel, done: make(chan error, 1)} + state := &guiListenerState{cleanup: cleanup, cancel: cancel, done: make(chan struct{})} state.active.Store(true) r.listenerState = state logger := r.server.Logger go func() { err := r.server.Serve(serveCtx, ln) state.active.Store(false) - state.done <- err + close(state.done) if err != nil && serveCtx.Err() == nil { logger.Error("SSH agent proxy stopped", "error", err) if r.onServeError != nil { diff --git a/cmd/ssh-keyselect-gui/version_nogui.go b/cmd/ssh-keyselect-gui/version_nogui.go deleted file mode 100644 index d7bcc17..0000000 --- a/cmd/ssh-keyselect-gui/version_nogui.go +++ /dev/null @@ -1,9 +0,0 @@ -//go:build !gui - -// SPDX-License-Identifier: Apache-2.0 -// SPDX-FileCopyrightText: Copyright contributors to the ssh-keyselect project. - -package main - -// Non-GUI builds use GoReleaser's version linker flag and do not have MyGo metadata. -func resolvePackagedVersion() {} diff --git a/docs/dev.md b/docs/dev.md index 7649979..c4e0cd6 100644 --- a/docs/dev.md +++ b/docs/dev.md @@ -125,7 +125,7 @@ When event recording is enabled, the GUI picker reads selected outcomes for the `internal/selectionhistory` stores GUI selection events, verified host hops, and the last selected key for each verified target host in `history.sqlite` under the per-user application-data directory by default. `[history].path` selects another file when set; it is omitted from saved configuration when empty, and relative paths resolve from the application-data directory. GUI Settings leaves the field empty and shows the resolved default path as its placeholder. `[history].enabled` and `[history].remember_selection` both default to true, are saved only when false, and are independent: the first controls event recording and the History window, while the second controls per-host preference reads and writes. The application opens the database only when at least one switch is enabled; when both are disabled, startup and configuration apply skip database path resolution and SQLite open/create. If both features are enabled, the event and preference update share one transaction. History-only recording does not update preferences; preference-only recording does not create events. Preferences use the final non-forwarding host-key fingerprint and selected public-key fingerprint; they only set the picker's initial row. Requests without a verified target host key do not read or update a preference. -When history is enabled, the proxy captures `requested_at` when it receives `RequestIdentities`, before listing upstream identities. The GUI records when the picker opens, when the user selects or cancels, and the outcome. Host hops preserve binding order, forwarding flags, fingerprints, and `known_hosts` display hints. The compact history table pages 50 rows ordered by request time, shows target host names separately from the host key, and shows selected-key comment, public-key data, and fingerprint in separate columns. It copies its displayed row fields and deletes events with their host-hop rows. Forwarding paths use ` -> ` between hops and comma-separated known-host hints followed by the key in brackets. CSV export starts with the table's columns in display order, then adds event and connection metadata, the complete host path as JSON, and the selected key algorithm and blob in Base64. When key remembrance is enabled, deleting the latest event for a host restores the prior surviving key preference. The result is the picker outcome, not SSH authentication acceptance, which the agent protocol does not expose. +When history is enabled, the proxy captures `requested_at` when it receives `RequestIdentities`, before listing upstream identities. The GUI records when the picker opens, when the user selects or cancels, and the outcome. Host hops preserve binding order, forwarding flags, fingerprints, and `known_hosts` display hints. The compact history table pages 50 rows ordered by request time, shows target host names separately from the host key, and shows selected-key comment, public-key data, and fingerprint in separate columns. It copies its displayed row fields and deletes events with their host-hop rows. Forwarding paths use ` -> ` between hops and comma-separated known-host hints followed by the key in brackets. CSV export starts with the table's columns in display order, then adds event and connection metadata, the complete host path as JSON, and the selected key algorithm and blob in Base64. When key remembrance is enabled, deleting the latest event for a host restores the prior surviving key preference. The result is the picker outcome, not SSH authentication acceptance, which the agent protocol does not expose. A full-table sort reads one consistent snapshot, skips a redundant count query, and stores row indices instead of duplicating all event structs; it only materializes the visible page for the GUI. The database starts at schema version 1, defined in `internal/selectionhistory/store.go`. It uses WAL mode, a 5-second busy timeout, and foreign keys. The database file is mode `0600`; missing parent directories are created with mode `0700`. Event timestamps are stored as UTC Unix nanoseconds and formatted in local time in the GUI and CSV; CSV timestamps use RFC 3339 with the local UTC offset. CSV key comments are sanitized and spreadsheet formula prefixes are neutralized. The ncruces SQLite driver embeds its SQLite WebAssembly module and keeps the database compatible with the repository's `CGO_ENABLED=0` builds without downloading a native library at runtime. Run `just deps-credits` after this dependency change. @@ -181,7 +181,7 @@ Signing requests from separate client connections run concurrently through indep #### Frames and request queue -Once a client starts sending an agent frame, it must finish within 10 seconds or the connection is closed. The read deadline starts after the first frame byte, is not extended by partial reads, and is cleared after a complete frame. It does not limit idle connections or time spent choosing a key. +Once a client starts sending an agent frame, it must finish within 10 seconds or the connection is closed. The read deadline starts after the first frame byte, is not extended by partial reads, and is cleared after a complete frame. Frontend responses also have a 10-second write deadline, so a client that stops reading cannot retain a connection slot indefinitely. These deadlines do not limit idle connections or time spent choosing a key. Clients should wait for each response before sending another request. The frame reader runs separately so a disconnect or an incomplete-frame timeout can cancel an open picker. It queues at most one complete request and closes the client if another arrives while the queue is full, so delivery to the handler never blocks client monitoring. @@ -189,12 +189,14 @@ Every reader exit cancels the connection context and closes the frontend socket #### Per-connection state -Each frontend connection accepts at most 16 session-binding requests and retains no more than 1 MiB of verified binding messages for its current chain. Starting a new forwarding chain clears the previous chain. The display-only `known_hosts` lookup reads at most 1 MiB from each file and stops scanning a file if a line exceeds 64 KiB. +Each frontend connection accepts at most 16 session-binding requests and retains no more than 1 MiB of verified binding messages for its current chain. Starting a new forwarding chain clears the previous chain. The display-only `known_hosts` lookup runs only when the picker opens, reads at most 1 MiB from each file, stops scanning a file if a line exceeds 64 KiB, and resolves each binding at most once. #### Cleanup and runtime directories Unix listener cleanup unlinks only the socket it created, after checking filesystem identity. Automatic unlinking on listener close is disabled so a replacement at the same path remains untouched. +On Linux, the listener applies mode `0600` through the socket descriptor before binding. macOS rejects `fchmod` on an unbound socket, so the listener checks that the bound path is a socket owned by the current user, applies the mode through the path, and verifies that its filesystem identity is unchanged. It records that identity for guarded cleanup. + Before replacing a stale Unix socket, the listener treats only `ECONNREFUSED` and `ENOENT` from the connection probe as stale, checks that the socket belongs to the effective user, and rechecks its filesystem identity before removal. Active sockets, non-socket entries, sockets owned by another user, and paths with an inconclusive probe are left untouched. Bind and permission failures also remove the path only when it still names the socket created by that listener. Unix TUI endpoints use `XDG_RUNTIME_DIR/ssh-keyselect` when configured, or `os.TempDir()/ssh-keyselect-` otherwise. The XDG directory and the private directory must belong to the effective UID. The private directory is opened without following a symlink; ownership is checked before permissions are set to `0700` through the directory descriptor. This separates users in a shared temporary directory and avoids changing another user's directory permissions. @@ -205,7 +207,7 @@ Unix TUI endpoints use `XDG_RUNTIME_DIR/ssh-keyselect` when configured, or `os.T The `cygwin` transport reads the socket file's endpoint information and connects through loopback TCP using the file's GUID handshake. The `wsl1` transport uses Windows AF_UNIX sockets with paths translated from `/mnt//...`. The `named-pipe` mode uses Windows OpenSSH named pipes. Native Windows and shell-specific defaults are implemented in platform-suffixed files under `internal/listener`, `internal/upstream`, `internal/winpath`, and `cmd/ssh-keyselect-gui`. -Cygwin socket metadata reads are capped at 256 bytes. The listener accepts each connection immediately; its handshake then runs in the proxy's per-connection handler, after admission and before normal client logging or agent request handling. Connection reads and writes enforce authentication before passing agent traffic. +Cygwin socket metadata reads are capped at 256 bytes. Its metadata file is created with a protected ACL for LocalSystem and the file owner before the handshake GUID is written. The listener accepts each connection immediately; its handshake then runs in the proxy's per-connection handler, after admission and before normal client logging or agent request handling. The GUID comparison is constant-time, and connection reads and writes enforce authentication before passing agent traffic. The Cygwin listener removes its metadata file on setup failure or shutdown only while the path still identifies the file it created. diff --git a/internal/agentproxy/server.go b/internal/agentproxy/server.go index c2b9b8b..a153f8c 100644 --- a/internal/agentproxy/server.go +++ b/internal/agentproxy/server.go @@ -28,6 +28,7 @@ const ( // Bound frontend resources even when forwarded clients leave connections open. maxClientConnections = 128 clientFrameReadTimeout = 10 * time.Second + clientFrameWriteTimeout = 10 * time.Second defaultSelectionTimeout = 120 * time.Second ) @@ -248,16 +249,11 @@ func (s *Server) handleConnection(parent context.Context, conn net.Conn, session } var chosen []identity.Identity if err == nil { - selectionCtx, cancelSelection := s.newSelectionContext(ctx) - requestContext := selectionContext(sessionBinds) - requestContext.ConnectionID = sessionID - requestContext.RequestedAt = requestedAt - chosen, err = s.selectAvailableIdentities(selectionCtx, log, requestContext, available) - if errors.Is(selectionCtx.Err(), context.DeadlineExceeded) && ctx.Err() == nil { + requestContext := selector.SelectionContext{ConnectionID: sessionID, RequestedAt: requestedAt} + chosen, err = s.selectAvailableIdentities(ctx, log, requestContext, available, sessionBinds) + if errors.Is(err, errSelectionTimeout) && ctx.Err() == nil { log.Warn("identity selection timed out", "timeout", s.selectionTimeoutDuration()) - err = errSelectionTimeout } - cancelSelection() } if errors.Is(err, errSelectionTimeout) { // Let SSH continue as if no keys were selected, then release this timed-out client. @@ -335,8 +331,6 @@ func (s *Server) handleConnection(parent context.Context, conn net.Conn, session if upstreamSessionBindingRejected { if upstreamSessionBindingFallback { if len(binding.raw) <= maxSessionBindingBytes-sessionBindingBytes { - binding.display.KnownHosts = sessionKnownHostNames(binding.hostKey) - binding.hostKey = nil sessionBinds = append(sessionBinds, binding) sessionBindingBytes += len(binding.raw) } else { @@ -362,8 +356,6 @@ func (s *Server) handleConnection(parent context.Context, conn net.Conn, session upstreamSessionBindingFallback = true upstreamSessionBinds = nil if len(binding.raw) <= maxSessionBindingBytes-sessionBindingBytes { - binding.display.KnownHosts = sessionKnownHostNames(binding.hostKey) - binding.hostKey = nil sessionBinds = append(sessionBinds, binding) sessionBindingBytes += len(binding.raw) } @@ -376,8 +368,6 @@ func (s *Server) handleConnection(parent context.Context, conn net.Conn, session } continue } - binding.display.KnownHosts = sessionKnownHostNames(binding.hostKey) - binding.hostKey = nil upstreamSessionBinds = append(upstreamSessionBinds, binding.raw) sessionBinds = append(sessionBinds, binding) sessionBindingBytes += len(binding.raw) @@ -460,7 +450,7 @@ func readClientFrame(conn net.Conn, timeout time.Duration) ([]byte, error) { return message, nil } -func (s *Server) selectAvailableIdentities(ctx context.Context, logger *slog.Logger, requestContext selector.SelectionContext, identities []identity.Identity) ([]identity.Identity, error) { +func (s *Server) selectAvailableIdentities(ctx context.Context, logger *slog.Logger, requestContext selector.SelectionContext, identities []identity.Identity, bindings []verifiedSessionBind) ([]identity.Identity, error) { logger.Info("identities requested", "upstream_count", len(identities)) if len(identities) == 0 { return nil, nil @@ -469,8 +459,11 @@ func (s *Server) selectAvailableIdentities(ctx context.Context, logger *slog.Log logger.Info("auto select enabled; exposing all upstream identities", "identity_count", len(identities)) return identities, nil } - chosen, err := s.Selector.Select(ctx, identities, requestContext) - if errors.Is(ctx.Err(), context.DeadlineExceeded) { + requestContext.HostBindings = selectionContext(bindings).HostBindings + selectionCtx, cancelSelection := s.newSelectionContext(ctx) + defer cancelSelection() + chosen, err := s.Selector.Select(selectionCtx, identities, requestContext) + if errors.Is(selectionCtx.Err(), context.DeadlineExceeded) { return nil, errSelectionTimeout } if err != nil { @@ -480,8 +473,8 @@ func (s *Server) selectAvailableIdentities(ctx context.Context, logger *slog.Log } return nil, err } - if ctx.Err() != nil { - return nil, ctx.Err() + if selectionCtx.Err() != nil { + return nil, selectionCtx.Err() } if err := validateSelection(identities, chosen); err != nil { return nil, err @@ -496,7 +489,9 @@ func (s *Server) newSelectionContext(parent context.Context) (context.Context, c func selectionContext(bindings []verifiedSessionBind) selector.SelectionContext { requestContext := selector.SelectionContext{HostBindings: make([]selector.HostBinding, len(bindings))} - for i, binding := range bindings { + for i := range bindings { + binding := &bindings[i] + binding.resolveKnownHosts() requestContext.HostBindings[i] = binding.display requestContext.HostBindings[i].KnownHosts = append([]string(nil), binding.display.KnownHosts...) } @@ -610,7 +605,12 @@ func validSignResponse(message []byte) bool { func writeFailure(conn net.Conn) bool { return writeResponse(conn, []byte{protocol.Failure}) } func writeResponse(conn net.Conn, response []byte) bool { - return protocol.WriteFrame(conn, response) == nil + if err := conn.SetWriteDeadline(time.Now().Add(clientFrameWriteTimeout)); err != nil { + return false + } + writeErr := protocol.WriteFrame(conn, response) + clearErr := conn.SetWriteDeadline(time.Time{}) + return writeErr == nil && clearErr == nil } // newSessionID returns a process-unique log correlation ID, not an authentication token. diff --git a/internal/agentproxy/session_bind.go b/internal/agentproxy/session_bind.go index 69b3566..d7f1c9c 100644 --- a/internal/agentproxy/session_bind.go +++ b/internal/agentproxy/session_bind.go @@ -30,8 +30,9 @@ type verifiedSessionBind struct { sessionID []byte raw []byte display selector.HostBinding - // hostKey is kept only until the optional known_hosts display hint is resolved. - hostKey ssh.PublicKey + // hostKeyBlob aliases raw so parsed key data need not stay live before a picker opens. + hostKeyBlob []byte + knownHostsResolved bool } // verifySessionBind accepts only host keys that verify their session identifier signature. @@ -61,9 +62,9 @@ func verifySessionBind(message []byte) (verifiedSessionBind, error) { return verifiedSessionBind{}, errors.New("session-bind host key signature did not verify") } return verifiedSessionBind{ - sessionID: request.SessionID, - raw: message, - hostKey: hostKey, + sessionID: request.SessionID, + raw: message, + hostKeyBlob: request.HostKey, display: selector.HostBinding{ Algorithm: hostKey.Type(), Fingerprint: ssh.FingerprintSHA256(hostKey), @@ -72,6 +73,18 @@ func verifySessionBind(message []byte) (verifiedSessionBind, error) { }, nil } +// resolveKnownHosts loads optional display hints only when the picker needs host context. +func (binding *verifiedSessionBind) resolveKnownHosts() { + if binding.knownHostsResolved { + return + } + if hostKey, err := ssh.ParsePublicKey(binding.hostKeyBlob); err == nil { + binding.display.KnownHosts = sessionKnownHostNames(hostKey) + } + binding.hostKeyBlob = nil + binding.knownHostsResolved = true +} + // sessionKnownHostNames returns exact default known_hosts entries for this host key as display hints. func sessionKnownHostNames(hostKey ssh.PublicKey) []string { home, err := os.UserHomeDir() diff --git a/internal/listener/unix.go b/internal/listener/unix.go index 57fabcb..d4c1073 100644 --- a/internal/listener/unix.go +++ b/internal/listener/unix.go @@ -7,11 +7,13 @@ package listener import ( + "context" "errors" "fmt" "net" "os" "path/filepath" + "runtime" "sync" "syscall" "time" @@ -64,12 +66,30 @@ func ListenWithMode(path string, requested transport.Mode) (net.Listener, func() return nil, nil, fmt.Errorf("inspect listen socket: %w", err) } - ln, err := net.Listen("unix", path) + listenConfig := net.ListenConfig{Control: func(_, _ string, raw syscall.RawConn) error { + // Linux carries the descriptor mode onto the bound socket. macOS rejects + // fchmod on an unbound socket, so it applies the mode to the owned path below. + if runtime.GOOS != "linux" { + return nil + } + var chmodErr error + if err := raw.Control(func(fd uintptr) { + chmodErr = syscall.Fchmod(int(fd), 0600) + }); err != nil { + return err + } + if chmodErr != nil { + return fmt.Errorf("set Unix socket permissions: %w", chmodErr) + } + return nil + }} + ln, err := listenConfig.Listen(context.Background(), "unix", path) if err != nil { return nil, nil, fmt.Errorf("listen on Unix socket: %w", err) } // Cleanup checks ownership before unlinking; net.UnixListener's automatic unlink would bypass that check. - ln.(*net.UnixListener).SetUnlinkOnClose(false) + unixListener := ln.(*net.UnixListener) + unixListener.SetUnlinkOnClose(false) created, err := os.Lstat(path) if err != nil { _ = ln.Close() @@ -77,7 +97,11 @@ func ListenWithMode(path string, requested transport.Mode) (net.Listener, func() } if created.Mode()&os.ModeSocket == 0 { _ = ln.Close() - return nil, nil, fmt.Errorf("listen path was replaced during socket creation: %s", path) + return nil, nil, fmt.Errorf("created Unix socket has unexpected type: %s", path) + } + if err := checkSocketOwner(created, path); err != nil { + _ = ln.Close() + return nil, nil, fmt.Errorf("listen path was replaced during socket creation: %w", err) } removeCreatedSocket := func() { current, err := os.Lstat(path) @@ -85,10 +109,27 @@ func ListenWithMode(path string, requested transport.Mode) (net.Listener, func() _ = os.Remove(path) } } - if err := os.Chmod(path, 0600); err != nil { + if runtime.GOOS != "linux" { + if err := os.Chmod(path, 0600); err != nil { + removeCreatedSocket() + _ = ln.Close() + return nil, nil, fmt.Errorf("set Unix socket permissions: %w", err) + } + current, err := os.Lstat(path) + if err != nil || !os.SameFile(created, current) { + removeCreatedSocket() + _ = ln.Close() + if err != nil { + return nil, nil, fmt.Errorf("inspect created Unix socket: %w", err) + } + return nil, nil, fmt.Errorf("listen path changed while setting socket permissions: %s", path) + } + created = current + } + if created.Mode().Perm() != 0600 { removeCreatedSocket() _ = ln.Close() - return nil, nil, fmt.Errorf("set Unix socket permissions: %w", err) + return nil, nil, fmt.Errorf("created Unix socket has unexpected permissions: %s", path) } current, err := os.Lstat(path) if err != nil || !os.SameFile(created, current) { diff --git a/internal/selectionhistory/store.go b/internal/selectionhistory/store.go index 6cbecca..a8cb094 100644 --- a/internal/selectionhistory/store.go +++ b/internal/selectionhistory/store.go @@ -304,13 +304,13 @@ func (s *Store) HasSelectionContext(ctx context.Context, targetHostFingerprint s FROM selection_events AS e LEFT JOIN selection_host_hops AS h ON h.event_id = e.id WHERE e.target_host_fingerprint = ? AND e.outcome = ? AND e.selected_key_fingerprint != '' - ORDER BY e.id DESC, h.ordinal`, + ORDER BY e.requested_at_ns DESC, e.id DESC, h.ordinal`, targetHostFingerprint, string(OutcomeSelected), ) if err != nil { return false, fmt.Errorf("read selection context from history: %w", err) } - defer rows.Close() + defer func() { _ = rows.Close() }() forwardingPathMatches := func(path []string) bool { if len(path) != len(forwardedFingerprints) { return false @@ -429,7 +429,7 @@ func (s *Store) record(ctx context.Context, event Event, rememberSelection bool) if err != nil { return fmt.Errorf("begin selection history write: %w", err) } - defer tx.Rollback() + defer func() { _ = tx.Rollback() }() var dialogOpenedAt, selectedAt any if !event.DialogOpenedAt.IsZero() { dialogOpenedAt = event.DialogOpenedAt.UTC().UnixNano() @@ -537,7 +537,7 @@ func (s *Store) Delete(ctx context.Context, eventID int64) error { if err != nil { return fmt.Errorf("begin selection history delete: %w", err) } - defer tx.Rollback() + defer func() { _ = tx.Rollback() }() var targetHost, selectedKey string var selectedAt sql.NullInt64 @@ -635,10 +635,12 @@ func (s *Store) listEvents(ctx context.Context, page, pageSize int, all bool) ([ if err != nil { return nil, 0, fmt.Errorf("begin selection history read: %w", err) } - defer tx.Rollback() + defer func() { _ = tx.Rollback() }() var total int - if err := tx.QueryRowContext(ctx, `SELECT count(*) FROM selection_events`).Scan(&total); err != nil { - return nil, 0, fmt.Errorf("count selection history events: %w", err) + if !all { + if err := tx.QueryRowContext(ctx, `SELECT count(*) FROM selection_events`).Scan(&total); err != nil { + return nil, 0, fmt.Errorf("count selection history events: %w", err) + } } query := ` WITH page_events AS ( @@ -717,6 +719,9 @@ func (s *Store) listEvents(ctx context.Context, page, pageSize int, all bool) ([ if err := tx.Commit(); err != nil { return nil, 0, fmt.Errorf("finish selection history read: %w", err) } + if all { + return events, len(events), nil + } return events, total, nil } @@ -734,7 +739,7 @@ func (s *Store) ExportCSV(ctx context.Context, destination io.Writer) error { if err != nil { return fmt.Errorf("begin selection history export: %w", err) } - defer tx.Rollback() + defer func() { _ = tx.Rollback() }() rows, err := tx.QueryContext(ctx, ` SELECT e.id, e.connection_id, e.requested_at_ns, e.dialog_opened_at_ns, e.resolved_at_ns, e.selected_at_ns, e.outcome, e.target_host_fingerprint, e.selected_key_fingerprint, diff --git a/internal/winsocket/cygwin.go b/internal/winsocket/cygwin.go index 96df8b1..eee9cfd 100644 --- a/internal/winsocket/cygwin.go +++ b/internal/winsocket/cygwin.go @@ -5,6 +5,7 @@ package winsocket import ( + "crypto/subtle" "encoding/binary" "fmt" "io" @@ -163,7 +164,7 @@ func cygwinServerHandshake(conn net.Conn, guid [16]byte) error { if _, err := io.ReadFull(conn, challenge[:]); err != nil { return fmt.Errorf("read Cygwin socket handshake: %w", err) } - if challenge != guid { + if subtle.ConstantTimeCompare(challenge[:], guid[:]) != 1 { return fmt.Errorf("cygwin socket handshake GUID did not match") } if err := writeAll(conn, guid[:]); err != nil { diff --git a/internal/winsocket/socketfile_windows.go b/internal/winsocket/socketfile_windows.go index 7385e08..fcc8c9d 100644 --- a/internal/winsocket/socketfile_windows.go +++ b/internal/winsocket/socketfile_windows.go @@ -20,6 +20,7 @@ import ( "strconv" "strings" "time" + "unsafe" "golang.org/x/sys/windows" @@ -145,7 +146,7 @@ func Listen(path string) (net.Listener, func(), error) { } guid := formatGUID(guidData) fileText := fmt.Sprintf("!%d s %s", port, guid) - file, err := os.OpenFile(nativePath, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0600) + file, err := createPrivateSocketFile(nativePath) if err != nil { _ = tcpListener.Close() return nil, nil, fmt.Errorf("create compatibility socket file: %w", err) @@ -194,6 +195,33 @@ func Listen(path string) (net.Listener, func(), error) { return ln, cleanup, nil } +// createPrivateSocketFile installs the owner-only ACL before writing the handshake secret. +func createPrivateSocketFile(path string) (*os.File, error) { + descriptor, err := windows.SecurityDescriptorFromString("D:P(A;;GA;;;SY)(A;;GA;;;OW)") + if err != nil { + return nil, fmt.Errorf("create private socket-file security descriptor: %w", err) + } + attributes := windows.SecurityAttributes{SecurityDescriptor: descriptor} + attributes.Length = uint32(unsafe.Sizeof(attributes)) + pathPointer, err := windows.UTF16PtrFromString(path) + if err != nil { + return nil, err + } + handle, err := windows.CreateFile( + pathPointer, + windows.GENERIC_WRITE|windows.FILE_READ_ATTRIBUTES, + windows.FILE_SHARE_READ|windows.FILE_SHARE_WRITE, + &attributes, + windows.CREATE_NEW, + windows.FILE_ATTRIBUTE_NORMAL, + 0, + ) + if err != nil { + return nil, err + } + return os.NewFile(uintptr(handle), path), nil +} + // removeStaleSocketFile reclaims a Cygwin endpoint only after its loopback listener refuses connections. func removeStaleSocketFile(path, nativePath string) error { info, err := os.Lstat(nativePath) diff --git a/scripts/build-windows-msi/summary.go b/scripts/build-windows-msi/summary.go index 43e0bba..87d1e62 100644 --- a/scripts/build-windows-msi/summary.go +++ b/scripts/build-windows-msi/summary.go @@ -116,7 +116,7 @@ func updateMSISummary(path string, timestamp time.Time) error { return fmt.Errorf("create temporary MSI: %w", err) } tempPath := temp.Name() - defer os.Remove(tempPath) + defer func() { _ = os.Remove(tempPath) }() writer := cfb.NewWriterV3(temp) replaced, err := copyStorage(writer.StorageWriter, reader.Storage, updatedSummary, true)