Skip to content
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

Using ForwardAgentConnections for creating a "jump host" #207

Closed
antonmedv opened this issue Jun 21, 2023 · 1 comment
Closed

Using ForwardAgentConnections for creating a "jump host" #207

antonmedv opened this issue Jun 21, 2023 · 1 comment

Comments

@antonmedv
Copy link

Hello!

Thanks for your awesome library! Really appreciate your work.

I have a question: is it possible to create a "jump host" using your library and crypto/ssh client?

[User machine]  --->  [gliderlabs/ssh]  --->   [Another OpenSSH server]

Thanks!

@antonmedv
Copy link
Author

Looks like I figured it out:

package main

import (
	"io"
	"log"
	"net"
	"os"

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

func main() {
	ssh.Handle(func(s ssh.Session) {
		if !ssh.AgentRequested(s) {
			s.Write([]byte("no agent forwarding\n"))
			return
		}
		l, err := ssh.NewAgentListener()
		if err != nil {
			log.Fatal(err)
		}
		defer l.Close()
		go ssh.ForwardAgentConnections(l, s)

		// Get a connection to the local SSH agent
		conn, err := net.Dial("unix", l.Addr().String())
		if err != nil {
			panic(err)
		}

		// Create an agent from the connection
		sshAgent := agent.NewClient(conn)

		// Define the client configuration
		config := &ClientConfig{
			User: "root", // Replace with your username
			Auth: []AuthMethod{
				// Use the agent for authentication
				PublicKeysCallback(sshAgent.Signers),
			},
			// This callback is used for server verification.
			// In a real application, you might want to use something stricter
			HostKeyCallback: InsecureIgnoreHostKey(),
		}

		// Connect to the remote server
		sshClient, err := Dial("tcp", "", config)
		if err != nil {
			panic(err)
		}

		// Create a session
		session, err := sshClient.NewSession()
		if err != nil {
			panic(err)
		}
		defer session.Close()

		// Set up the agent forwarding
		err = agent.RequestAgentForwarding(session)
		if err != nil {
			panic(err)
		}

		// You can now execute a command or do something with the session
		var b []byte
		b, err = session.CombinedOutput("ip route")
		if err != nil {
			panic(err)
		}
		io.WriteString(os.Stdout, string(b))
	})

	log.Println("starting ssh server on port 2222...")
	log.Fatal(ssh.ListenAndServe(":2222", nil))
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant