-
Notifications
You must be signed in to change notification settings - Fork 10
/
client.go
187 lines (156 loc) · 4.17 KB
/
client.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
186
187
package main
import (
"crypto/tls"
"crypto/x509"
"flag"
"fmt"
"io"
"io/ioutil"
"log"
"net"
"net/http"
"net/http/httputil"
"net/url"
"path"
"strings"
"golang.org/x/net/proxy"
"golang.org/x/net/websocket"
)
var (
certsDir = flag.String("certs_dir", "", "Directory of certs for TLS connection to AMQP, or empty for non-TLS connection. "+
"Expected files are: cacert.pem, cert.pem and key.pem.")
serverName = flag.String("server_name", "", "Name of the server for TLS verification, or empty for default")
targetHost = flag.String("target_host", "", "The target host:port to tunnel to")
port = flag.Int("port", 8080, "The local port to listen on")
listenAddr = flag.String("listen_addr", "127.0.0.1", "Address to listen on. Empty string for all interfaces.")
)
func getTlsConfig() (*tls.Config, error) {
if *certsDir == "" {
return nil, nil
}
tlscfg := &tls.Config{
RootCAs: x509.NewCertPool(),
CurvePreferences: []tls.CurveID{tls.CurveP521, tls.CurveP384, tls.CurveP256},
MinVersion: tls.VersionTLS12,
CipherSuites: []uint16{
tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
},
}
if ca, err := ioutil.ReadFile(path.Join(*certsDir, "cacert.pem")); err == nil {
tlscfg.RootCAs.AppendCertsFromPEM(ca)
} else {
return nil, fmt.Errorf("Failed reading CA certificate: %v", err)
}
if cert, err := tls.LoadX509KeyPair(path.Join(*certsDir, "/cert.pem"), path.Join(*certsDir, "/key.pem")); err == nil {
tlscfg.Certificates = append(tlscfg.Certificates, cert)
} else {
return nil, fmt.Errorf("Failed reading client certificate: %v", err)
}
tlscfg.ServerName = strings.Split(*targetHost, ":")[0]
if *serverName != "" {
tlscfg.ServerName = *serverName
}
return tlscfg, nil
}
func getWsConfig() (*websocket.Config, error) {
url := url.URL{Scheme: "ws", Host: *targetHost}
if *certsDir != "" {
url.Scheme = "wss"
}
config, err := websocket.NewConfig(url.String(), "http://localhost/")
if err != nil {
return nil, err
}
if config.TlsConfig, err = getTlsConfig(); err != nil {
return nil, err
}
return config, nil
}
func iocopy(dst io.Writer, src io.Reader, c chan error) {
_, err := io.Copy(dst, src)
c <- err
}
type closeable interface {
CloseWrite() error
}
func closeWrite(conn net.Conn) {
if closeme, ok := conn.(closeable); ok {
closeme.CloseWrite()
}
}
func getProxiedConn(turl url.URL) (net.Conn, error) {
// We first try to get a Socks5 proxied conncetion. If that fails, we're moving on to http{s,}_proxy.
dialer := proxy.FromEnvironment()
if dialer != proxy.Direct {
return dialer.Dial("tcp", turl.Host)
}
turl.Scheme = strings.Replace(turl.Scheme, "ws", "http", 1)
proxyURL, err := http.ProxyFromEnvironment(&http.Request{URL: &turl})
if proxyURL == nil {
return net.Dial("tcp", turl.Host)
}
p, err := net.Dial("tcp", proxyURL.Host)
if err != nil {
return nil, err
}
cc := httputil.NewProxyClientConn(p, nil)
_, err = cc.Do(&http.Request{
Method: "CONNECT",
URL: &url.URL{},
Host: turl.Host,
})
if err != nil && err != httputil.ErrPersistEOF {
return nil, err
}
conn, _ := cc.Hijack()
return conn, nil
}
func handleConnection(wsConfig *websocket.Config, conn net.Conn) {
defer conn.Close()
tcp, err := getProxiedConn(*wsConfig.Location)
if err != nil {
log.Print("getProxiedConn(): ", err)
return
}
if *certsDir != "" {
tcp = tls.Client(tcp, wsConfig.TlsConfig)
}
ws, err := websocket.NewClient(wsConfig, tcp)
if err != nil {
log.Print("websocket.NewClient(): ", err)
return
}
defer ws.Close()
c := make(chan error, 2)
go iocopy(ws, conn, c)
go iocopy(conn, ws, c)
for i := 0; i < 2; i++ {
if err := <-c; err != nil {
fmt.Print("io.Copy(): ", err)
return
}
// If any of the sides closes the connection, we want to close the write channel.
closeWrite(conn)
closeWrite(tcp)
}
}
func main() {
flag.Parse()
wsConfig, err := getWsConfig()
if err != nil {
panic(err)
}
ln, err := net.Listen("tcp", fmt.Sprintf("%s:%d", *listenAddr, *port))
if err != nil {
panic(err)
}
for {
conn, err := ln.Accept()
if err != nil {
log.Print("ln.Accept(): ", err)
continue
}
go handleConnection(wsConfig, conn)
}
}