/
tunnel.go
185 lines (168 loc) · 4.54 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
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
package tunnel
import (
"bufio"
"fmt"
"io"
"net"
"net/http"
"net/url"
"os"
"github.com/qiniu/log"
"golang.org/x/crypto/ssh"
)
type (
Configuration struct {
Protocol string `json:"protocol"`
Subdomain string `json:"subdomain"`
Domain string `json:"domain"`
Port int `json:"port"`
Host string `json:"host"`
User string
RemoteHost string
RemotePort int
TargetHost string
TargetPort int
InBoundConnectionHook func(net.Conn) error
Channel chan int
HideBanner bool
}
Error struct {
Code int `json:"code,omitempty"`
Message string `json:"message"`
}
)
const (
_ = iota
EventReconnect
)
var (
hostBytes = []byte("ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQDoSLknvlFrFzroOlh1cqvcIFelHO+Wvj1UZ/p3J9bgsJGiKfh3DmBqEw1DOEwpHJz4zuV375TyjGuHuGZ4I4xztnwauhFplfEvriVHQkIDs6UnGwJVr15XUQX04r0i6mLbJs5KqIZTZuZ9ZGOj7ZWnaA7C07nPHGrERKV2Fm67rPvT6/qFikdWUbCt7KshbzdwwfxUohmv+NI7vw2X6vPU8pDaNEY7vS3YgwD/WlvQx+WDF2+iwLVW8OWWjFuQso6Eg1BSLygfPNhAHoiOWjDkijc8U9LYkUn7qsDCnvJxCoTTNmdECukeHfzrUjTSw72KZoM5KCRV78Wrctai1Qn6yRQz9BOSguxewLfzHtnT43/MLdwFXirJ/Ajquve2NAtYmyGCq5HcvpDAyi7lQ0nFBnrWv5zU3YxrISIpjovVyJjfPx8SCRlYZwVeUq6N2yAxCzJxbElZPtaTSoXBIFtoas2NXnCWPgenBa/2bbLQqfgbN8VQ9RaUISKNuYDIn4+eO72+RxF9THzZeV17pnhTVK88XU4asHot1gXwAt4vEhSjdUBC9KUIkfukI6F4JFxtvuO96octRahdV1Qg0vF+D0+SPy2HxqjgZWgPE2Xh/NmuIXwbE0wkymR2wrgj8Hd4C92keo2NBRh9dD7D2negnVYaYsC+3k/si5HNuCHnHQ== tunnel@labstack.com")
)
func Create(c *Configuration) {
hostKey, _, _, _, err := ssh.ParseAuthorizedKey(hostBytes)
if err != nil {
log.Fatalf("failed to parse host key: %v", err)
}
config := &ssh.ClientConfig{
User: c.User,
Auth: []ssh.AuthMethod{
ssh.Password("password"),
},
HostKeyCallback: ssh.FixedHostKey(hostKey),
BannerCallback: func(message string) error {
if !c.HideBanner {
fmt.Print(message)
}
return nil
},
}
client := new(ssh.Client)
// Connect
proxy := os.Getenv("http_proxy")
if proxy != "" {
proxyURL, err := url.Parse(proxy)
if err != nil {
log.Fatalf("cannot open new session: %v", err)
}
tcp, err := net.Dial("tcp", proxyURL.Hostname())
if err != nil {
log.Fatalf("cannot open new session: %v", err)
}
connReq := &http.Request{
Method: "CONNECT",
URL: &url.URL{Path: c.Host},
Host: c.Host,
Header: make(http.Header),
}
if proxyURL.User != nil {
if p, ok := proxyURL.User.Password(); ok {
connReq.SetBasicAuth(proxyURL.User.Username(), p)
}
}
connReq.Write(tcp)
resp, err := http.ReadResponse(bufio.NewReader(tcp), connReq)
if err != nil {
log.Fatalf("cannot open new session: %v", err)
}
defer resp.Body.Close()
conn, chans, reqs, err := ssh.NewClientConn(tcp, c.Host, config)
if err != nil {
log.Fatalf("cannot open new session: %v", err)
}
client = ssh.NewClient(conn, chans, reqs)
} else {
client, err = ssh.Dial("tcp", c.Host, config)
}
if err != nil {
log.Errorf("failed to connect: %v", err)
c.Channel <- EventReconnect
return
}
defer client.Close()
// Session
sess, err := client.NewSession()
if err != nil {
log.Fatalf("failed to create session: %v", err)
}
defer sess.Close()
r, err := sess.StdoutPipe()
if err != nil {
log.Print(err)
}
br := bufio.NewReader(r)
go func() {
for {
line, _, err := br.ReadLine()
if err != nil {
if err == io.EOF {
c.Channel <- EventReconnect
return
} else {
log.Fatalf("failed to read: %v", err)
}
}
fmt.Printf("%s\n", line)
}
}()
// Remote listener
ln, err := client.Listen("tcp", fmt.Sprintf("%s:%d", c.RemoteHost, c.RemotePort))
if err != nil {
log.Fatalf("failed to listen on remote host: %v", err)
}
defer ln.Close()
for {
// Handle inbound connection
in, err := ln.Accept()
if err != nil {
log.Printf("failed to accept connection: %v", err)
return
}
if c.InBoundConnectionHook != nil {
go c.InBoundConnectionHook(in)
continue
}
go func(in net.Conn) {
defer in.Close()
// Target connection
out, err := net.Dial("tcp", fmt.Sprintf("%s:%d", c.TargetHost, c.TargetPort))
if err != nil {
log.Printf("failed to connect to target: %v", err)
return
}
defer out.Close()
// Copy
errCh := make(chan error, 2)
cp := func(dst io.Writer, src io.Reader) {
_, err := io.Copy(dst, src)
errCh <- err
}
go cp(in, out)
go cp(out, in)
// Handle error
err = <-errCh
if err != nil && err != io.EOF {
log.Printf("failed to copy: %v", err)
}
}(in)
}
}