forked from fitzy101/light-man
/
main.go
632 lines (562 loc) · 15 KB
/
main.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
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
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
// light-man is a tool for communicating with an Opengear Lighthouse instance
// via cli, utilising the REST API. Currently implemented are:
// add, delete, list, and shell.
//
// Written with go 1.9, however would probably run on earlier versions.
// To compile, navigate to the source folder and type 'make'. You'll need to
// install the dependencies with `go get ./...`.
package main
import (
"bytes"
"encoding/json"
"errors"
"flag"
"fmt"
"io"
"net/http"
"os"
"os/signal"
"regexp"
"strings"
"text/tabwriter"
"github.com/fitzy101/light-man/client"
"github.com/fitzy101/light-man/conf"
"github.com/fitzy101/light-man/types"
"golang.org/x/crypto/ssh"
)
var (
// Lighthouse vars.
lhaddress string
lhusername string
lhpassword string
lhtoken string
// Console Server vars.
address string
username string
password string
name string
bundle string
noauto bool
log bool
id string
smartgroup string
// Housekeeping vars.
command string
)
const (
dcommand = "the command to run with light-man"
daddress = "URL of the Lighthouse instance"
dnaddress = "FQDN or IP Address of the node"
dusername = "user name for a Lighthouse user (default is 'root')"
dpassword = "password for the Lighthouse user (default is 'default')"
dname = "name of the node to add"
dbundle = "name of the enrollment bundle"
dauto = "indicates the node should NOT be auto-approved on enrollment"
did = "the identifier for a node - find with the list command"
dsmartgroup = "the name of a smartgroup to filter the command"
dlog = "enable request logging to stdout"
nodeURI = "/nodes"
searchURI = "/search/nodes"
sgURI = "/nodes/smartgroups"
sshPort = 22
sshConn = "tcp"
)
func init() {
flag.StringVar(&command, "c", "", dcommand)
flag.StringVar(&address, "a", "", daddress)
flag.StringVar(&username, "u", "root", dusername)
flag.StringVar(&password, "p", "default", dpassword)
flag.StringVar(&name, "n", "", dname)
flag.StringVar(&bundle, "b", "", dbundle)
flag.StringVar(&id, "i", "", did)
flag.StringVar(&smartgroup, "g", "", dsmartgroup)
flag.BoolVar(&noauto, "no", false, dauto)
flag.BoolVar(&log, "log", false, dlog)
}
func usage() string {
var sbuff bytes.Buffer
sbuff.WriteString("Usage: light-man -c [COMMAND] [OPTIONS]...\n")
// configure
sbuff.WriteString("\tconfigure: set up light-man with your Lighthouse credentials\n")
sbuff.WriteString(fmt.Sprintf("\t\t-a: %s\n", daddress))
sbuff.WriteString(fmt.Sprintf("\t\t-u: %s\n", dusername))
sbuff.WriteString(fmt.Sprintf("\t\t-p: %s\n", dpassword))
// add
sbuff.WriteString("\tadd: add a new node to the Lighthouse\n")
sbuff.WriteString(fmt.Sprintf("\t\t-a: %s\n", dnaddress))
sbuff.WriteString(fmt.Sprintf("\t\t-u: %s\n", dusername))
sbuff.WriteString(fmt.Sprintf("\t\t-p: %s\n", dpassword))
sbuff.WriteString(fmt.Sprintf("\t\t-n: %s\n", dname))
sbuff.WriteString(fmt.Sprintf("\t\t-no: %s\n", dauto))
// list
sbuff.WriteString("\tlist: list all nodes on the Lighthouse\n")
sbuff.WriteString(fmt.Sprintf("\t\t-g: %s\n", dsmartgroup))
// delete
sbuff.WriteString("\tdelete: delete a node from the Lighthouse\n")
sbuff.WriteString(fmt.Sprintf("\t\t-i: %s\n", did))
// delete-all
sbuff.WriteString("\tdelete-all: delete all nodes from the Lighthouse\n")
sbuff.WriteString(fmt.Sprintf("\t\t-g: %s\n", dsmartgroup))
// shell
sbuff.WriteString("\tshell: get a port manager shell on the Lighthouse\n")
return sbuff.String()
}
func main() {
flag.Usage = func() {
exitErr(usage())
}
flag.Parse()
if len(os.Args) == 1 {
exitErr(usage())
}
// Check the required fields were provided.
if err := validate(); err != nil {
exitErr(err.Error())
}
// Catch any segfaults within runCommand().
defer func() {
if r := recover(); r != nil {
msg := fmt.Sprintf("Error running command.. check the Lighthouse is accessible or reconfigure light-man.")
exitErr(msg)
}
}()
msg, err := runCommand(command)
if err != nil {
exitErr(err.Error())
}
exitSuccess(msg)
}
func runCommand(command string) (string, error) {
if log {
client.LogLevel = client.LOGINFO
}
var msg string
switch command {
case "configure":
client.LhAddress = address
client.LhUsername = username
client.LhPassword = password
token, err := client.GetToken()
if err != nil {
return msg, err
}
msg, err := configure(address, username, password, token)
if err != nil {
return msg, err
}
return msg, nil
case "add":
if err := loadConfiguration(); err != nil {
return msg, err
}
msg, err := addNode(address, username, password, name, bundle, noauto)
if err != nil {
return msg, err
}
return msg, nil
case "list":
if err := loadConfiguration(); err != nil {
return msg, err
}
msg, err := listNodes()
if err != nil {
return msg, err
}
return msg, nil
case "delete":
if err := loadConfiguration(); err != nil {
return msg, err
}
msg, err := deleteNode()
if err != nil {
return msg, err
}
return msg, nil
case "shell":
if err := loadConfiguration(); err != nil {
return msg, err
}
msg, err := getShell()
if err != nil {
return msg, err
}
return msg, nil
case "delete-all":
if err := loadConfiguration(); err != nil {
return msg, err
}
msg, err := deleteAllNodes()
if err != nil {
return msg, err
}
return msg, nil
default:
return msg, fmt.Errorf("%s is not a valid command", command)
}
}
func validate() error {
if command == "" {
return errors.New("command (-c) must be provided")
}
// No args for list.
if command == "list" {
return nil
}
// ID required for delete.
if command == "delete" {
if id == "" {
return errors.New("id (-i) must be provided")
}
}
// Address required for configure and add.
if command == "add" || command == "configure" {
if address == "" {
return errors.New("address (-a) must be provided")
}
// Trim any trailing slash if we're configuring light-man,
// and force https.
if command == "configure" {
match, _ := regexp.MatchString(`^https://`, address)
if !match {
return errors.New("address must start with https://")
}
aL := len(address)
if address[aL-1:] == "/" {
address = address[:aL-1]
}
}
}
return nil
}
// configure sets up the light-man configuration file.
func configure(address, username, password, token string) (string, error) {
var ret string
configdir, err := conf.WriteConfig(address, username, password, token)
if err != nil {
return ret, err
}
ret = fmt.Sprintf("config saved to %s\n", configdir)
return ret, nil
}
func loadConfiguration() error {
add, user, pass, token, err := conf.LoadConfiguration()
if err != nil {
return err
}
// Setup the client package with the user data.
lhaddress = add
lhusername = user
lhpassword = pass
lhtoken = token
client.LhAddress = lhaddress
client.LhUsername = lhusername
client.LhPassword = lhpassword
client.LhToken = lhtoken
return nil
}
func exitSuccess(msg string) {
w := tabwriter.NewWriter(os.Stdout, 0, 8, 1, '\t', 1)
fmt.Fprintf(w, msg)
w.Flush()
os.Exit(0)
}
func exitErr(err string) {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
// addNode makes a POST request to the lighthouse including all of the new
// node information. This formats any error/response message to be friendly for
// the user.
func addNode(address, username, password, name, bundle string, approve bool) (string, error) {
var ret string
// Build the request body.
enrolBody := types.NodeEnrollmentBody{
Address: address,
Name: name,
Username: username,
Password: password,
AutoApprove: !approve, // user specifies if they dont want it
CallHome: false,
}
if bundle != "" {
enrolBody.Bundle = bundle
enrolBody.Hostname = name
enrolBody.CallHome = true
}
request := types.EnrollmentRequest{
Enrollment: enrolBody,
}
reqJSON, err := json.Marshal(&request)
if err != nil {
return ret, err
}
url, err := client.GetURL(nodeURI)
if err != nil {
return ret, err
}
req, err := client.BuildReq(&reqJSON, url, http.MethodPost, true)
rawResp, err := client.HTTPClient().Do(req)
if err != nil {
return ret, err
}
_, err = client.ParseReq(rawResp)
if err != nil {
return ret, err
}
return "Node added successfully\n", nil
}
// getAllNodes retrieves information for all nodes on the lighthouse.
func getAllNodes() (types.NodesListResponse, error) {
var ret types.NodesListResponse
// If a smartgroup name was specified, we need to perform a search first
// and append it onto the URI.
var url string
var err error
if smartgroup != "" {
searchID, err := getSearchID()
if err != nil {
return ret, err
}
searchQ := client.Parameters{
Name: "searchId",
Value: searchID,
}
url, err = client.GetURL(nodeURI, searchQ)
if err != nil {
return ret, err
}
} else {
url, err = client.GetURL(nodeURI)
if err != nil {
return ret, err
}
}
req, err := client.BuildReq(nil, url, http.MethodGet, true)
rawResp, err := client.HTTPClient().Do(req)
if err != nil {
return ret, err
}
body, err := client.ParseReq(rawResp)
if err != nil {
return ret, err
}
// Decode the response.
err = json.Unmarshal(body, &ret)
if err != nil {
return ret, err
}
return ret, nil
}
// listNodes returns a formatted output of a list of all nodes on the lighthouse.
func listNodes() (string, error) {
var ret string
list, err := getAllNodes()
if err != nil {
return ret, err
}
// Prettify the response for output.
if len(list.Nodes) == 0 {
ret = "No nodes to list\n"
return ret, nil
}
var out bytes.Buffer
out.WriteString("ID\tName\tModel\tStatus\tLHVPN.Address\tFW.Version\tConn.Status\tErrors\n")
for _, v := range list.Nodes {
out.WriteString(fmt.Sprintf("%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n",
v.ID,
v.Name,
v.Model,
v.Status,
v.LHVPNAddress,
v.Version,
v.RuntimeStatus.ConnectionStatus,
v.RuntimeStatus.ActionErr,
))
}
ret = out.String()
return ret, err
}
// deleteNode attempts to delete the node provided with -i.
func deleteNode() (string, error) {
var ret string
uri := fmt.Sprintf("%s/%s", nodeURI, id)
url, err := client.GetURL(uri)
if err != nil {
return ret, err
}
req, err := client.BuildReq(nil, url, http.MethodDelete, true)
rawResp, err := client.HTTPClient().Do(req)
if err != nil {
return ret, err
}
if _, err := client.ParseReq(rawResp); err != nil {
return ret, err
}
// Confirm the node was deleted.
if rawResp.StatusCode != 204 {
return ret, errors.New("Node was not able to be deleted")
}
ret = "Node deletion process started\n"
return ret, nil
}
// deleteAllNodes attempts to delete all nodes enrolled in lighthouse.
func deleteAllNodes() (string, error) {
var ret string
// First we need all nodes, so we can get their id.
list, err := getAllNodes()
if err != nil {
return ret, err
}
if len(list.Nodes) == 0 {
ret = "No nodes to delete\n"
return ret, nil
}
// Go through the list and delete all the nodes.
for _, v := range list.Nodes {
uri := fmt.Sprintf("%s/%s", nodeURI, v.ID)
url, err := client.GetURL(uri)
if err != nil {
return ret, err
}
req, err := client.BuildReq(nil, url, http.MethodDelete, true)
rawResp, err := client.HTTPClient().Do(req)
if err != nil {
return ret, err
}
if _, err := client.ParseReq(rawResp); err != nil {
return ret, err
}
// Confirm the node was deleted.
if rawResp.StatusCode != 204 {
return ret, fmt.Errorf("Node %s was not able to be deleted", v.ID)
}
}
ret = fmt.Sprintf("Node deletion process started for %v node(s)\n", len(list.Nodes))
return ret, nil
}
// getSSHAddr returns a formatted address for the ssh connection to the
// lighthouse.
func getSSHAddr() string {
// We only want the hostname of the LH.
add := strings.Replace(lhaddress, "https://", "", 1)
return fmt.Sprintf("%s:%v", add, sshPort)
}
// getShell puts the user into an ssh connection running the pmshell command
// on the lighthouse.
func getShell() (string, error) {
var ret string
// Start by making a new ssh session on the lighthouse.
sshConfig := &ssh.ClientConfig{
User: lhusername,
Auth: []ssh.AuthMethod{
ssh.Password(lhpassword),
},
HostKeyCallback: ssh.InsecureIgnoreHostKey(), // We're authing with credentials.
}
connection, err := ssh.Dial(sshConn, getSSHAddr(), sshConfig)
if err != nil {
return ret, fmt.Errorf("Failed to create a new shell session: %s", err)
}
session, err := connection.NewSession()
if err != nil {
return ret, fmt.Errorf("Failed to create a new shell session: %s", err)
}
defer session.Close()
// We'll need to create a PTY on the lighthouse to run the command.
modes := ssh.TerminalModes{
ssh.ECHO: 0,
ssh.TTY_OP_ISPEED: 14400,
ssh.TTY_OP_OSPEED: 14400,
}
if err := session.RequestPty("xterm", 160, 80, modes); err != nil {
return ret, fmt.Errorf("Failed to create a new shell session: %s", err)
}
// Pipe all stdout, stderr, stdin to/from the PTY.
stdin, err := session.StdinPipe()
if err != nil {
return ret, fmt.Errorf("Failed to create a new shell session: %s", err)
}
stdout, err := session.StdoutPipe()
if err != nil {
return ret, fmt.Errorf("Failed to create a new shell session: %s", err)
}
stderr, err := session.StderrPipe()
if err != nil {
return ret, fmt.Errorf("Failed to create a new shell session: %s", err)
}
// Keep them synchronised.
go io.Copy(stdin, os.Stdin)
go io.Copy(os.Stdout, stdout)
go io.Copy(os.Stderr, stderr)
// We'll need to catch SIGINT and SIGKILL to ensure the ssh session is closed.
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt, os.Kill)
go func() {
<-c
session.Close()
}()
// Now we can run the pmshell command
ret = "Shell session completed\n"
session.Run("pmshell")
return ret, nil
}
// getSearchID returns a searchID for a specified smartgroup.
func getSearchID() (string, error) {
// Unfortunately there isn't a GET smartgroup by name endpoint, so we
// need to enumerate them all to find the one we want.
var ret string
// Fetch all of the smart groups.
url, err := client.GetURL(sgURI)
if err != nil {
return ret, err
}
req, err := client.BuildReq(nil, url, http.MethodGet, true)
rawResp, err := client.HTTPClient().Do(req)
if err != nil {
return ret, err
}
body, err := client.ParseReq(rawResp)
if err != nil {
return ret, err
}
var b types.NodesSmartgroupResponse
err = json.Unmarshal(body, &b)
if err != nil {
return ret, err
}
// Now we need to find the smartgroupID, and from that the query.
var query string
for _, sg := range b.Smartgroups {
if strings.Compare(sg.Name, smartgroup) == 0 {
query = sg.Query
}
}
if query == "" {
return ret, nil
}
// Finally we can get a searchID.
param := client.Parameters{
Name: "json",
Value: query,
}
url, err = client.GetURL(searchURI, param)
if err != nil {
return ret, err
}
req, err = client.BuildReq(nil, url, http.MethodGet, true)
rawResp, err = client.HTTPClient().Do(req)
if err != nil {
return ret, err
}
body, err = client.ParseReq(rawResp)
if err != nil {
return ret, err
}
var bsearch types.SearchResponse
err = json.Unmarshal(body, &bsearch)
if err != nil {
return ret, err
}
ret = bsearch.SearchIDs.ID
return ret, nil
}