Thanks to visit codestin.com
Credit goes to github.com

Skip to content

feat: add GPG forwarding to coder ssh #5482

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 14 commits into from
Jan 6, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Prev Previous commit
Next Next commit
chore: PR comments
  • Loading branch information
deansheather committed Jan 5, 2023
commit a90d3d634cb5ebf13adba80d68cdc97e31d369ce
31 changes: 19 additions & 12 deletions agent/ssh.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ func (h *forwardedUnixHandler) HandleSSHRequest(ctx ssh.Context, _ *ssh.Server,
conn, ok := ctx.Value(ssh.ContextKeyConn).(*gossh.ServerConn)
if !ok {
h.log.Warn(ctx, "SSH unix forward request from client with no gossh connection")
return false, []byte{}
return false, nil
}

switch req.Type {
Expand All @@ -53,7 +53,7 @@ func (h *forwardedUnixHandler) HandleSSHRequest(ctx ssh.Context, _ *ssh.Server,
err := gossh.Unmarshal(req.Payload, &reqPayload)
if err != nil {
h.log.Warn(ctx, "parse [email protected] request payload from client", slog.Error(err))
return false, []byte{}
return false, nil
}

addr := reqPayload.SocketPath
Expand All @@ -64,7 +64,7 @@ func (h *forwardedUnixHandler) HandleSSHRequest(ctx ssh.Context, _ *ssh.Server,
h.log.Warn(ctx, "SSH unix forward request for socket path that is already being forwarded (maybe to another client?)",
slog.F("socket_path", addr),
)
return false, []byte{}
return false, nil
}

// Create socket parent dir if not exists.
Expand All @@ -76,7 +76,7 @@ func (h *forwardedUnixHandler) HandleSSHRequest(ctx ssh.Context, _ *ssh.Server,
slog.F("socket_path", addr),
slog.Error(err),
)
return false, []byte{}
return false, nil
}

ln, err := net.Listen("unix", addr)
Expand All @@ -85,19 +85,20 @@ func (h *forwardedUnixHandler) HandleSSHRequest(ctx ssh.Context, _ *ssh.Server,
slog.F("socket_path", addr),
slog.Error(err),
)
return false, []byte{}
return false, nil
}

// The listener needs to successfully start before it can be added to
// the map, so we don't have to worry about checking for an existing
// listener.
//
// This is also what the upstream TCP version of this code does.
h.Lock()
h.forwards[addr] = ln
h.Unlock()
go func() {
<-ctx.Done()
h.Lock()
ln, ok := h.forwards[addr]
h.Unlock()
if ok {
_ = ln.Close()
}
_ = ln.Close()
}()
go func() {
for {
Expand All @@ -109,6 +110,7 @@ func (h *forwardedUnixHandler) HandleSSHRequest(ctx ssh.Context, _ *ssh.Server,
slog.Error(err),
)
}
// closed below
break
}
payload := gossh.Marshal(&forwardedStreamLocalPayload{
Expand All @@ -129,9 +131,14 @@ func (h *forwardedUnixHandler) HandleSSHRequest(ctx ssh.Context, _ *ssh.Server,
Bicopy(ctx, ch, c)
}()
}

h.Lock()
delete(h.forwards, addr)
ln2, ok := h.forwards[addr]
if ok && ln2 == ln {
delete(h.forwards, addr)
}
h.Unlock()
_ = ln.Close()
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is the ctx/cancel necessary at all since we manually close here?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We need the ctx.Done() goroutine to kill the listener so we can free up that goroutine when i.e. the connection dies, however if the listener errors we need to cancel the context so we can free up that goroutine as well.

}()

return true, nil
Expand Down
69 changes: 34 additions & 35 deletions cli/ssh.go
Original file line number Diff line number Diff line change
Expand Up @@ -221,30 +221,18 @@ func ssh() *cobra.Command {
}
}

// Wait for the context to be canceled, or the SSH session to end.
sshErr := make(chan error)
go func() {
defer close(sshErr)

err = sshSession.Wait()
if err != nil {
// If the connection drops unexpectedly, we get an ExitMissingError but no other
// error details, so try to at least give the user a better message
if errors.Is(err, &gossh.ExitMissingError{}) {
sshErr <- xerrors.New("SSH connection ended unexpectedly")
return
}
sshErr <- err
err = sshSession.Wait()
if err != nil {
// If the connection drops unexpectedly, we get an
// ExitMissingError but no other error details, so try to at
// least give the user a better message
if errors.Is(err, &gossh.ExitMissingError{}) {
return xerrors.New("SSH connection ended unexpectedly")
}
}()

select {
case <-ctx.Done():
_ = sshSession.Close()
return ctx.Err()
case err := <-sshErr:
return err
}

return nil
},
}
cliflag.BoolVarP(cmd.Flags(), &stdio, "stdio", "", "CODER_SSH_STDIO", false, "Specifies whether to emit SSH output over stdin/stdout.")
Expand Down Expand Up @@ -456,7 +444,12 @@ func uploadGPGKeys(ctx context.Context, sshClient *gossh.Client) error {
// Check if the agent is running in the workspace already.
// Note: we don't support windows in the workspace for GPG forwarding so
// using shell commands is fine.
agentSocketBytes, err := runRemoteSSH(sshClient, nil, "set -eux; agent_socket=$(gpgconf --list-dir agent-socket); echo $agent_socket; test ! -S $agent_socket")
agentSocketBytes, err := runRemoteSSH(sshClient, nil, `
set -eux
agent_socket=$(gpgconf --list-dir agent-socket)
echo "$agent_socket"
test ! -S "$agent_socket"
`)
agentSocket := strings.TrimSpace(string(agentSocketBytes))
if err != nil {
return xerrors.Errorf("check if agent socket is running (check if %q exists): %w", agentSocket, err)
Expand Down Expand Up @@ -540,24 +533,30 @@ func sshForwardRemote(ctx context.Context, stderr io.Writer, sshClient *gossh.Cl
return
}

localConn, err := net.Dial(localAddr.Network(), localAddr.String())
if err != nil {
_, _ = fmt.Fprintf(stderr, "Dial local address %s: %+v\n", localAddr.String(), err)
_ = remoteConn.Close()
continue
}
go func() {
defer func() {
_ = remoteConn.Close()
}()

if c, ok := localAddr.(cookieAddr); ok {
_, err = localConn.Write(c.cookie)
localConn, err := net.Dial(localAddr.Network(), localAddr.String())
if err != nil {
_, _ = fmt.Fprintf(stderr, "Write cookie to local connection: %+v\n", err)
_, _ = fmt.Fprintf(stderr, "Dial local address %s: %+v\n", localAddr.String(), err)
return
}
defer func() {
_ = localConn.Close()
_ = remoteConn.Close()
continue
}()

if c, ok := localAddr.(cookieAddr); ok {
_, err = localConn.Write(c.cookie)
if err != nil {
_, _ = fmt.Fprintf(stderr, "Write cookie to local connection: %+v\n", err)
return
}
}
}

go agent.Bicopy(ctx, localConn, remoteConn)
agent.Bicopy(ctx, localConn, remoteConn)
}()
}
}()

Expand Down