-
Notifications
You must be signed in to change notification settings - Fork 0
/
tunnelConn.go
216 lines (198 loc) · 5.15 KB
/
tunnelConn.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
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
package main
import (
"context"
"errors"
"fmt"
"github.com/gorilla/websocket"
"golang.org/x/oauth2/google"
"google.golang.org/api/compute/v1"
"io"
"net/http"
"net/url"
"strconv"
"strings"
)
// TunnelConnection represents the connection between your local
// machine and the IAP
type TunnelConnection struct {
websocketConn *websocket.Conn
reader io.Reader
writer io.Writer
bytesAcked uint32
bytesReceived uint32
connected bool
sid string
project string
zone string
instanceName string
port string
nic string
}
const (
tlsBaseUri = "tunnel.cloudproxy.app"
wssScheme = "wss"
mtlsScheme = "mtls"
webSocketVersion = "v4"
connectEndpoint = "connect"
// Currently not used, I can check what's required to trigger this...
mtlsBaseURi = "mtls.tunnel.cloudproxy.app"
subProtocolName = "relay.tunnel.cloudproxy.app"
origin = "bot:iap-tunneler"
defaultNetworkInterface = "nic0"
)
// TunnelConnectionOption acts as a configuration wrapper to our tunnel connection
type TunnelConnectionOption func(connection *TunnelConnection)
// NewTunnelConnection creates a tunnel connection object, but doesn't connect to the
// websocket connection.
func NewTunnelConnection(ctx context.Context, opts ...TunnelConnectionOption) (*TunnelConnection, error) {
tc := &TunnelConnection{}
for _, opt := range opts {
opt(tc)
}
if tc.nic == "" {
tc.nic = defaultNetworkInterface
}
computeService, err := compute.NewService(context.Background())
if err != nil {
return nil, err
}
instanceService := computeService.Instances
instanceListCall := instanceService.List(tc.project, tc.zone)
filters := []string{
"status = RUNNING",
fmt.Sprintf("name = %s", tc.instanceName),
}
instanceListCall.Filter(strings.Join(filters[:], " "))
instanceList, err := instanceListCall.Do()
if err != nil {
return nil, err
}
// verify instance exists
instanceVerify := false
for _, instance := range instanceList.Items {
nicVerify := false
for _, nic := range instance.NetworkInterfaces {
if nic.Name == tc.nic {
nicVerify = true
break
}
}
if !nicVerify {
break
}
if instance.Name == tc.instanceName {
instanceVerify = true
break
}
}
if !instanceVerify {
return nil, errors.New("failed to find instance")
}
return tc, nil
}
// Connect connects to the websocket, duh.
func (tc *TunnelConnection) Connect(ctx context.Context) error {
// currently it doesn't give me an issue with scopes, in the future
// I may want to be explicit
scopes := []string{}
cred, err := google.FindDefaultCredentials(ctx, scopes...)
if err != nil {
return err
}
ts, err := cred.TokenSource.Token()
// may want to be more variable down the road, but for now this works
u := url.URL{Scheme: wssScheme, Host: tlsBaseUri, Path: fmt.Sprintf("/%s/%s", webSocketVersion, connectEndpoint)}
q := u.Query()
q.Add("project", tc.project)
q.Add("zone", tc.zone)
q.Add("instance", tc.instanceName)
q.Add("interface", tc.nic)
q.Add("port", tc.port)
if tc.sid != "" {
q.Add("sid", tc.sid)
}
if tc.bytesReceived > tc.bytesAcked {
q.Add("ack", strconv.Itoa(int(tc.bytesReceived)))
}
u.RawQuery = q.Encode()
c, _, err := websocket.DefaultDialer.Dial(u.String(), http.Header{
"Origin": []string{origin},
"Sec-Websocket-Protocol": []string{subProtocolName},
"Authorization": []string{fmt.Sprintf("Bearer %s", ts.AccessToken)},
})
if err != nil {
return err
}
tc.websocketConn = c
tc.connected = true
return nil
}
// Close closes the connection
func (tc *TunnelConnection) Close() error {
err := tc.websocketConn.WriteMessage(websocket.CloseMessage, nil)
if err != nil {
return err
}
err = tc.websocketConn.Close()
if err != nil {
return err
}
tc.websocketConn = nil
return nil
}
func (tc *TunnelConnection) Read(p []byte) (n int, err error) {
_, msg, err := tc.websocketConn.ReadMessage()
if err != nil {
return 0, err
}
bytesRead := len(msg)
for k, v := range msg {
p[k] = v
}
return bytesRead, nil
}
func (tc *TunnelConnection) Write(b []byte) (n int, err error) {
err = tc.websocketConn.WriteMessage(websocket.BinaryMessage, b)
return len(b), err
}
func (tc *TunnelConnection) GetSid() string {
return tc.sid
}
func (tc *TunnelConnection) SetSid(sid string) {
tc.sid = sid
}
func WithProject(project string) TunnelConnectionOption {
return func(tc *TunnelConnection) {
tc.project = project
}
}
func WithTunnelReader(reader io.Reader) TunnelConnectionOption {
return func(tc *TunnelConnection) {
tc.reader = reader
}
}
func WithTunnelWriter(writer io.Writer) TunnelConnectionOption {
return func(tc *TunnelConnection) {
tc.writer = writer
}
}
func WithInstanceName(instanceName string) TunnelConnectionOption {
return func(tc *TunnelConnection) {
tc.instanceName = instanceName
}
}
func WithZone(zone string) TunnelConnectionOption {
return func(tc *TunnelConnection) {
tc.zone = zone
}
}
func WithPort(port string) TunnelConnectionOption {
return func(tc *TunnelConnection) {
tc.port = port
}
}
func WithNic(nic string) TunnelConnectionOption {
return func(tc *TunnelConnection) {
tc.nic = nic
}
}