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
384
385
386
387
388
|
// Copyright (C) 2018-2021 LEAP
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package vpn
import (
"errors"
"fmt"
"io/ioutil"
"log"
"os"
"path"
"path/filepath"
"strconv"
"strings"
"0xacab.org/leap/bitmask-vpn/pkg/config"
"0xacab.org/leap/shapeshifter"
)
const (
openvpnManagementAddr = "127.0.0.1"
openvpnManagementPort = "6061"
)
// StartVPN for provider
func (b *Bitmask) StartVPN(provider string) error {
if !b.CanStartVPN() {
return errors.New("BUG: cannot start vpn")
}
var err error
b.certPemPath, err = b.getCert()
if err != nil {
return err
}
b.openvpnArgs, err = b.bonafide.GetOpenvpnArgs()
if err != nil {
return err
}
return b.startOpenVPN()
}
func (b *Bitmask) CanStartVPN() bool {
/* FIXME this is not enough. We should check, if provider needs
* credentials, if we have a valid token, otherwise remove it and
make sure that we're asking for the credentials input */
return !b.bonafide.NeedsCredentials()
}
func (b *Bitmask) startTransport(host string) (proxy string, err error) {
// TODO configure port if not available
proxy = "127.0.0.1:4430"
if b.shapes != nil {
return proxy, nil
}
gateways, err := b.bonafide.GetGateways(b.transport)
if err != nil {
return "", err
}
if len(gateways) == 0 {
log.Printf("No gateway for transport %s in provider", b.transport)
return "", nil
}
for _, gw := range gateways {
if gw.Host != host {
continue
}
if _, ok := gw.Options["cert"]; !ok {
continue
}
log.Println("Selected Gateway:", gw.Host, gw.IPAddress)
b.shapes = &shapeshifter.ShapeShifter{
Cert: gw.Options["cert"],
Target: gw.IPAddress + ":" + gw.Ports[0],
SocksAddr: proxy,
}
go b.listenShapeErr()
if iatMode, ok := gw.Options["iat-mode"]; ok {
b.shapes.IatMode, err = strconv.Atoi(iatMode)
if err != nil {
b.shapes.IatMode = 0
}
}
err = b.shapes.Open()
if err != nil {
log.Printf("Can't connect to transport %s: %v", b.transport, err)
continue
}
log.Println("Connected via obfs4 to", gw.IPAddress, "(", gw.Host, ")")
return proxy, nil
}
return "", fmt.Errorf("No working gateway for transport %s: %v", b.transport, err)
}
func (b *Bitmask) listenShapeErr() {
ch := b.shapes.GetErrorChannel()
for {
err, more := <-ch
if !more {
return
}
log.Printf("Error from shappeshifter: %v", err)
}
}
func (b *Bitmask) startOpenVPN() error {
arg := []string{}
b.statusCh <- Starting
if b.GetTransport() == "obfs4" {
gateways, err := b.bonafide.GetGateways("obfs4")
if err != nil {
return err
}
if len(gateways) == 0 {
log.Printf("ERROR No gateway for transport %s in provider", b.transport)
return errors.New("ERROR: cannot find any gateway for selected transport")
}
gw := gateways[0]
proxy, err := b.startTransport(gw.Host)
if err != nil {
return err
}
b.ptGateway = gw
err = b.launch.firewallStart(gateways)
if err != nil {
return err
}
proxyArgs := strings.Split(proxy, ":")
// TODO pass UDP flag
arg = append(arg, "--remote", proxyArgs[0], proxyArgs[1], "tcp4")
arg = append(arg, "--route", gw.IPAddress, "255.255.255.255", "net_gateway")
} else {
arg = b.openvpnArgs
log.Println("args passed to bitmask-root:", arg)
gateways, err := b.bonafide.GetGateways("openvpn")
if err != nil {
return err
}
err = b.launch.firewallStart(gateways)
if err != nil {
return err
}
for _, gw := range gateways {
for _, port := range gw.Ports {
if port != "53" {
if b.udp {
os.Setenv("UDP", "1")
arg = append(arg, "--remote", gw.IPAddress, port, "udp4")
} else {
os.Setenv("UDP", "0")
arg = append(arg, "--remote", gw.IPAddress, port, "tcp4")
}
}
}
}
}
arg = append(arg,
"--verb", "3",
"--management-client",
"--management", openvpnManagementAddr, openvpnManagementPort,
"--ca", b.getTempCaCertPath(),
"--cert", b.certPemPath,
"--key", b.certPemPath,
"--persist-tun")
/* persist-tun is needed for reconnects */
return b.launch.openvpnStart(arg...)
}
func (b *Bitmask) getCert() (certPath string, err error) {
log.Println("Getting certificate...")
failed := false
persistentCertFile := filepath.Join(config.Path, strings.ToLower(config.Provider)+".pem")
if _, err := os.Stat(persistentCertFile); !os.IsNotExist(err) && isValidCert(persistentCertFile) {
// reuse cert. for the moment we're not writing one there, this is
// only to allow users to get certs off-band and place them there
// as a last-resort fallback for circumvention.
certPath = persistentCertFile
err = nil
} else {
// download one fresh
certPath = b.getTempCertPemPath()
if _, err := os.Stat(certPath); os.IsNotExist(err) {
log.Println("Fetching certificate to", certPath)
cert, err := b.bonafide.GetPemCertificate()
if err != nil {
log.Println(err)
failed = true
}
err = ioutil.WriteFile(certPath, cert, 0600)
if err != nil {
failed = true
}
}
}
if failed || !isValidCert(certPath) {
d := config.APIURL[8 : len(config.APIURL)-1]
logDnsLookup(d)
cert, err := b.bonafide.GetPemCertificateNoDNS()
if cert != nil {
log.Println("Successfully did certificate bypass")
err = nil
} else {
err = errors.New("Cannot get vpn certificate")
}
err = ioutil.WriteFile(certPath, cert, 0600)
if err != nil {
failed = true
}
}
return certPath, err
}
// Explicit call to GetGateways, to be able to fetch them all before starting the vpn
func (b *Bitmask) fetchGateways() {
log.Println("Fetching gateways...")
_, err := b.bonafide.GetAllGateways(b.transport)
if err != nil {
log.Println("ERROR Cannot fetch gateways")
}
}
// StopVPN or cancel
func (b *Bitmask) StopVPN() error {
err := b.launch.firewallStop()
if err != nil {
return err
}
if b.shapes != nil {
b.shapes.Close()
b.shapes = nil
}
return b.launch.openvpnStop()
}
// Reconnect to the VPN
func (b *Bitmask) Reconnect() error {
if !b.CanStartVPN() {
return errors.New("BUG: cannot start vpn")
}
status, err := b.GetStatus()
if err != nil {
return err
}
log.Println("DEBUG Reconnecting")
if status != Off {
b.statusCh <- Stopping
if b.shapes != nil {
b.shapes.Close()
b.shapes = nil
}
err = b.launch.openvpnStop()
if err != nil {
return err
}
}
err = b.launch.firewallStop()
// FIXME - there's a window in which we might leak traffic here!
if err != nil {
return err
}
return b.startOpenVPN()
}
// ReloadFirewall restarts the firewall
func (b *Bitmask) ReloadFirewall() error {
err := b.launch.firewallStop()
if err != nil {
return err
}
status, err := b.GetStatus()
if err != nil {
return err
}
if status != Off {
gateways, err := b.bonafide.GetAllGateways("any")
if err != nil {
return err
}
return b.launch.firewallStart(gateways)
}
return nil
}
// GetStatus returns the VPN status
func (b *Bitmask) GetStatus() (string, error) {
status := Off
if b.isFailed() {
status = Failed
} else {
status, err := b.getOpenvpnState()
if err != nil {
status = Off
}
if status == Off && b.launch.firewallIsUp() {
return Failed, nil
}
}
return status, nil
}
func (b *Bitmask) InstallHelpers() error {
// TODO use pickle module from here
return nil
}
// VPNCheck returns if the helpers are installed and up to date and if polkit is running
func (b *Bitmask) VPNCheck() (helpers bool, privilege bool, err error) {
return b.launch.check()
}
func (b *Bitmask) ListLocationFullness(transport string) map[string]float64 {
return b.bonafide.ListLocationFullness(transport)
}
func (b *Bitmask) ListLocationLabels(transport string) map[string][]string {
return b.bonafide.ListLocationLabels(transport)
}
// UseGateway selects a gateway, by label, as the default gateway
func (b *Bitmask) UseGateway(label string) {
b.bonafide.SetManualGateway(label)
}
// UseAutomaticGateway sets the gateway to be selected automatically
// best gateway will be used
func (b *Bitmask) UseAutomaticGateway() {
b.bonafide.SetAutomaticGateway()
}
// SetTransport selects an obfuscation transport to use
func (b *Bitmask) SetTransport(t string) error {
if t != "openvpn" && t != "obfs4" {
return fmt.Errorf("Transport %s not implemented", t)
}
log.Println("Setting transport to", t)
// compare and set string looks strange, but if assigning directly
// we're getting some kind of corruption with the transport string.
// I suspect something's
// not quite right with the c<->go char pointers handling.
if t == "obfs4" {
b.transport = "obfs4"
} else if t == "openvpn" {
b.transport = "openvpn"
}
return nil
}
// GetTransport gets the obfuscation transport to use. Only obfs4 available for now.
func (b *Bitmask) GetTransport() string {
if b.transport == "obfs4" {
return "obfs4"
} else {
return "openvpn"
}
}
func (b *Bitmask) getTempCertPemPath() string {
return path.Join(b.tempdir, "openvpn.pem")
}
func (b *Bitmask) getTempCaCertPath() string {
return path.Join(b.tempdir, "cacert.pem")
}
|