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
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
|
//
// Copyright (C) 2016 Canonical Ltd
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 3 as
// published by the Free Software Foundation.
//
// 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 main
import (
"bufio"
"bytes"
"encoding/base64"
"encoding/json"
"fmt"
"log"
"math/rand"
"net"
"net/http"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"time"
)
const DefaultPassworthLength = 16
type wizardStep func(map[string]interface{}, *bufio.Reader, bool) error
// Go stores both IPv4 and IPv6 as [16]byte
// with IPv4 addresses stored in the end of the buffer
// in bytes 13..16
const ipv4Offset = net.IPv6len - net.IPv4len
var defaultIp = net.IPv4(10, 0, 60, 1)
// Utility function to read input and strip the trailing \n
var readUserInput = func (reader *bufio.Reader) string {
ret, err := reader.ReadString('\n')
if err != nil {
panic(err)
}
return strings.TrimRight(ret, "\n")
}
// Helper function to list network interfaces
func findExistingInterfaces(wifi bool) (wifis []string) {
// Use sysfs to get interfaces list
const sysNetPath = "/sys/class/net"
ifaces, err := net.Interfaces()
wifis = []string{}
if err == nil {
for _, iface := range ifaces {
if iface.Flags&net.FlagLoopback == 0 {
// The "wireless" subdirectory exists only for wireless interfaces
if _, err := os.Stat(filepath.Join(sysNetPath, iface.Name, "wireless")); os.IsNotExist(err) != wifi {
wifis = append(wifis, iface.Name)
}
}
}
}
return
}
func findFreeSubnet(startIp net.IP) (net.IP, error) {
curIp := startIp
addrs, err := net.InterfaceAddrs()
if err != nil {
return nil, err
}
// Start from startIp and increment the third octect every time
// until we found an IP which isn't assigned to any interface
for found := false; !found; {
// Cycle through all the assigned addresses
for _, addr := range addrs {
found = true
_, subnet, _ := net.ParseCIDR(addr.String())
// If busy, increment the third octect and retry
if subnet.Contains(curIp) {
found = false
if curIp[ipv4Offset+2] == 255 {
return nil, fmt.Errorf("No free netmask found")
}
curIp[ipv4Offset+2]++
break
}
}
}
return curIp, nil
}
func generatePassword(length int) string {
// base64 produces 4 byte for every 3 byte of input, rounded up
password := make([]byte, length / 4 * 3 + 3)
rand.Read(password)
return base64.StdEncoding.EncodeToString(password)[:length]
}
func askForPassword(reader *bufio.Reader) (string, error) {
fmt.Print("Please enter the WPA2 passphrase: ")
key := readUserInput(reader)
if len(key) < 8 || len(key) > 63 {
return "", fmt.Errorf("WPA2 passphrase must be between 8 and 63 characters")
}
return key, nil
}
var allSteps = [...]wizardStep{
// determine the WiFi interface
func(configuration map[string]interface{}, reader *bufio.Reader, nonInteractive bool) error {
ifaces := findExistingInterfaces(true)
if len(ifaces) == 0 {
return fmt.Errorf("There are no valid wireless network interfaces available")
} else if len(ifaces) == 1 {
fmt.Println("Automatically selected only available wireless network interface " + ifaces[0])
return nil
}
if nonInteractive {
fmt.Println("Selecting interface", ifaces[0])
configuration["wifi.interface"] = ifaces[0]
return nil
}
fmt.Print("Which wireless interface you want to use? ")
ifacesVerb := "are"
if len(ifaces) == 1 {
ifacesVerb = "is"
}
fmt.Printf("Available %s %s: ", ifacesVerb, strings.Join(ifaces, ", "))
iface := readUserInput(reader)
if re := regexp.MustCompile("^[[:alnum:]]+$"); !re.MatchString(iface) {
return fmt.Errorf("Invalid interface name '%s' given", iface)
}
configuration["wifi.interface"] = iface
return nil
},
// Ask for WiFi ESSID
func(configuration map[string]interface{}, reader *bufio.Reader, nonInteractive bool) error {
if nonInteractive {
configuration["wifi.ssid"] = "Ubuntu"
return nil
}
fmt.Print("Which SSID you want to use for the access point: ")
iface := readUserInput(reader)
if len(iface) == 0 || len(iface) > 31 {
return fmt.Errorf("ESSID length must be between 1 and 31 characters")
}
configuration["wifi.ssid"] = iface
return nil
},
// Select WiFi encryption type
func(configuration map[string]interface{}, reader *bufio.Reader, nonInteractive bool) error {
if nonInteractive {
configuration["wifi.security"] = "wpa2"
return nil
}
fmt.Print("Do you want to protect your network with a WPA2 password instead of staying open for everyone? (y/n) ")
switch resp := strings.ToLower(readUserInput(reader)); resp {
case "y":
configuration["wifi.security"] = "wpa2"
case "n":
configuration["wifi.security"] = "open"
default:
return fmt.Errorf("Invalid answer: %s", resp)
}
return nil
},
// If WPA2 is set, ask for valid password
func(configuration map[string]interface{}, reader *bufio.Reader, nonInteractive bool) error {
if configuration["wifi.security"] == "open" {
return nil
}
if nonInteractive {
// Generate a random 16 characters alphanumeric password
configuration["wifi.security-passphrase"] = generatePassword(DefaultPassworthLength)
return nil
}
// Ask the user for a valid password (min 8, max 63 chars)
if password, err := askForPassword(reader); err == nil {
configuration["wifi.security-passphrase"] = password
} else {
return err
}
return nil
},
// Configure WiFi AP IP address
func(configuration map[string]interface{}, reader *bufio.Reader, nonInteractive bool) error {
if nonInteractive {
wifiIp, err := findFreeSubnet(defaultIp)
if err != nil {
return err
}
fmt.Println("AccessPoint IP set to", wifiIp.String())
configuration["wifi.address"] = wifiIp.String()
configuration["wifi.netmask"] = "255.255.255.0"
return nil
}
fmt.Print("Insert the Access Point IP address: ")
inputIp := readUserInput(reader)
ipv4 := net.ParseIP(inputIp)
if ipv4 == nil {
return fmt.Errorf("Invalid IP address: %s", inputIp)
}
if !ipv4.IsGlobalUnicast() {
return fmt.Errorf("%s is a reserved IPv4 address", inputIp)
}
if ipv4.To4() == nil {
return fmt.Errorf("%s is not an IPv4 address", inputIp)
}
configuration["wifi.address"] = inputIp
configuration["wifi.netmask"] = ipv4.DefaultMask().String()
return nil
},
// Configure the DHCP pool
func(configuration map[string]interface{}, reader *bufio.Reader, nonInteractive bool) error {
if nonInteractive {
wifiIp := net.ParseIP(configuration["wifi.address"].(string))
// Set the DCHP in the range 2..199 with 198 total hosts
// leave about 50 hosts outside the pool for static addresses
// wifiIp[ipv4Offset + 3] is the last octect of the IP address
wifiIp[ipv4Offset+3] = 2
configuration["dhcp.range-start"] = wifiIp.String()
wifiIp[ipv4Offset+3] = 199
configuration["dhcp.range-stop"] = wifiIp.String()
return nil
}
var maxpoolsize byte
ipv4 := net.ParseIP(configuration["wifi.address"].(string))
if ipv4[ipv4Offset+3] <= 128 {
maxpoolsize = 254 - ipv4[ipv4Offset+3]
} else {
maxpoolsize = ipv4[ipv4Offset+3] - 1
}
fmt.Printf("How many host do you want your DHCP pool to hold to? (1-%d) ", maxpoolsize)
input := readUserInput(reader)
inputhost, err := strconv.ParseUint(input, 10, 8)
if err != nil {
return fmt.Errorf("Invalid answer: %s", input)
}
if byte(inputhost) > maxpoolsize {
return fmt.Errorf("%d is bigger than the maximum pool size %d", inputhost, maxpoolsize)
}
nhosts := byte(inputhost)
// Allocate the pool in the bigger half, trying to avoid overlap with access point IP
if octect3 := ipv4[ipv4Offset+3]; octect3 <= 128 {
ipv4[ipv4Offset+3] = octect3 + 1
configuration["dhcp.range-start"] = ipv4.String()
ipv4[ipv4Offset+3] = octect3 + nhosts
configuration["dhcp.range-stop"] = ipv4.String()
} else {
ipv4[ipv4Offset+3] = octect3 - nhosts
configuration["dhcp.range-start"] = ipv4.String()
ipv4[ipv4Offset+3] = octect3 - 1
configuration["dhcp.range-stop"] = ipv4.String()
}
return nil
},
// Enable or disable connection sharing
func(configuration map[string]interface{}, reader *bufio.Reader, nonInteractive bool) error {
if nonInteractive {
configuration["share.disabled"] = false
return nil
}
fmt.Print("Do you want to enable connection sharing? (y/n) ")
switch resp := strings.ToLower(readUserInput(reader)); resp {
case "y":
configuration["share.disabled"] = false
case "n":
configuration["share.disabled"] = true
default:
return fmt.Errorf("Invalid answer: %s", resp)
}
return nil
},
// Select the wired interface to share
func(configuration map[string]interface{}, reader *bufio.Reader, nonInteractive bool) error {
if nonInteractive {
configuration["share.disabled"] = true
procNetRoute, err := os.Open("/proc/net/route")
if err != nil {
return err
}
defer procNetRoute.Close()
var iface string
// Using something like math.MaxUint32 causes an overflow on
// some architectures so lets use just a high enough value
// for typical systems here.
minMetric := 100000
scanner := bufio.NewScanner(procNetRoute)
// Skip the first line with table header
scanner.Text()
for scanner.Scan() {
route := strings.Fields(scanner.Text())
if len(route) < 8 {
continue
}
// If we picked the interface already for the AP to operate on
// ignore it.
if route[0] == configuration["wifi.interface"] {
break
}
// A /proc/net/route line is in the form:
// iface destination gateway ...
// eth1 00000000 0155A8C0 ...
// look for a 0 destination (0.0.0.0) which is our default route
metric, err := strconv.Atoi(route[7])
if err != nil {
metric = 0
}
if route[1] == "00000000" && metric < minMetric {
iface = route[0]
minMetric = metric
break
}
}
if len(iface) == 0 {
configuration["share.disabled"] = true
} else {
fmt.Println("Selecting", iface, "for connection sharing")
configuration["share.disabled"] = false
configuration["share.network-interface"] = iface
}
return nil
}
if configuration["share.disabled"] == true {
return nil
}
ifaces := findExistingInterfaces(false)
if len(ifaces) == 0 {
fmt.Println("No network interface available which's connection can be shared. Disabling connection sharing.")
configuration["share.disabled"] = true
return nil
}
ifacesVerb := "are"
if len(ifaces) == 1 {
ifacesVerb = "is"
}
fmt.Println("Which network interface you want to use for connection sharing?")
fmt.Printf("Available %s %s: ", ifacesVerb, strings.Join(ifaces, ", "))
iface := readUserInput(reader)
if re := regexp.MustCompile("^[[:alnum:]]+$"); !re.MatchString(iface) {
return fmt.Errorf("Invalid interface name '%s' given", iface)
}
configuration["share.network-interface"] = iface
return nil
},
func(configuration map[string]interface{}, reader *bufio.Reader, nonInteractive bool) error {
if nonInteractive {
configuration["disabled"] = false
return nil
}
fmt.Print("Do you want to enable the AP now? (y/n) ")
switch resp := strings.ToLower(readUserInput(reader)); resp {
case "y":
configuration["disabled"] = false
fmt.Println("In order to get the AP correctly enabled you have to restart the backend service:")
fmt.Println(" $ systemctl restart snap.wifi-ap.backend")
case "n":
configuration["disabled"] = true
default:
return fmt.Errorf("Invalid answer: %s", resp)
}
return nil
},
}
// Use the REST API to set the configuration
func applyConfiguration(configuration map[string]interface{}) error {
for key, value := range configuration {
log.Printf("%v=%v\n", key, value)
}
json, err := json.Marshal(configuration)
if err != nil {
return err
}
response, err := sendHTTPRequest(getServiceConfigurationURI(), "POST", bytes.NewReader(json))
if err != nil {
return err
}
if response.StatusCode == http.StatusOK && response.Status == http.StatusText(http.StatusOK) {
fmt.Println("Configuration applied succesfully")
return nil
} else {
return fmt.Errorf("Failed to set configuration, service returned: %d (%s)\n", response.StatusCode, response.Status)
}
}
type wizardCommand struct {
Auto bool `long:"auto" description:"Automatically configure the AP"`
}
func (cmd *wizardCommand) Execute(args []string) error {
rand.Seed(time.Now().UnixNano())
// Setup some sane default values, we don't ask the user for everything
configuration := make(map[string]interface{})
reader := bufio.NewReader(os.Stdin)
for _, step := range allSteps {
for {
if err := step(configuration, reader, cmd.Auto); err != nil {
if cmd.Auto {
return err
}
fmt.Println("Error: ", err)
fmt.Print("Do you want to try again? (y/n) ")
answer := readUserInput(reader)
if strings.ToLower(answer) != "y" {
return err
}
} else {
// Good answer
break
}
}
}
return applyConfiguration(configuration)
}
func init() {
addCommand("wizard", "Start the interactive wizard configuration", "", &wizardCommand{})
}
|