Skip to content

Commit

Permalink
support forward agent
Browse files Browse the repository at this point in the history
  • Loading branch information
lonnywong committed Sep 16, 2023
1 parent 9940bb8 commit cd27bcc
Show file tree
Hide file tree
Showing 5 changed files with 151 additions and 56 deletions.
77 changes: 55 additions & 22 deletions tssh/agent_unix.go
Original file line number Diff line number Diff line change
@@ -1,40 +1,73 @@
//go:build !windows

/*
MIT License
Copyright (c) 2023 Lonny Wong <[email protected]>
Copyright (c) 2023 [Contributors](https://github.com/trzsz/trzsz-ssh/graphs/contributors)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

package tssh

import (
"net"
"os"
"sync"
"time"

"golang.org/x/crypto/ssh/agent"
)

func getAgentSigners() []*sshSigner {
socket := os.Getenv("SSH_AUTH_SOCK")
if socket == "" {
return nil
}
var (
agentOnce sync.Once
agentConn net.Conn
agentClient agent.ExtendedAgent
)

conn, err := net.DialTimeout("unix", socket, time.Second)
if err != nil {
debug("open ssh agent [%s] failed: %v", socket, err)
return nil
}
cleanupAfterLogined = append(cleanupAfterLogined, func() {
conn.Close()
func getAgentClient() agent.ExtendedAgent {
agentOnce.Do(func() {
sock := os.Getenv("SSH_AUTH_SOCK")
if sock == "" {
debug("no ssh agent environment variable SSH_AUTH_SOCK")
return
}

var err error
agentConn, err = net.DialTimeout("unix", sock, time.Second)
if err != nil {
debug("dial ssh agent unix socket [%s] failed: %v", sock, err)
return
}

agentClient = agent.NewClient(agentConn)
debug("new ssh agent client [%s] success", sock)
})

client := agent.NewClient(conn)
signers, err := client.Signers()
if err != nil {
debug("get ssh agent signers failed: %v", err)
return nil
}
return agentClient
}

wrappers := make([]*sshSigner, 0, len(signers))
for _, signer := range signers {
wrappers = append(wrappers, &sshSigner{path: "ssh-agent", pubKey: signer.PublicKey(), signer: signer})
func closeAgentClient() {
if agentConn != nil {
agentConn.Close()
agentConn = nil
}
return wrappers
agentClient = nil
}
88 changes: 55 additions & 33 deletions tssh/agent_windows.go
Original file line number Diff line number Diff line change
@@ -1,53 +1,75 @@
package tssh

/*
MIT License
Copyright (c) 2023 Lonny Wong <[email protected]>
Copyright (c) 2023 [Contributors](https://github.com/trzsz/trzsz-ssh/graphs/contributors)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

import (
"os"
"sync"
"time"

"github.com/natefinch/npipe"
"golang.org/x/crypto/ssh/agent"
)

// AGENT_PIPE_ID is the default pipe id for openssh ssh-agent on windows.
const AGENT_PIPE_ID = `\\.\pipe\openssh-ssh-agent`

func getAgentSigners() []*sshSigner {
pipeId := AGENT_PIPE_ID
var (
agentOnce sync.Once
agentConn *npipe.PipeConn
agentClient agent.ExtendedAgent
)

// if avaialable, use env:SSH_AUTH_SOCK as pipe id
if socket := os.Getenv("SSH_AUTH_SOCK"); socket != "" {
pipeId = socket
}
func getAgentClient() agent.ExtendedAgent {
agentOnce.Do(func() {
name := `\\.\pipe\openssh-ssh-agent`
if sock := os.Getenv("SSH_AUTH_SOCK"); sock != "" {
name = sock
}

// test named pipe existance
if _, err := os.Stat(pipeId); err != nil {
if !os.IsNotExist(err) {
debug("failed to access named pipe '%s': %v", pipeId, err)
if !isFileExist(name) {
debug("ssh agent named pipe [%s] does not exist", name)
return
}
return nil
}

// connect to named pipe
conn, err := npipe.DialTimeout(pipeId, time.Second)
if err != nil {
debug("open ssh agent on named pipe '%s' failed: %v", pipeId, err)
return nil
}
var err error
agentConn, err = npipe.DialTimeout(name, time.Second)
if err != nil {
debug("dial ssh agent named pipe [%s] failed: %v", name, err)
return
}

client := agent.NewClient(conn)
cleanupAfterLogined = append(cleanupAfterLogined, func() {
conn.Close()
agentClient = agent.NewClient(agentConn)
debug("new ssh agent client [%s] success", name)
})

signers, err := client.Signers()
if err != nil {
debug("get ssh agent signers failed: %v", err)
return nil
}
return agentClient
}

wrappers := make([]*sshSigner, 0, len(signers))
for _, signer := range signers {
wrappers = append(wrappers, &sshSigner{path: "ssh-agent", pubKey: signer.PublicKey(), signer: signer})
func closeAgentClient() {
if agentConn != nil {
agentConn.Close()
agentConn = nil
}
return wrappers
agentClient = nil
}
3 changes: 3 additions & 0 deletions tssh/args.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
MIT License
Copyright (c) 2023 Lonny Wong <[email protected]>
Copyright (c) 2023 [Contributors](https://github.com/trzsz/trzsz-ssh/graphs/contributors)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
Expand Down Expand Up @@ -50,6 +51,8 @@ type sshArgs struct {
Destination string `arg:"positional" help:"alias in ~/.ssh/config, or [user@]hostname[:port]"`
Command string `arg:"positional" help:"command to execute instead of a login shell"`
Argument []string `arg:"positional" help:"command arguments separated by spaces"`
ForwardAgent bool `arg:"-A,--" help:"enable forwarding the ssh agent connection"`
NoForwardAgent bool `arg:"-a,--" help:"disable forwarding the ssh agent connection"`
DisableTTY bool `arg:"-T,--" help:"disable pseudo-terminal allocation"`
ForceTTY bool `arg:"-t,--" help:"force pseudo-terminal allocation"`
Gateway bool `arg:"-g,--" help:"forwarding allows remote hosts to connect"`
Expand Down
3 changes: 3 additions & 0 deletions tssh/args_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
MIT License
Copyright (c) 2023 Lonny Wong <[email protected]>
Copyright (c) 2023 [Contributors](https://github.com/trzsz/trzsz-ssh/graphs/contributors)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
Expand Down Expand Up @@ -50,6 +51,8 @@ func TestSshArgs(t *testing.T) {

assertArgsEqual("", sshArgs{})
assertArgsEqual("-V", sshArgs{Ver: true})
assertArgsEqual("-A", sshArgs{ForwardAgent: true})
assertArgsEqual("-a", sshArgs{NoForwardAgent: true})
assertArgsEqual("-T", sshArgs{DisableTTY: true})
assertArgsEqual("-t", sshArgs{ForceTTY: true})
assertArgsEqual("-g", sshArgs{Gateway: true})
Expand Down
36 changes: 35 additions & 1 deletion tssh/login.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
MIT License
Copyright (c) 2023 Lonny Wong <[email protected]>
Copyright (c) 2023 [Contributors](https://github.com/trzsz/trzsz-ssh/graphs/contributors)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
Expand Down Expand Up @@ -45,6 +46,7 @@ import (
"github.com/skeema/knownhosts"
"github.com/trzsz/trzsz-go/trzsz"
"golang.org/x/crypto/ssh"
"golang.org/x/crypto/ssh/agent"
"golang.org/x/term"
)

Expand Down Expand Up @@ -554,7 +556,16 @@ func getPublicKeysAuthMethod(args *sshArgs) ssh.AuthMethod {
}
}

addPubKeySigners(getAgentSigners())
if agentClient := getAgentClient(); agentClient != nil {
signers, err := agentClient.Signers()
if err != nil {
warning("get ssh agent signers failed: %v", err)
} else {
for _, signer := range signers {
addPubKeySigners([]*sshSigner{{path: "ssh-agent", pubKey: signer.PublicKey(), signer: signer}})
}
}
}

if len(args.Identity.values) > 0 {
for _, identity := range args.Identity.values {
Expand Down Expand Up @@ -879,6 +890,26 @@ func wrapStdIO(serverIn io.WriteCloser, serverOut io.Reader, tty bool) {
go forwardIO(serverOut, os.Stdout, []byte("\n"), []byte("\r\n"))
}

func sshAgentForward(args *sshArgs, client *ssh.Client, session *ssh.Session) {
agentClient := getAgentClient()
if agentClient == nil {
return
}
if args.NoForwardAgent || !args.ForwardAgent && strings.ToLower(getOptionConfig(args, "ForwardAgent")) != "yes" {
closeAgentClient()
return
}
if err := agent.ForwardToAgent(client, agentClient); err != nil {
warning("forward to agent failed: %v", err)
return
}
if err := agent.RequestAgentForwarding(session); err != nil {
warning("request agent forwarding failed: %v", err)
return
}
debug("request ssh agent forwarding success")
}

func sshLogin(args *sshArgs, tty bool) (client *ssh.Client, session *ssh.Session, err error) {
defer func() {
if err != nil {
Expand Down Expand Up @@ -930,6 +961,9 @@ func sshLogin(args *sshArgs, tty bool) (client *ssh.Client, session *ssh.Session
return
}

// ssh agent forward
sshAgentForward(args, client, session)

// no tty
if !tty {
wrapStdIO(serverIn, serverOut, tty)
Expand Down

0 comments on commit cd27bcc

Please sign in to comment.