/
server.go
1661 lines (1427 loc) · 41.5 KB
/
server.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
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"crypto/rand"
"crypto/rsa"
"crypto/sha256"
"crypto/x509"
"crypto/x509/pkix"
"encoding/base64"
"encoding/json"
"encoding/pem"
"fmt"
"github.com/RobinUS2/golang-jresp"
"github.com/julienschmidt/httprouter"
"github.com/nu7hatch/gouuid"
"github.com/spf13/cast"
"github.com/RobinUS2/indispenso/data_table"
"io/ioutil"
"math/big"
"net"
"net/http"
"os"
"strconv"
"strings"
"sync"
"time"
)
// Server methods (you probably only need one or two in HA failover mode)
type Server struct {
clientsMux sync.RWMutex
clients map[string]*RegisteredClient
Tags map[string]bool
tagsMux sync.RWMutex
userStore *UserStore
templateStore *TemplateStore
consensus *Consensus
executionCoordinator *ExecutionCoordinator
httpCheckStore *HttpCheckStore
authService *AuthService
notifications *NotificationManager
InstanceId string // Unique ID generated at startup of the server, used for re-authentication and client-side refresh after and update/restart
}
// Register client
func (s *Server) RegisterClient(clientId string, tags []string) {
s.clientsMux.RLock()
if s.clients[clientId] == nil {
s.clientsMux.RUnlock()
// Write lock
s.clientsMux.Lock()
s.clients[clientId] = newRegisteredClient(clientId)
s.clientsMux.Unlock()
log.Printf("Client %s registered with tags %s", clientId, tags)
} else {
s.clientsMux.RUnlock()
}
// Update client
s.clients[clientId].mux.Lock()
s.clients[clientId].LastPing = time.Now()
s.clients[clientId].Tags = tags
s.clients[clientId].mux.Unlock()
// Update tags
s.tagsMux.Lock()
for _, tag := range tags {
s.Tags[tag] = true
}
s.tagsMux.Unlock()
}
func (s *Server) GetClient(clientId string) *RegisteredClient {
s.clientsMux.Lock()
defer s.clientsMux.Unlock()
return s.clients[clientId]
}
// Scan for old clients
func (s *Server) CleanupClients() {
s.clientsMux.Lock()
for k, client := range s.clients {
if time.Now().Sub(client.LastPing).Seconds() > float64(CLIENT_PING_INTERVAL*5) {
// Disconnect
log.Printf("Client %s disconnected", client.ClientId)
delete(s.clients, k)
}
}
s.clientsMux.Unlock()
}
// Submit command to registered client using channel notify system
func (client *RegisteredClient) Submit(cmd *Cmd) {
client.mux.Lock()
// Command in pending list, this will be polled of within milliseconds
client.Cmds[cmd.Id] = cmd
// Keep track of command status
client.DispatchedCmds[cmd.Id] = cmd
client.mux.Unlock()
// Log
audit.Log(nil, "Execute", fmt.Sprintf("Command '%s' on client %s with id %s", cmd.Command, client.ClientId, cmd.Id))
// Signal for work
client.CmdChan <- true
}
// A client that is registered with the server
type RegisteredClient struct {
mux sync.RWMutex
ClientId string
AuthToken string `json:"-"` // Do not add to JSON
LastPing time.Time
Tags []string
// Dispatched commands to the client
DispatchedCmds map[string]*Cmd
// Pending commands
Cmds map[string]*Cmd
// Channel used to trigger the long poll to fire a command to the client
CmdChan chan bool `json:"-"`
}
// Get list of dispatched commands
// will automatically purge commands older than X days
func (c *RegisteredClient) GetDispatchedCmds() map[string]*Cmd {
// Max age
maxAge := time.Now().Unix() - (14 * 86400)
// Is this one dirty? Meaning it contains too old data?
dirty := false
// Placeholder of list
newMap := make(map[string]*Cmd, 0)
// Build list
c.mux.RLock()
for k, d := range c.DispatchedCmds {
if d.Created >= maxAge {
newMap[k] = d
} else {
dirty = true
}
}
c.mux.RUnlock()
// Swap?
if dirty {
c.mux.Lock()
if conf.Debug {
log.Printf("Cleaning up dispatched commands of client %s size went from %d to %d", c.ClientId, len(c.DispatchedCmds), len(newMap))
}
c.DispatchedCmds = newMap
c.mux.Unlock()
}
return newMap
}
// Does this register client have this tag?
func (c *RegisteredClient) HasTag(s string) bool {
if c.Tags == nil {
return false
}
if len(c.Tags) == 0 {
return false
}
for _, tag := range c.Tags {
if tag == s {
return true
}
}
return false
}
// Generate keys
func (s *Server) _prepareTlsKeys() error {
if _, err := os.Stat(conf.GetSslCertFile()); os.IsNotExist(err) {
if !conf.AutoGenerateCert {
log.Printf("Cannot locat certificate file(%s) doesn't exist, provide one or enable automatic self signed cert generation", conf.GetSslCertFile())
return err
}
privateKey, err := _readOrGeneratePrivateKey(conf.GetSslPrivateKeyFile())
if err != nil {
return err
}
return _generateCertificate(conf.GetSslCertFile(), privateKey, 365*24*time.Hour)
}
return nil
}
func _readOrGeneratePrivateKey(fileName string) (*rsa.PrivateKey, error) {
if _, err := os.Stat(fileName); os.IsNotExist(err) {
privateKey, _ := rsa.GenerateKey(rand.Reader, 2048)
keyOut, err := os.OpenFile(fileName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
defer keyOut.Close()
if err != nil {
log.Printf("failed to open %s for writing: %s", fileName, err)
return privateKey, err
}
pem.Encode(keyOut, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(privateKey)})
return privateKey, nil
} else {
log.Printf("Private key (%s) exists and will be used", fileName)
certArray, err := ioutil.ReadFile(fileName)
if err != nil {
return nil, err
}
block, _ := pem.Decode(certArray)
return x509.ParsePKCS1PrivateKey(block.Bytes)
}
}
/**
Function that provide Serial number for certificate.
The serial number is chosen by the CA which issued the certificate.
It is just written in the certificate. The CA can choose the serial
number in any way as it sees fit.
*/
func _getCertSerialNumber() *big.Int {
serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
if err != nil {
log.Printf("failed to generate serial number: %s", err)
}
return serialNumber
}
func _generateCertificateTmpl(subject pkix.Name, validPeriod time.Duration) x509.Certificate {
currentTime := time.Now()
return x509.Certificate{
SerialNumber: _getCertSerialNumber(),
Subject: subject,
NotBefore: currentTime,
NotAfter: currentTime.Add(validPeriod),
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
IsCA: false,
BasicConstraintsValid: true,
IPAddresses: []net.IP{net.IPv4(127, 0, 0, 1).To4()},
}
}
func _generateCertificate(fileName string, privateKey *rsa.PrivateKey, validPeriod time.Duration) error {
log.Println("Autogeneration of selfsigned certificate key...")
subject := pkix.Name{
Organization: []string{"Indispenso"},
Country: []string{"NL"},
CommonName: "ssl.indispenso.org",
OrganizationalUnit: []string{"IT"},
Province: []string{"Indispenso"},
Locality: []string{"Indispenso"},
}
tmpl := _generateCertificateTmpl(subject, validPeriod)
certBytes, err := x509.CreateCertificate(rand.Reader, &tmpl, &tmpl, &privateKey.PublicKey, privateKey)
if err != nil {
log.Printf("Failed to create certificate: %s\n", err)
return err
}
log.Println("Public key generated sucessfully")
certFile, err := os.Create(fileName)
if err != nil {
log.Printf("Cannot create cert file : %s\n", err)
return err
}
pem.Encode(certFile, &pem.Block{Type: "CERTIFICATE", Bytes: certBytes})
certFile.Close()
log.Printf("Successfully written certificate: %s\n", fileName)
return err
}
// Start server
func (s *Server) Start() bool {
// Users
s.userStore = newUserStore(conf.HomeFile("users.json"))
s.authService = createAuthService(s.userStore)
// Templates
s.templateStore = newTemplateStore()
// Consensus handler
s.consensus = newConsensus()
// Coordinator
s.executionCoordinator = newExecutionCoordinator()
// HTTP checks
s.httpCheckStore = newHttpCheckStore()
//Notifications
s.notifications = newNotificationManager()
// Print info
log.Printf("Starting server at https://localhost:%d/", conf.ServerPort)
// Start webserver
go func() {
router := httprouter.New()
// Homepage that redirects to /console
router.GET("/", Home)
// For uptime checks
router.GET("/ping", Ping)
// List tags
router.GET("/tags", GetTags)
// Client commands
router.GET("/client/:clientId/ping", ClientPing)
router.GET("/client/:clientId/cmds", ClientCmds)
router.PUT("/client/:clientId/cmd/:cmd/state", PutClientCmdState)
router.PUT("/client/:clientId/cmd/:cmd/logs", PutClientCmdLogs)
router.GET("/client/:clientId/cmd/:cmd/logs", GetClientCmdLogs)
router.POST("/client/:clientId/auth", PostClientAuth)
// Auth endpoint
router.POST("/auth", PostAuth)
// Templates
router.GET("/templates", GetTemplate)
router.POST("/template/:templateid/validation", PostTemplateValidation)
router.DELETE("/template/:templateid/validation/:id", DeleteTemplateValidation)
router.POST("/template", PostTemplate)
router.DELETE("/template", DeleteTemplate)
// Update password
router.PUT("/user/password", PutUserPassword)
// List clients (~ slaves)
router.GET("/clients", GetClients)
// List users
router.GET("/users", GetUsers)
// List user names by ids
router.GET("/users/names", GetUsersNames)
// Create user
router.POST("/user", PostUser)
// Remove user
router.DELETE("/user", DeleteUser)
//Change user
router.PUT("/user", PutUser)
// Consensus requests
router.POST("/consensus/request", PostConsensusRequest)
router.DELETE("/consensus/request", DeleteConsensusRequest)
router.POST("/consensus/approve", PostConsensusApprove)
router.GET("/consensus/pending", GetConsensusPending)
// Dispatched commands list
router.POST("/dispatched", data_table.DefaultStoreHandler(DispatchedCmdQuery))
// Http checks
router.GET("/http-check/:id", GetHttpCheck)
router.GET("/http-checks", GetHttpChecks)
router.POST("/http-check", PostHttpCheck)
router.DELETE("/http-check", DeleteHttpCheck)
// Two factor auth
router.GET("/user/2fa", GetUser2fa)
router.PUT("/user/2fa", PutUser2fa)
// Backup
router.GET("/backup/configs.zip", GetBackupConfigs)
// Console endpoint for interface
router.ServeFiles("/console/*filepath", http.Dir("console"))
// Auto generate key
if err := s._prepareTlsKeys(); err != nil {
log.Printf("TLS preperation failed due to : %s", err)
log.Fatal("Unable to start server")
}
// Start server
log.Printf("Failed to start server %v", http.ListenAndServeTLS(fmt.Sprintf(":%d", conf.ServerPort), conf.GetSslCertFile(), conf.GetSslPrivateKeyFile(), router))
}()
// Minutely cleanups etc
go func() {
c := time.Tick(1 * time.Minute)
for _ = range c {
server.CleanupClients()
}
}()
return true
}
func (s *Server) SetupNotifications(conf *Conf) {
for _, n := range conf.GetNotifications() {
if !n.IsEnabled() {
continue
}
if err := n.IsValid(); err != nil {
log.Printf("Invalid notification service config: %s", err)
}
service, err := n.GetService()
if err != nil {
log.Printf("Cannot instantiate notification service: %s", err)
}
s.notifications.register(service)
log.Printf("Succesfully registerd notification %s", n.GetName())
}
}
func createAuthService(us *UserStore) *AuthService {
as := newAuthService(us, DefaultFirstFactorAuth, newGAuthAuthenticator())
if conf.EnableLdap {
as.appendFirstFactor(newLdapAuthenticator(conf.ldapConfig, us))
}
return as
}
// Get logs from dispatched job
func GetClientCmdLogs(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
jr := jresp.NewJsonResp()
if !authUser(r) {
jr.Error("User not authorized for GetClientCmdLogs ")
fmt.Fprint(w, jr.ToString(conf.Debug))
return
}
// Get client
registeredClient := server.GetClient(ps.ByName("clientId"))
if registeredClient == nil {
jr.Error("Client not registered")
fmt.Fprint(w, jr.ToString(conf.Debug))
return
}
// Command
cmdId := ps.ByName("cmd")
registeredClient.mux.RLock()
cmd := registeredClient.DispatchedCmds[cmdId]
registeredClient.mux.RUnlock()
if cmd == nil {
jr.Error("Command not found")
fmt.Fprint(w, jr.ToString(conf.Debug))
return
}
jr.Set("log_output", cmd.BufOutput)
jr.Set("log_error", cmd.BufOutputErr)
jr.OK()
fmt.Fprint(w, jr.ToString(conf.Debug))
}
// Enable user two factor
func PutUser2fa(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
jr := jresp.NewJsonResp()
if !authUser(r) {
jr.Error("User not authorized for PutUser2fa")
fmt.Fprint(w, jr.ToString(conf.Debug))
return
}
// User
user := getUser(r)
if len(user.TotpSecret) < 1 {
jr.Error("Two factor authentication not setup")
fmt.Fprint(w, jr.ToString(conf.Debug))
return
}
if user.HasTwoFactor() {
jr.Error("Two factor authentication already setup")
fmt.Fprint(w, jr.ToString(conf.Debug))
return
}
// Gather values
value1 := r.PostFormValue("token_1")
value2 := r.PostFormValue("token_2")
if value1 == value2 || strings.TrimSpace(value1) == strings.TrimSpace(value2) {
jr.Error("The two values should not be the same. Wait for the next token (in a few seconds) to show up and provide that.")
fmt.Fprint(w, jr.ToString(conf.Debug))
return
}
// Validate
valid1, _ := user.ValidateTotp(value1)
valid2, _ := user.ValidateTotp(value2)
res := valid1 && valid2 // Both must match
if res == false {
jr.Error("The two tokens do not match. Make sure that the clock is set correctly on your mobile device and the Indispenso server.")
fmt.Fprint(w, jr.ToString(conf.Debug))
return
}
// Enable
if res {
user.TotpSecretValidated = true
user.AuthType |= AUTH_TYPE_TWO_FACTOR
server.userStore.save()
}
jr.Set("enabled", res)
jr.OK()
fmt.Fprint(w, jr.ToString(conf.Debug))
}
// Get user two factor data
func GetUser2fa(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
jr := jresp.NewJsonResp()
if !authUser(r) {
jr.Error("User not authorized for GetUser2fa")
fmt.Fprint(w, jr.ToString(conf.Debug))
return
}
// User
user := getUser(r)
if user.HasTwoFactor() {
jr.Error("Two factor authentication already setup")
fmt.Fprint(w, jr.ToString(conf.Debug))
return
}
if err := user.GenerateOTPSecret(); err != nil {
jr.Error(err.Error())
fmt.Fprint(w, jr.ToString(conf.Debug))
return
}
server.userStore.save()
qrImageBytes, err := user.TotpQrImage()
if err != nil {
jr.Error(err.Error())
fmt.Fprint(w, jr.ToString(conf.Debug))
return
}
jr.Set("Secret", user.TotpSecret)
jr.Set("Png", qrImageBytes)
jr.OK()
fmt.Fprint(w, jr.ToString(conf.Debug))
}
func DispatchedCmdQuery(tableStore *data_table.DefaultStore) *data_table.DefaultStore {
// Fetch and create
server.clientsMux.RLock()
for _, client := range server.clients {
for _, d := range client.GetDispatchedCmds() {
commandTime := time.Unix(d.Created, 0)
row := make(map[string]interface{})
row["created"] = commandTime.Format("2006-01-02 15:04:05")
template := server.templateStore.Get(d.TemplateId)
if template != nil {
row["template"] = template.Title
} else {
row["template"] = "-"
}
user := server.userStore.ById(d.RequestUserId)
if user != nil {
row["user"] = user.Username
} else {
row["user"] = "-"
}
row["client"] = client.ClientId
row["state"] = d.State
row["link"] = fmt.Sprintf("logs?id=%s&client=%s", d.Id, client.ClientId)
rowObj := tableStore.CreateRow(row)
if time.Since(commandTime).Hours() > 24 {
rowObj.RowClass = "history-old"
}
tableStore.AddRow(rowObj)
}
}
server.clientsMux.RUnlock()
return tableStore
}
// Get pending execution request
func GetConsensusPending(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
jr := jresp.NewJsonResp()
if !authUser(r) {
jr.Error("User not authorized for GetConsensusPending")
fmt.Fprint(w, jr.ToString(conf.Debug))
return
}
user := getUser(r)
server.consensus.pendingMux.RLock()
pending := make([]*ConsensusRequest, 0)
work := make([]*ConsensusRequest, 0)
for _, req := range server.consensus.Pending {
// Ignore already executed
if req.Executed {
continue
}
// Ignore self
if req.RequestUserId == user.Id {
pending = append(pending, req)
continue
}
// Voted?
if req.ApproveUserIds[user.Id] == true {
pending = append(pending, req)
continue
}
work = append(work, req)
}
jr.Set("requests", pending)
jr.Set("server_instance_id", server.InstanceId)
jr.Set("work", work)
server.consensus.pendingMux.RUnlock()
jr.OK()
fmt.Fprint(w, jr.ToString(conf.Debug))
}
// Approve execution request
func PostConsensusApprove(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
jr := jresp.NewJsonResp()
if !authUser(r) {
jr.Error("User not authorized for PostConsensusApprove")
fmt.Fprint(w, jr.ToString(conf.Debug))
return
}
user := getUser(r)
if !user.HasRole("approver") {
jr.Error("User not allowed for PostConsensusApprove")
fmt.Fprint(w, jr.ToString(conf.Debug))
return
}
// Vote
id := strings.TrimSpace(r.PostFormValue("id"))
req := server.consensus.Get(id)
if req == nil {
jr.Error("Request not found")
fmt.Fprint(w, jr.ToString(conf.Debug))
return
}
res := req.Approve(user)
server.consensus.save()
jr.Set("approved", res)
jr.OK()
fmt.Fprint(w, jr.ToString(conf.Debug))
}
// Cancel execution request
func DeleteConsensusRequest(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
jr := jresp.NewJsonResp()
if !authUser(r) {
jr.Error("User not authorized for DeleteConsensusRequest")
fmt.Fprint(w, jr.ToString(conf.Debug))
return
}
user := getUser(r)
if !user.HasRole("requester") {
jr.Error("User not allowed to DeleteConsensusRequest")
fmt.Fprint(w, jr.ToString(conf.Debug))
return
}
// Get template
id := strings.TrimSpace(r.URL.Query().Get("id"))
req := server.consensus.Get(id)
if req == nil {
jr.Error("Request not found")
fmt.Fprint(w, jr.ToString(conf.Debug))
return
}
// Did we request this? Or are we admin
isAdmin := user.HasRole("admin")
isCreator := req.RequestUserId == user.Id
if !isAdmin && !isCreator {
jr.Error("Only the creator or admins can cancel a request")
fmt.Fprint(w, jr.ToString(conf.Debug))
return
}
// Create request
res := req.Cancel(user)
server.consensus.save()
jr.Set("cancelled", res)
jr.OK()
fmt.Fprint(w, jr.ToString(conf.Debug))
}
// Create execution request
func PostConsensusRequest(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
jr := jresp.NewJsonResp()
if !authUser(r) {
jr.Error("User not authorized for PostConsensusRequest")
fmt.Fprint(w, jr.ToString(conf.Debug))
return
}
// Are we allow to request execution?
user := getUser(r)
if !user.HasRole("requester") {
jr.Error("User not allowed to PostConsensusRequest")
fmt.Fprint(w, jr.ToString(conf.Debug))
return
}
// Verify two factor for, so that a hacked account can not request or execute anything without getting access to the 2fa device
if res, _ := user.ValidateTotp(r.PostFormValue("totp")); res == false {
jr.Error("Invalid two factor token")
fmt.Fprint(w, jr.ToString(conf.Debug))
return
}
// Reason
reason := strings.TrimSpace(r.PostFormValue("reason"))
if len(reason) < 4 {
jr.Error("Please provide a valid reason")
fmt.Fprint(w, jr.ToString(conf.Debug))
return
}
// Template
templateId := strings.TrimSpace(r.PostFormValue("template"))
clientIds := strings.Split(strings.TrimSpace(r.PostFormValue("clients")), ",")
// Create request
cr := server.consensus.AddRequest(templateId, clientIds, user, reason)
cr.AddCallback(consensusRequestFinishedNotification)
cr.check() // Check whether it can run straight away
server.consensus.save()
jr.OK()
fmt.Fprint(w, jr.ToString(conf.Debug))
}
func consensusRequestFinishedNotification(consensusRequest *ConsensusRequest) {
msg := fmt.Sprintf("Consesnsus request(id: %s) finished within %d s", consensusRequest.Id, consensusRequest.CompleteTime-consensusRequest.StartTime)
server.notifications.Notify(&Message{Type: EXECUTION_DONE, Content: msg, Url: conf.ServerRequest("/console/#!history")})
}
// Create validation rule for templates
func PostTemplateValidation(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
jr := jresp.NewJsonResp()
if !authUser(r) {
jr.Error("User not authorized for PostTemplateValidation")
fmt.Fprint(w, jr.ToString(conf.Debug))
return
}
// Get template
id := ps.ByName("templateid")
template := server.templateStore.Get(id)
if template == nil {
jr.Error("Template not found")
fmt.Fprint(w, jr.ToString(conf.Debug))
return
}
// Input
txt := r.PostFormValue("text")
isFatal := r.PostFormValue("fatal") == "1"
mustContain := r.PostFormValue("must_contain") == "1"
streamId := 1 // Default process output stream only
// Text must have length
if len(strings.TrimSpace(txt)) < 1 {
jr.Error("Text can not be empty")
fmt.Fprint(w, jr.ToString(conf.Debug))
return
}
// Create rule
rule := newExecutionValidation(txt, isFatal, mustContain, streamId)
// Add rule
template.AddValidationRule(rule)
// Save
res := server.templateStore.save()
// Done
jr.Set("saved", res)
jr.OK()
fmt.Fprint(w, jr.ToString(conf.Debug))
}
// Delete validation rule from template
func DeleteTemplateValidation(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
jr := jresp.NewJsonResp()
if !authUser(r) {
jr.Error("User not authorized for DeleteTemplateValidation")
fmt.Fprint(w, jr.ToString(conf.Debug))
return
}
// Get template
templateId := ps.ByName("templateid")
template := server.templateStore.Get(templateId)
if template == nil {
jr.Error("Template not found")
fmt.Fprint(w, jr.ToString(conf.Debug))
return
}
// Validaton rule id
id := ps.ByName("id")
// Delete rule
template.DeleteValidationRule(id)
// Save
res := server.templateStore.save()
// Done
jr.Set("saved", res)
jr.OK()
fmt.Fprint(w, jr.ToString(conf.Debug))
}
// Get templates
func GetTemplate(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
jr := jresp.NewJsonResp()
if !authUser(r) {
jr.Error("User not authorized for GetTemplate")
fmt.Fprint(w, jr.ToString(conf.Debug))
return
}
server.templateStore.templateMux.RLock()
jr.Set("templates", server.templateStore.Templates)
server.templateStore.templateMux.RUnlock()
jr.OK()
fmt.Fprint(w, jr.ToString(conf.Debug))
}
// Create template
func PostTemplate(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
jr := jresp.NewJsonResp()
if !authUser(r) {
jr.Error("User not authorized for PostTemplate")
fmt.Fprint(w, jr.ToString(conf.Debug))
return
}
user := getUser(r)
if !user.HasRole("admin") {
jr.Error("User not allowed to PostTemplate")
fmt.Fprint(w, jr.ToString(conf.Debug))
return
}
title := strings.TrimSpace(r.PostFormValue("title"))
description := strings.TrimSpace(r.PostFormValue("description"))
command := r.PostFormValue("command")
includedTags := r.PostFormValue("includedTags")
excludedTags := r.PostFormValue("excludedTags")
executionStrategyStr := r.PostFormValue("executionStrategy")
// Create strategy
var executionStrategy *ExecutionStrategy
switch executionStrategyStr {
case "simple":
executionStrategy = newExecutionStrategy(SimpleExecutionStrategy)
break
case "one-test":
executionStrategy = newExecutionStrategy(OneTestExecutionStrategy)
break
case "rolling":
executionStrategy = newExecutionStrategy(RollingExecutionStrategy)
break
case "exponential-rolling":
executionStrategy = newExecutionStrategy(ExponentialRollingExecutionStrategy)
break
default:
jr.Error("Strategy not found")
fmt.Fprint(w, jr.ToString(conf.Debug))
return
}
// Minimum authorizations
minAuthStr := strings.TrimSpace(r.PostFormValue("minAuth"))
minAuth, minAuthE := strconv.ParseInt(minAuthStr, 10, 0)
if len(minAuthStr) < 1 {
jr.Error("Fill in min auth")
fmt.Fprint(w, jr.ToString(conf.Debug))
return
} else if minAuthE != nil {
jr.Error(fmt.Sprintf("%s", minAuthE))
fmt.Fprint(w, jr.ToString(conf.Debug))
return
} else if minAuth < 1 {
jr.Error("Min auth must be at least 1")
fmt.Fprint(w, jr.ToString(conf.Debug))
return
}
// Timeout
timeoutStr := strings.TrimSpace(r.PostFormValue("timeout"))
timeout, timeoutE := strconv.ParseInt(timeoutStr, 10, 0)
if len(timeoutStr) < 1 {
jr.Error("Fill in timeout")
fmt.Fprint(w, jr.ToString(conf.Debug))
return
} else if timeoutE != nil {
jr.Error(fmt.Sprintf("%s", timeoutE))
fmt.Fprint(w, jr.ToString(conf.Debug))
return
} else if timeout < 1 {
jr.Error("Timeout must be at least 1 second")
fmt.Fprint(w, jr.ToString(conf.Debug))
return
}
// Validate template
template := newTemplate(title, description, command, true, strings.Split(includedTags, ","), strings.Split(excludedTags, ","), uint(minAuth), int(timeout), executionStrategy)
valid, err := template.IsValid()
if !valid {
jr.Error(fmt.Sprintf("%s", err))
fmt.Fprint(w, jr.ToString(conf.Debug))
return
}
server.templateStore.Add(template)
server.templateStore.save()
jr.Set("template", template)
jr.Set("saved", true)
jr.OK()
fmt.Fprint(w, jr.ToString(conf.Debug))
}
// Login
func PostAuth(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
jr := jresp.NewJsonResp()
authReq := &AuthRequest{
login: strings.TrimSpace(r.PostFormValue("username")),
credential: strings.TrimSpace(r.PostFormValue("password")),
token: strings.TrimSpace(r.PostFormValue("2fa")),
}
user, err := server.authService.authUser(authReq)
if err != nil {
log.Printf("%s\n", err)
jr.Error("Username / password / two-factor combination invalid") // Message must be constant to not leak information
fmt.Fprint(w, jr.ToString(conf.Debug))
return
}
// Start setssion
token := user.StartSession()
user.TouchSession(getIp(r))
server.userStore.save() // Call save to persist token
// Return token
jr.Set("session_token", token)
// User roles
roles := make([]string, 0)
for role := range user.Roles {
roles = append(roles, role)
}
jr.Set("user_roles", roles)
jr.Set("user_id", user.Id)
jr.Set("two_factor_enabled", user.HasTwoFactor())
jr.OK()
fmt.Fprint(w, jr.ToString(conf.Debug))
}
// List of all tags