Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go x/crypto/ssh -- How to establish ssh connection to private instance over a bastion node

Tags:

ssh

go

I want to implement this scenario: On AWS, I have a VPC, in which it is deployed a public and private subnet. In the public subnet, I have a "bastion" instance, while in private subnet, there is one node running some services(AKA "service instance"). By using *nux ssh command, I can do things like this to connect to the "service instance" from my local laptop:

ssh -t -o ProxyCommand="ssh -i <key> ubuntu@<bastion-ip> nc %h %p" -i <key> ubuntu@<service-instance-ip>

I have a Go program, and want to do the following things:

  1. ssh connect to the "service instance" from "local laptop" over the "bastion"
  2. use the connection session to run some commands (e.g. "ls -l")
  3. upload files from "local laptop" to "service instance"

I've tried but not able to implement the same process as doing

ssh -t -o ProxyCommand="ssh -i <key> ubuntu@<bastion-ip> nc %h %p" -i <key> ubuntu@<service-instance-ip>

Could anyone help to show me an example? Thanks!

BTW, I found this: https://github.com/golang/go/issues/6223, which means it is definately able to do that, right?

like image 348
Edward Avatar asked Dec 05 '22 01:12

Edward


1 Answers

You can do this even more directly with the "x/crypto/ssh" without the nc command, since there is a method to dial a connection from the remote host and presents it as a net.Conn.

Once you have an ssh.Client, you can use the Dial method to get a virtual net.Conn between you and the final host. You can then turn that into a new ssh.Conn with ssh.NewClientConn, and create a new ssh.Client with ssh.NewClient

// connect to the bastion host
bClient, err := ssh.Dial("tcp", bastionAddr, config)
if err != nil {
    log.Fatal(err)
}

// Dial a connection to the service host, from the bastion
conn, err := bClient.Dial("tcp", serviceAddr)
if err != nil {
    log.Fatal(err)
}

ncc, chans, reqs, err := ssh.NewClientConn(conn, serviceAddr, config)
if err != nil {
    log.Fatal(err)
}

sClient := ssh.NewClient(ncc, chans, reqs)
// sClient is an ssh client connected to the service host, through the bastion host.
like image 60
JimB Avatar answered Dec 11 '22 12:12

JimB