Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -369,7 +369,7 @@ On Windows and Linux, use `--config FILE` to select another file; command-line v
- 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.
- If the configured Listen endpoint is already active or blocked by a non-socket file, the GUI starts with the proxy `Not configured`.
- 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.

Expand Down
4 changes: 3 additions & 1 deletion cmd/ssh-keyselect-gui/gui_config.go
Original file line number Diff line number Diff line change
Expand Up @@ -1067,7 +1067,9 @@ func (s *guiSettingsState) apply() {
activeUpstream, _ := s.app.endpointAgent.Snapshot()
unchanged = unchanged && activeUpstream.Path == resolvedUpstream
}
if unchanged {
// An unchanged Apply must retry a listener that was unavailable at startup.
retryUnavailableListen := s.app.actualListen == ""
if unchanged && !retryUnavailableListen {
guiCloseWindowAfterFrame(s.window)
return
}
Expand Down
47 changes: 43 additions & 4 deletions cmd/ssh-keyselect-gui/listen_endpoint_windows.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,16 @@
package main

import (
"context"
"errors"
"net"
"os"
"time"

"github.com/jfut/ssh-keyselect/internal/transport"
"github.com/jfut/ssh-keyselect/internal/winpath"
"github.com/jfut/ssh-keyselect/internal/winsocket"
"golang.org/x/sys/windows"
)

// guiListenPathExists checks filesystem endpoints and leaves named pipes to the pipe listener.
Expand All @@ -21,11 +27,44 @@ func guiListenPathExists(endpoint string) (bool, error) {
if err != nil {
return false, nil
}
if _, err := os.Lstat(path); err == nil {
return true, nil
} else if errors.Is(err, os.ErrNotExist) {
info, err := os.Lstat(path)
if errors.Is(err, os.ErrNotExist) {
return false, nil
} else {
}
if err != nil {
return false, err
}
if info.Mode()&os.ModeSocket != 0 {
if err := winsocket.CheckCurrentUserFileOwner(path); err != nil {
return true, nil
}
conn, dialErr := net.DialTimeout("unix", path, 300*time.Millisecond)
if dialErr == nil {
_ = conn.Close()
return true, nil
}
return !guiWindowsSocketProbeFoundStale(dialErr), nil
}

mode, modeErr := winsocket.DetectMode(endpoint)
if modeErr != nil || mode != transport.Cygwin {
// Non-socket files and unknown compatibility metadata still occupy the path.
return true, nil
}
if err := winsocket.CheckCurrentUserFileOwner(path); err != nil {
return true, nil
}
ctx, cancel := context.WithTimeout(context.Background(), 300*time.Millisecond)
conn, dialErr := winsocket.Dial(ctx, endpoint)
cancel()
if dialErr == nil {
_ = conn.Close()
return true, nil
}
return !guiWindowsSocketProbeFoundStale(dialErr), nil
}

// guiWindowsSocketProbeFoundStale accepts only errors proving that no listener remains.
func guiWindowsSocketProbeFoundStale(err error) bool {
return errors.Is(err, windows.WSAECONNREFUSED) || errors.Is(err, os.ErrNotExist)
}
2 changes: 1 addition & 1 deletion docs/dev.md
Original file line number Diff line number Diff line change
Expand Up @@ -215,7 +215,7 @@ At GUI startup and for New, an unset upstream resolves from `UPSTREAM_SSH_AUTH_S

The event loop stays available to finish cancelled picker tasks while server handlers drain. MyGo's `OnWillQuit` handler stops the selector, cancels the application context, and waits for server shutdown and owned socket cleanup before returning. Closing the native picker releases its waiting agent request so shutdown can finish while the UI loop is active.

At GUI startup, an active socket, non-socket filesystem entry, socket not owned by the effective user, or inconclusive stale-socket probe leaves the proxy unconfigured. An owned stale socket can proceed to the listener's ownership and identity checks for safe reclamation.
At GUI startup, an active socket, non-socket filesystem entry, socket not owned by the current user, or inconclusive stale-socket probe leaves the proxy unconfigured. Stale probes have a 300 ms deadline. Unix listeners treat only `ECONNREFUSED` and `ENOENT` as stale. Windows AF_UNIX listeners require a refused Unix-socket probe; Cygwin listeners require a refused loopback TCP probe. Both check the file owner and recheck filesystem identity before removing a stale socket. Named pipes do not use filesystem-path checks.

### GUI rendering and memory

Expand Down
30 changes: 30 additions & 0 deletions internal/listener/windows.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,13 @@ import (
"path/filepath"
"strings"
"sync"
"time"

"github.com/Microsoft/go-winio"
"github.com/jfut/ssh-keyselect/internal/transport"
"github.com/jfut/ssh-keyselect/internal/winpath"
"github.com/jfut/ssh-keyselect/internal/winsocket"
"golang.org/x/sys/windows"
)

const pipePrefix = `\\.\pipe\`
Expand Down Expand Up @@ -79,6 +81,34 @@ func listenUnixSocket(path string) (net.Listener, func(), error) {
if err := os.MkdirAll(filepath.Dir(nativePath), 0700); err != nil {
return nil, nil, fmt.Errorf("create socket directory: %w", err)
}
if info, err := os.Lstat(nativePath); err == nil {
if info.Mode()&os.ModeSocket == 0 {
return nil, nil, fmt.Errorf("listen path exists and is not a socket: %s", nativePath)
}
if err := winsocket.CheckCurrentUserFileOwner(nativePath); err != nil {
return nil, nil, fmt.Errorf("stale listen socket is not owned by the current user: %w", err)
}
conn, dialErr := net.DialTimeout("unix", nativePath, 300*time.Millisecond)
if dialErr == nil {
_ = conn.Close()
return nil, nil, fmt.Errorf("another instance is already listening on %s", nativePath)
}
if !errors.Is(dialErr, windows.WSAECONNREFUSED) && !errors.Is(dialErr, os.ErrNotExist) {
return nil, nil, fmt.Errorf("cannot determine whether socket is stale: %w", dialErr)
}
current, err := os.Lstat(nativePath)
if errors.Is(err, os.ErrNotExist) {
// Another process already removed the stale socket; bind below.
} else if err != nil {
return nil, nil, fmt.Errorf("reinspect stale socket: %w", err)
} else if !os.SameFile(info, current) {
return nil, nil, fmt.Errorf("listen path changed while checking stale socket: %s", nativePath)
} else if err := os.Remove(nativePath); err != nil && !errors.Is(err, os.ErrNotExist) {
return nil, nil, fmt.Errorf("remove stale socket: %w", err)
}
} else if !errors.Is(err, os.ErrNotExist) {
return nil, nil, fmt.Errorf("inspect listen socket: %w", err)
}
ln, err := net.Listen("unix", nativePath)
if err != nil {
return nil, nil, fmt.Errorf("listen on Windows Unix socket: %w", err)
Expand Down
76 changes: 76 additions & 0 deletions internal/winsocket/socketfile_windows.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"context"
"crypto/rand"
"encoding/binary"
"errors"
"fmt"
"io"
"net"
Expand Down Expand Up @@ -129,6 +130,9 @@ func Listen(path string) (net.Listener, func(), error) {
if err := os.MkdirAll(filepath.Dir(nativePath), 0700); err != nil {
return nil, nil, fmt.Errorf("create socket-file directory: %w", err)
}
if err := removeStaleSocketFile(path, nativePath); err != nil {
return nil, nil, err
}
tcpListener, err := net.ListenTCP("tcp4", &net.TCPAddr{IP: net.IPv4(127, 0, 0, 1)})
if err != nil {
return nil, nil, fmt.Errorf("listen on loopback TCP socket: %w", err)
Expand Down Expand Up @@ -190,6 +194,78 @@ func Listen(path string) (net.Listener, func(), error) {
return ln, cleanup, nil
}

// removeStaleSocketFile reclaims a Cygwin endpoint only after its loopback listener refuses connections.
func removeStaleSocketFile(path, nativePath string) error {
info, err := os.Lstat(nativePath)
if errors.Is(err, os.ErrNotExist) {
return nil
}
if err != nil {
return fmt.Errorf("inspect compatibility socket file: %w", err)
}
if !info.Mode().IsRegular() {
return fmt.Errorf("compatibility socket path exists and is not a file: %s", nativePath)
}
if err := CheckCurrentUserFileOwner(nativePath); err != nil {
return fmt.Errorf("compatibility socket file is not owned by the current user: %w", err)
}
if _, err := read(path); err != nil {
return fmt.Errorf("compatibility socket path exists and is not a valid socket file: %w", err)
}

ctx, cancel := context.WithTimeout(context.Background(), 300*time.Millisecond)
conn, dialErr := Dial(ctx, path)
cancel()
if dialErr == nil {
_ = conn.Close()
return fmt.Errorf("another instance is already listening on %s", nativePath)
}
if !errors.Is(dialErr, windows.WSAECONNREFUSED) && !errors.Is(dialErr, os.ErrNotExist) {
return fmt.Errorf("cannot determine whether compatibility socket is stale: %w", dialErr)
}

current, err := os.Lstat(nativePath)
if errors.Is(err, os.ErrNotExist) {
return nil
}
if err != nil {
return fmt.Errorf("reinspect stale compatibility socket: %w", err)
}
if !os.SameFile(info, current) {
return fmt.Errorf("compatibility socket path changed while checking stale socket: %s", nativePath)
}
if err := os.Remove(nativePath); err != nil && !errors.Is(err, os.ErrNotExist) {
return fmt.Errorf("remove stale compatibility socket: %w", err)
}
return nil
}

// CheckCurrentUserFileOwner prevents stale socket cleanup from removing another Windows user's file.
func CheckCurrentUserFileOwner(path string) error {
descriptor, err := windows.GetNamedSecurityInfo(path, windows.SE_FILE_OBJECT, windows.OWNER_SECURITY_INFORMATION)
if err != nil {
return fmt.Errorf("read file owner: %w", err)
}
if descriptor == nil {
return fmt.Errorf("file owner is unavailable")
}
owner, _, err := descriptor.Owner()
if err != nil {
return fmt.Errorf("read file owner: %w", err)
}
if owner == nil {
return fmt.Errorf("file owner is unavailable")
}
user, err := windows.GetCurrentProcessToken().GetTokenUser()
if err != nil {
return fmt.Errorf("read current user: %w", err)
}
if user == nil || user.User.Sid == nil || !owner.Equals(user.User.Sid) {
return fmt.Errorf("file belongs to another user")
}
return nil
}

func makeSocketFile(portText, guidText string) (socketFile, error) {
port, err := strconv.ParseUint(portText, 10, 16)
if err != nil || port == 0 {
Expand Down
Loading