This repository was archived by the owner on Oct 2, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathssh_tunnel.go
More file actions
218 lines (184 loc) · 4.47 KB
/
ssh_tunnel.go
File metadata and controls
218 lines (184 loc) · 4.47 KB
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
package main
import (
"context"
"fmt"
"io"
"io/ioutil"
"net"
"os"
"os/user"
"path/filepath"
"strconv"
"strings"
"github.com/kevinburke/ssh_config"
"golang.org/x/crypto/ssh"
"golang.org/x/crypto/ssh/agent"
)
// Endpoint ..
type Endpoint struct {
Host string
Port int
}
func (endpoint *Endpoint) String() string {
return fmt.Sprintf("%s:%d", endpoint.Host, endpoint.Port)
}
// SSHtunnel ..
type SSHtunnel struct {
Local *Endpoint
Server *Endpoint
Remote *Endpoint
Config *ssh.ClientConfig
}
// Start a ssh tunnel
func (tunnel *SSHtunnel) Start(ctx context.Context) error {
listener, err := net.Listen("tcp", tunnel.Local.String())
if err != nil {
return err
}
defer listener.Close()
for {
go func() {
select {
case <-ctx.Done():
listener.Close()
return
}
}()
conn, err := listener.Accept()
if err != nil {
return err
}
go tunnel.forward(conn)
}
}
func (tunnel *SSHtunnel) forward(localConn net.Conn) {
fmt.Printf("Dial to %s", tunnel.Server.String())
serverConn, err := ssh.Dial("tcp", tunnel.Server.String(), tunnel.Config)
if err != nil {
fmt.Printf("Server dial error: %s\n", err)
return
}
remoteConn, err := serverConn.Dial("tcp", tunnel.Remote.String())
if err != nil {
fmt.Printf("Remote dial error: %s\n", err)
return
}
copyConn := func(writer, reader net.Conn) {
defer writer.Close()
defer reader.Close()
_, err := io.Copy(writer, reader)
if err != nil {
fmt.Printf("io.Copy error: %s", err)
}
defer serverConn.Close()
defer remoteConn.Close()
}
go copyConn(localConn, remoteConn)
go copyConn(remoteConn, localConn)
}
// SSHAgent ..
func SSHAgent() ssh.AuthMethod {
if sshAgent, err := net.Dial("unix", os.Getenv("SSH_AUTH_SOCK")); err == nil {
return ssh.PublicKeysCallback(agent.NewClient(sshAgent).Signers)
}
return nil
}
// PublicKeyFile ..
func PublicKeyFile(file string) (ssh.AuthMethod, error) {
buffer, err := ioutil.ReadFile(file)
if err != nil {
return nil, err
}
key, err := ssh.ParsePrivateKey(buffer)
if err != nil {
return nil, err
}
return ssh.PublicKeys(key), nil
}
func start(ctx context.Context, sshcfg *ssh_config.Config, sshHost string) {
/*
Host my-tunnel
Hostname 52.233.225.199
User gesund
IdentityFile ~/.ssh/id_rsa
DynamicForward 8080
ControlMaster auto
ControlPath ~/.ssh/sockets/%r@%h:%p
UserKnownHostsFile /dev/null
StrictHostKeyChecking no
LocalForward 127.0.0.1:9906 127.0.0.1:3306
*/
localForward, _ := sshcfg.Get(sshHost, "LocalForward")
if len(localForward) <= 0 {
panic("Missing LocalForward ssh configuration.")
}
localForwards := strings.Split(localForward, " ")
if len(localForwards) < 2 {
panic("Missing LocalForward local and remote definition.")
}
localForward, remoteForward := localForwards[0], localForwards[1]
fmt.Println(localForward, remoteForward)
host, strPort, err := net.SplitHostPort(localForward)
fmt.Println(host, strPort)
port, err := strconv.Atoi(strPort)
if err != nil {
panic(err)
}
// Read hosts and users from ssh config
localEndpoint := &Endpoint{
Host: host,
Port: port, // "localForwardPort"
}
remoteHostname, _ := sshcfg.Get(sshHost, "Hostname")
fmt.Println(remoteHostname)
serverEndpoint := &Endpoint{
Host: remoteHostname,
Port: 22, //default ssh port
}
host, strPort, err = net.SplitHostPort(remoteForward)
port, err = strconv.Atoi(strPort)
if err != nil {
panic(err)
}
//TODO localForwardCfg must be parsed into
//remote localfowrad [optional ip]:port dest_ip:port
remoteEndpoint := &Endpoint{
Host: host, // get from localForwardCfg
Port: port, // localForwardCfg
}
username, _ := sshcfg.Get(sshHost, "User")
fmt.Println(username)
identityFile, _ := sshcfg.Get(sshHost, "IdentityFile")
fmt.Println(identityFile)
// Check in case of paths like "/something/~/something/"
if strings.HasPrefix(identityFile, "~/") {
usr, _ := user.Current()
dir := usr.HomeDir
identityFile = filepath.Join(dir, identityFile[2:])
}
fmt.Println(identityFile)
publicKey, err := PublicKeyFile(identityFile)
if err != nil {
panic(err)
}
sshConfig := &ssh.ClientConfig{
User: username,
Auth: []ssh.AuthMethod{
publicKey,
},
HostKeyCallback: func(hostname string, remote net.Addr, key ssh.PublicKey) error {
return nil
},
/*Auth: []ssh.AuthMethod{
SSHAgent(),
},*/
}
fmt.Println()
tunnel := &SSHtunnel{
Config: sshConfig,
Local: localEndpoint,
Server: serverEndpoint,
Remote: remoteEndpoint,
}
go tunnel.Start(ctx)
}