-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtunnel.go
85 lines (70 loc) · 1.76 KB
/
tunnel.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package main
import (
"fmt"
"io"
"io/ioutil"
"log"
"net"
"golang.org/x/crypto/ssh"
"golang.org/x/sync/errgroup"
)
const dockerSocket = "/var/run/docker.sock"
// SSHTunnel forwards connections to a remote host through SSH
type SSHTunnel struct {
Endpoint string
Config *ssh.ClientConfig
}
// Start opens the ssh tunnel and forwards connections through it
func (tunnel *SSHTunnel) Start(listener net.Listener) error {
serverConn, err := ssh.Dial("tcp", tunnel.Endpoint, tunnel.Config)
if err != nil {
return fmt.Errorf("server dial error: %v", err)
}
defer serverConn.Close()
for {
localConn, err := listener.Accept()
if err != nil {
return fmt.Errorf("error accepting connection: %v", err)
}
go tunnel.handleConnection(localConn, serverConn)
}
}
func (tunnel *SSHTunnel) handleConnection(localConn net.Conn, s *ssh.Client) {
defer localConn.Close()
remoteConn, err := s.Dial("unix", dockerSocket)
if err != nil {
fmt.Printf("remote dial error: %v", err)
return
}
defer remoteConn.Close()
tunnel.forward(localConn, remoteConn)
}
func (tunnel *SSHTunnel) forward(localConn, remoteConn net.Conn) error {
var g errgroup.Group
g.Go(pipe(localConn, remoteConn))
g.Go(pipe(remoteConn, localConn))
return g.Wait()
}
func pipe(w io.Writer, r io.Reader) func() error {
return func() error {
_, err := io.Copy(w, r)
if err != io.EOF {
return err
}
return nil
}
}
func getSSHKey(key []byte) ssh.AuthMethod {
signer, err := ssh.ParsePrivateKey(key)
if err != nil {
log.Fatalf("unable to parse private key: %v", err)
}
return ssh.PublicKeys(signer)
}
func getSSHKeyFromFile(filename string) ssh.AuthMethod {
key, err := ioutil.ReadFile(filename)
if err != nil {
log.Fatalf("unable to read private key: %v", err)
}
return getSSHKey(key)
}