-
-
Notifications
You must be signed in to change notification settings - Fork 48
/
cmd_client.go
383 lines (332 loc) · 7.46 KB
/
cmd_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
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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
// cmd_client.go contains the core of the VPN-client
package main
import (
"bytes"
"context"
"encoding/json"
"flag"
"fmt"
"log"
"net/url"
"os"
"os/exec"
"strconv"
"strings"
"github.com/google/subcommands"
"github.com/gorilla/websocket"
"github.com/skx/simple-vpn/config"
"github.com/skx/simple-vpn/shared"
"github.com/songgao/water"
)
// clientCmd is the structure for this sub-command.
//
type clientCmd struct {
// The configuration file
config *config.Reader
}
//
// Glue for our sub-command-library.
//
func (*clientCmd) Name() string { return "client" }
func (*clientCmd) Synopsis() string { return "Start the VPN-client." }
func (*clientCmd) Usage() string {
return `client :
Launch the VPN-client.
`
}
//
// Flag setup
//
func (p *clientCmd) SetFlags(f *flag.FlagSet) {
}
func (p *clientCmd) configureClient(dev *water.Interface, ip string, subnet string, mtu int, gateway string) error {
//
// The MTU/Device as a string
//
mtuStr := fmt.Sprintf("%d", mtu)
devStr := dev.Name()
//
// Ensure we have the right mask for the client IP
//
fmt.Printf("Client IP is %s\n", ip)
if strings.Contains(ip, ":") {
ip += "/128"
} else {
ip += "/32"
}
//
// The commands we're going to execute
//
cmds := [][]string{
{"ip", "link", "set", "dev", devStr, "up"},
{"ip", "link", "set", "mtu", mtuStr, "dev", devStr},
{"ip", "addr", "add", ip, "dev", devStr},
{"ip", "route", "add", gateway, "dev", devStr},
{"ip", "route", "add", subnet, "via", gateway},
}
//
// For each command
//
for _, cmd := range cmds {
//
// Show what we're doing.
//
fmt.Printf("Running: '%s'\n", strings.Join(cmd, " "))
//
// Run the command
//
x := exec.Command(cmd[0], cmd[1:]...)
x.Stdout = os.Stdout
x.Stderr = os.Stderr
err := x.Run()
if err != nil {
fmt.Printf("Failed to run %s - %s",
strings.Join(cmd, " "), err.Error())
return err
}
}
return nil
}
//
// Entry-point.
//
func (p *clientCmd) Execute(_ context.Context, f *flag.FlagSet, _ ...interface{}) subcommands.ExitStatus {
//
// Ensure we have a configuration file.
//
if len(f.Args()) < 1 {
fmt.Printf("We expect a configuration-file to be specified.\n")
return subcommands.ExitFailure
}
//
// Parse the configuration file.
//
var err error
p.config, err = config.New(f.Args()[0])
if err != nil {
fmt.Printf("Failed to read the configuration file %s - %s\n", f.Args()[0], err.Error())
return subcommands.ExitFailure
}
//
// Get the end-point to which we're going to connect.
//
endPoint := p.config.Get("vpn")
if endPoint == "" {
fmt.Printf("The configuration file didn't include a vpn=... line\n")
fmt.Printf("We don't know where to connect! Aborting.\n")
return subcommands.ExitFailure
}
//
// Get the shared-secret.
//
key := p.config.Get("key")
if key == "" {
fmt.Printf("The configuration file didn't include key=... line\n")
fmt.Printf("That means authentication is impossible! Aborting.\n")
return subcommands.ExitFailure
}
//
// Get our client-name
//
name := p.config.Get("name")
if name == "" {
//
// If none is set then send the hostname.
//
name, _ = os.Hostname()
}
//
// Add our name/key to the connection URI.
//
// Note that the URL might contain "?" already. Unlikely, but
// certainly possible.
//
if strings.Contains(endPoint, "?") {
endPoint += "&"
} else {
endPoint += "?"
}
endPoint += "name=" + url.QueryEscape(name)
endPoint += "&"
endPoint += "key=" + url.QueryEscape(key)
//
// Connect to the remote host.
//
conn, _, err := websocket.DefaultDialer.Dial(endPoint, nil)
if err != nil {
fmt.Printf("Failed to connect to %s\n", endPoint)
fmt.Printf("%s\n", err.Error())
fmt.Printf("(The connection failed, or the key was bogus.)\n")
return 1
}
defer conn.Close()
//
// Now we're cooking.
//
var iface *water.Interface
//
// When we're disconnected we cleanup the interface.
//
defer func() {
if iface != nil {
iface.Close()
}
}()
//
// Setup command-handlers for adding routes, etc.
//
socket := shared.MakeSocket("0", conn, nil, nil)
//
// Init is the function which is received when we connect.
//
// This gives us our IP, MTU, etc.
//
socket.AddCommandHandler("init", func(args []string) error {
var err error
//
// We receive these arguments
//
// 1. subnet
// 2. ip address
// 3. mtu
// 4. gateway
//
subnetStr := args[0]
ipStr := args[1]
mtuStr := args[2]
gatewayStr := args[3]
mtu, err := strconv.Atoi(mtuStr)
if err != nil {
fmt.Printf("MTU was not a valid int: %s\n", err.Error())
os.Exit(1)
}
//
// Create the TUN device
//
var waterMode water.DeviceType
waterMode = water.TUN
iface, err = water.New(water.Config{
DeviceType: waterMode,
})
if err != nil {
fmt.Printf("Failed to create a new TUN device: %s\n", err.Error())
os.Exit(1)
}
//
// Now configure it.
//
err = p.configureClient(iface, ipStr, subnetStr, mtu, gatewayStr)
if err != nil {
panic(err)
}
//
// If we reached this point we're basically done.
//
// Launch the "up" script, if we can.
//
if p.config.Get("up") != "" {
//
// Setup the environment.
//
os.Setenv("DEVICE", iface.Name())
os.Setenv("CLIENT_IP", ipStr)
os.Setenv("SERVER_IP", gatewayStr)
os.Setenv("SUBNET", subnetStr)
os.Setenv("MTU", mtuStr)
//
// Launch the script.
//
cmd := p.config.Get("up")
x := exec.Command(cmd)
x.Stdout = os.Stdout
x.Stderr = os.Stderr
err = x.Run()
if err != nil {
fmt.Printf("Failed to run %s - %s",
cmd, err.Error())
}
}
//
// Now we start shuffling packets.
//
log.Printf("Configured interface, the VPN is up!")
err = socket.SetInterface(iface)
if err != nil {
fmt.Printf("Failed bind socket-magic to TUN device: %s\n", err.Error())
os.Exit(1)
}
//
// Send a command to the server, asking it to update all
// clients with the list of known-peers (and their IPs).
//
socket.SendCommand("refresh-peers", "now")
return nil
})
//
// This function is invoked when clients join/leave the VPN.
//
// It is the function which is called as a result of the server
// handling the `refresh` command that we sent at join-time.
//
socket.AddCommandHandler("update-peers", func(args []string) error {
fmt.Printf("Preparing to update peer-list\n")
//
// If the client has not defined a `peers` command then
// we can just return here.
//
cmd := p.config.Get("peers")
if cmd == "" {
fmt.Printf("Peer command is empty.\n")
return nil
}
//
// OK we have a command.
//
fmt.Printf("Updating peer-list now.\n")
//
// We're given an array of strings such as:
//
// "1.2.3.3\tsteve",
// "1.2.3.4\tgold",
//
// Convert that into a simple structure.
//
type Client struct {
Name string
IP string
}
//
// The thing we'll send
//
var connected []Client
//
// Populate, appropriately.
//
for _, ent := range args {
out := strings.Split(ent, "\t")
connected = append(connected, Client{Name: out[1], IP: out[0]})
}
//
// Convert to JSON.
//
obj, err := json.Marshal(connected)
if err != nil {
fmt.Printf("Failed to convert object to JSON: %s\n", err.Error())
return err
}
x := exec.Command(cmd)
x.Stdin = bytes.NewBuffer(obj)
x.Stdout = os.Stdout
x.Stderr = os.Stderr
err = x.Run()
if err != nil {
fmt.Printf("Failed to run %s - %s",
cmd, err.Error())
return err
}
return nil
})
socket.Serve(false)
socket.Wait()
return subcommands.ExitSuccess
}