This repository was archived by the owner on Feb 25, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathmiddleware.go
More file actions
1180 lines (1044 loc) · 43.7 KB
/
middleware.go
File metadata and controls
1180 lines (1044 loc) · 43.7 KB
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 middleware emits events with data from services running on the base.
package middleware
import (
"bufio"
"encoding/json"
"fmt"
"log"
"os/exec"
"regexp"
"strings"
"time"
"github.com/digitalbitbox/bitbox-base/middleware/src/authentication"
"github.com/digitalbitbox/bitbox-base/middleware/src/configuration"
"github.com/digitalbitbox/bitbox-base/middleware/src/handlers"
"github.com/digitalbitbox/bitbox-base/middleware/src/hsm"
"github.com/digitalbitbox/bitbox-base/middleware/src/ipcnotification"
"github.com/digitalbitbox/bitbox-base/middleware/src/prometheus"
"github.com/digitalbitbox/bitbox-base/middleware/src/redis"
"github.com/digitalbitbox/bitbox-base/middleware/src/rpcmessages"
"github.com/digitalbitbox/bitbox02-api-go/api/firmware"
"github.com/digitalbitbox/bitbox02-api-go/api/firmware/messages"
"github.com/digitalbitbox/bitbox02-api-go/util/semver"
"golang.org/x/crypto/bcrypt"
)
// UserAuthStruct holds the structure that is written into the redis middleware:auth key's value.
type UserAuthStruct struct {
BCryptedPassword string `json:"password"`
Role string `json:"role"`
}
// initialAdminPassword is the default password that allows login when setting up a base.
const initialAdminPassword = "ICanHasPasword?"
// Middleware connects to services on the base with provided parameters and emits events for the handler.
type Middleware struct {
config configuration.Configuration
events chan handlers.Event
prometheusClient prometheus.Client
redisClient redis.Redis
jwtAuth *authentication.JwtAuth
serviceInfo rpcmessages.GetServiceInfoResponse
baseUpdateProgress rpcmessages.GetBaseUpdateProgressResponse
baseUpdateAvailable rpcmessages.IsBaseUpdateAvailableResponse
baseVersion *semver.SemVer
// Saves state for the setup process
isMiddlewarePasswordSet bool
isBaseSetupDone bool
hsm *hsm.HSM
hsmFirmware *firmware.Device
}
// GetMiddlewareVersion returns the Middleware Version for the `GET /version` endpoint.
func (middleware *Middleware) GetMiddlewareVersion() string {
return middleware.config.GetMiddlewareVersion()
}
// NewMiddleware returns a new instance of the middleware.
//
// hsmFirmware let's you talk to the HSM. NOTE: it the HSM could not be connected, this is nil. The
// middleware must be able to run and serve RPC calls without the HSM present.
func NewMiddleware(config configuration.Configuration, hsm *hsm.HSM) (*Middleware, error) {
middleware := &Middleware{
config: config,
//TODO(TheCharlatan) find a better way to increase the channel size
events: make(chan handlers.Event), //the channel size needs to be increased every time we had an extra endpoint
serviceInfo: rpcmessages.GetServiceInfoResponse{},
baseUpdateProgress: rpcmessages.GetBaseUpdateProgressResponse{
State: rpcmessages.UpdateNotInProgress,
ProgressPercentage: 0,
ProgressDownloadedKiB: 0,
},
isMiddlewarePasswordSet: false,
baseUpdateAvailable: rpcmessages.IsBaseUpdateAvailableResponse{
ErrorResponse: &rpcmessages.ErrorResponse{Success: true},
UpdateAvailable: false,
},
baseVersion: semver.NewSemVer(0, 0, 0),
hsm: hsm,
}
middleware.prometheusClient = prometheus.NewClient(middleware.config.GetPrometheusURL())
if !middleware.config.IsRedisMock() {
middleware.redisClient = redis.NewClient(middleware.config.GetRedisPort())
} else {
middleware.redisClient = redis.NewMockClient("")
}
// Initialize the HSM firmware connection and install firmware upgrade if available
if hsm != nil {
middleware.initHSM()
}
err := middleware.checkMiddlewareSetup()
if err != nil {
log.Println("failed to update the middleware password set flag")
return nil, err
}
if !middleware.isMiddlewarePasswordSet {
usersMap := make(map[string]UserAuthStruct)
bcryptedPassword, err := bcrypt.GenerateFromPassword([]byte(initialAdminPassword), 12)
if err != nil {
log.Println("Failed to generate new standard password")
return nil, err
}
usersMap["admin"] = UserAuthStruct{BCryptedPassword: string(bcryptedPassword), Role: "admin"}
authStructureString, err := json.Marshal(&usersMap)
if err != nil {
log.Println("Unable to marshal auth structure map")
return nil, err
}
err = middleware.redisClient.SetString(redis.MiddlewareAuth, string(authStructureString))
if err != nil {
log.Println("Unable to initialize auth data structure")
return nil, err
}
}
middleware.jwtAuth, err = authentication.NewJwtAuth()
// return if there is an error, this should not really happen though on our device and in our dev environments, low entropy is usually common in embedded environments
if err != nil {
return nil, err
}
return middleware, nil
}
// IsBaseUpdateAvailable indicates if a Base firmeware is available and returns information about the update
func (middleware *Middleware) IsBaseUpdateAvailable() rpcmessages.IsBaseUpdateAvailableResponse {
return middleware.baseUpdateAvailable
}
// rpcLoop gets new data from the various rpc connections of the middleware and emits events if new data is available
func (middleware *Middleware) rpcLoop() {
for {
if middleware.didServiceInfoChange() {
middleware.events <- handlers.Event{
Identifier: []byte(rpcmessages.OpServiceInfoChanged),
QueueIfNoClient: false,
}
}
time.Sleep(5 * time.Second)
}
}
// updateCheckLoop repeatedly checks for information about new Base image updates
// When an update is available it's
func (middleware *Middleware) updateCheckLoop() {
// This time is chosen arbitrary, but the time should be not too high for users to be notified
// not to long after the update release and not too low to avoid to frequent update checks.
const timeBetweenUpdateChecks time.Duration = 30 * time.Minute
for {
updateInfo, err := getBaseUpdateInfo(middleware.config.GetImageUpdateInfoURL())
if err != nil {
log.Printf("Could not GET update info: %s\n", err)
time.Sleep(timeBetweenUpdateChecks)
continue
}
newVersion, err := semver.NewSemVerFromString(updateInfo.Version)
if err != nil {
log.Printf("Could not parse update info version as SemVer: %s\n", err)
time.Sleep(timeBetweenUpdateChecks)
continue
}
if !middleware.baseVersion.AtLeast(newVersion) {
log.Printf("A Base image update is available from version %s to %s.\n", middleware.baseVersion.String(), newVersion.String())
middleware.baseUpdateAvailable.UpdateAvailable = true
middleware.baseUpdateAvailable.UpdateInfo = updateInfo
middleware.events <- handlers.Event{
Identifier: []byte(rpcmessages.OpBaseUpdateIsAvailable),
QueueIfNoClient: false,
}
}
time.Sleep(timeBetweenUpdateChecks)
}
}
// hsmHeartbeatLoop
func (middleware *Middleware) hsmHeartbeatLoop() {
for {
// TODO(@0xB10C) fetch the `stateCode` and `descriptionCode` from redis keys set byt the supervisor
err := middleware.hsmFirmware.BitBoxBaseHeartbeat(messages.BitBoxBaseHeartbeatRequest_IDLE, messages.BitBoxBaseHeartbeatRequest_EMPTY)
if err != nil {
log.Printf("Received an error from the HSM: %s\n", err)
time.Sleep(time.Second)
continue
}
// Send a heartbeat every 5 seconds. The HSM watchdog's timeout is 60 seconds
time.Sleep(5 * time.Second)
}
}
// Start gives a trigger for the handler to start the rpc event loop
func (middleware *Middleware) Start() <-chan handlers.Event {
if middleware.hsmFirmware != nil {
go middleware.hsmHeartbeatLoop()
}
go middleware.rpcLoop()
err := middleware.setHSMConfig()
if err != nil {
log.Printf("Error: could not set the HSM config: %s", err)
}
// before the updateCheckLoop is started the Middleware needes the Base version
baseVersion, err := middleware.redisClient.GetString(redis.BaseVersion)
if err != nil {
log.Printf("Error: could not get the Base version from Redis: %s", err)
}
baseSemVersion, err := semver.NewSemVerFromString(baseVersion)
if err != nil {
log.Printf("Error: could not parse the Base version as semver: %s", err)
}
middleware.baseVersion = baseSemVersion
log.Printf("Current Base image version is %s.\n", middleware.baseVersion.String())
go middleware.updateCheckLoop()
notificationReader, err := ipcnotification.NewReader(middleware.config.GetNotificationNamedPipePath())
if err != nil {
log.Printf("Error creating new IPC notification reader: %s", err)
// TODO: set base system status to ERROR
} else {
go middleware.ipcNotificationLoop(notificationReader)
}
return middleware.events
}
// ipcNotificationLoop waits for
func (middleware *Middleware) ipcNotificationLoop(reader *ipcnotification.Reader) {
const supportedNotificationVersion int = 1
notifications := reader.Notifications()
for {
notification := <-notifications
if notification.Version != supportedNotificationVersion {
log.Printf("Dropping IPC notification with unsupported version: %s\n", notification.String())
}
log.Printf("Received notification with topic '%s': %v\n", notification.Topic, notification.Payload)
switch notification.Topic {
case "mender-update":
if success, ok := ipcnotification.ParseMenderUpdatePayload(notification.Payload); ok {
switch success {
case true:
middleware.events <- handlers.Event{
Identifier: []byte(rpcmessages.OpBaseUpdateSuccess),
QueueIfNoClient: true,
}
case false:
middleware.events <- handlers.Event{
Identifier: []byte(rpcmessages.OpBaseUpdateFailure),
QueueIfNoClient: true,
}
}
} else {
log.Printf("Could not parse %s notification payload: %v\n", notification.Topic, notification.Payload)
}
default:
log.Printf("Dropping IPC notification with unknown topic: %s\n", notification.String())
}
}
}
// ResyncBitcoin returns a ErrorResponse struct in response to a rpcserver request
func (middleware *Middleware) ResyncBitcoin() rpcmessages.ErrorResponse {
log.Println("executing full bitcoin resync via the cmd script")
out, err := middleware.runBBBCmdScript([]string{"bitcoind", "resync"})
if err != nil {
errorCode := handleBBBScriptErrorCode(out, err, nil)
return rpcmessages.ErrorResponse{
Success: false,
Message: strings.Join(out, "\n"),
Code: errorCode,
}
}
return rpcmessages.ErrorResponse{Success: true}
}
// ReindexBitcoin returns a ErrorResponse struct in response to a rpcserver request
func (middleware *Middleware) ReindexBitcoin() rpcmessages.ErrorResponse {
log.Println("executing full bitcoin resync via the cmd script")
out, err := middleware.runBBBCmdScript([]string{"bitcoind", "reindex"})
if err != nil {
errorCode := handleBBBScriptErrorCode(out, err, nil)
return rpcmessages.ErrorResponse{
Success: false,
Message: strings.Join(out, "\n"),
Code: errorCode,
}
}
return rpcmessages.ErrorResponse{Success: true}
}
// SystemEnv returns a new GetEnvResponse struct with the values as read from the environment
func (middleware *Middleware) SystemEnv() rpcmessages.GetEnvResponse {
response := rpcmessages.GetEnvResponse{Network: middleware.config.GetNetwork(), ElectrsRPCPort: middleware.config.GetElectrsRPCPort()}
return response
}
// SetupStatus returns the current status in the setup process as a SetupStatusResponse struct. This includes the middleware password set boolean and the base setup boolean.
func (middleware *Middleware) SetupStatus() rpcmessages.SetupStatusResponse {
return rpcmessages.SetupStatusResponse{MiddlewarePasswordSet: middleware.isMiddlewarePasswordSet, BaseSetup: middleware.isBaseSetupDone}
}
// InitialAdminPassword is a getter that returns the constant initialAdminPassword string
// This password is only valid for authentication until the admin user changes it.
func (middleware *Middleware) InitialAdminPassword() string {
return initialAdminPassword
}
// BackupSysconfig creates a backup of the system configuration onto a flashdrive.
// 1. Check if one and only one valid flashdrive is plugged in
// 2. Mount the flashdrive
// 3. Backup the system configuration
// 4. Unmount the flashdrive
func (middleware *Middleware) BackupSysconfig() (response rpcmessages.ErrorResponse) {
response = middleware.mountFlashdrive()
if !response.Success {
return response
}
// It's crucial that mounted flashdrives get unmounted.
defer func() {
unmountResponse := middleware.unmountFlashdrive()
// In case the backing up the system configuration fails the error message should
// be preserved. If the backup was successful, but the unmouting fails, then the
// ErrorCode and message should be overwritten.
if response.Success {
response = unmountResponse // overrites the backup response
}
}()
log.Println("Executing a backup of the system config via the cmd script")
out, err := middleware.runBBBCmdScript([]string{"backup", "sysconfig"})
if err != nil {
errorCode := handleBBBScriptErrorCode(out, err, []rpcmessages.ErrorCode{
rpcmessages.ErrorBackupSysconfigNotAMountpoint,
})
return rpcmessages.ErrorResponse{
Success: false,
Message: strings.Join(out, "\n"),
Code: errorCode,
}
}
return rpcmessages.ErrorResponse{Success: true}
}
// BackupHSMSecret returns a ErrorResponse struct in response to a rpcserver request
func (middleware *Middleware) BackupHSMSecret() rpcmessages.ErrorResponse {
log.Println("Executing a backup of the c-lightning hsm_secret via the cmd script")
out, err := middleware.runBBBCmdScript([]string{"backup", "hsm_secret"})
if err != nil {
errorCode := handleBBBScriptErrorCode(out, err, nil)
return rpcmessages.ErrorResponse{
Success: false,
Message: strings.Join(out, "\n"),
Code: errorCode,
}
}
return rpcmessages.ErrorResponse{Success: true}
}
// RestoreSysconfig restores a backup of the system configuration from the flashdrive.
// 1. Check if one and only one valid flashdrive is plugged in
// 2. Mount the flashdrive
// 3. Restore the system configuration (currently not choosable)
// 4. Unmount the flashdrive
func (middleware *Middleware) RestoreSysconfig() (response rpcmessages.ErrorResponse) {
response = middleware.mountFlashdrive()
if !response.Success {
return response
}
// It's crucial that mounted flashdrives get unmounted.
defer func() {
unmountResponse := middleware.unmountFlashdrive()
// In case the restoring up the system configuration fails the error message should
// be preserved. If the backup was successful, but the unmouting fails, then the
// ErrorCode and message should be overwritten.
if response.Success {
response = unmountResponse // overrites the backup response
}
}()
log.Println("Executing a restore of the system config via the cmd script")
out, err := middleware.runBBBCmdScript([]string{"restore", "sysconfig"})
if err != nil {
errorCode := handleBBBScriptErrorCode(out, err, []rpcmessages.ErrorCode{
rpcmessages.ErrorRestoreSysconfigBackupNotFound,
})
return rpcmessages.ErrorResponse{
Success: false,
Message: strings.Join(out, "\n"),
Code: errorCode,
}
}
return rpcmessages.ErrorResponse{Success: true}
}
// RestoreHSMSecret returns a ErrorResponse struct in response to a rpcserver request
func (middleware *Middleware) RestoreHSMSecret() rpcmessages.ErrorResponse {
log.Println("Executing a restore of the c-lightning hsm_secret via the cmd script")
out, err := middleware.runBBBCmdScript([]string{"restore", "hsm_secret"})
if err != nil {
errorCode := handleBBBScriptErrorCode(out, err, nil)
return rpcmessages.ErrorResponse{
Success: false,
Message: strings.Join(out, "\n"),
Code: errorCode,
}
}
return rpcmessages.ErrorResponse{Success: true}
}
// UserAuthenticate returns an ErrorResponse struct in response to a rpcserver request.
// To check if the user should be authenticated from default values, the bool 'isMiddlewarePasswordSet' is read from redis
func (middleware *Middleware) UserAuthenticate(args rpcmessages.UserAuthenticateArgs) rpcmessages.UserAuthenticateResponse {
// isMiddlewarePasswordSet checks if the base is run the first time.
err := middleware.checkMiddlewareSetup()
if err != nil {
return rpcmessages.UserAuthenticateResponse{
ErrorResponse: &rpcmessages.ErrorResponse{
Success: false,
Message: "authentication failed, redis error",
Code: rpcmessages.ErrorAuthenticationFailed,
},
}
}
usersMap, err := middleware.getAuthStructure()
if err != nil {
return rpcmessages.UserAuthenticateResponse{
ErrorResponse: &rpcmessages.ErrorResponse{
Success: false,
Message: "authentication unsuccessful, see middleware logs for more information",
Code: rpcmessages.ErrorAuthenticationFailed,
},
}
}
if _, ok := usersMap[args.Username]; !ok {
log.Printf("User %s not found in database", args.Username)
//TODO: Once we support multiple users work over the ErrorAuthenticationUsernameNotFound ErrorResponse message. It reveals information about the database.
return rpcmessages.UserAuthenticateResponse{
ErrorResponse: &rpcmessages.ErrorResponse{
Success: false,
Message: "authentication unsuccessful, username not found",
Code: rpcmessages.ErrorAuthenticationUsernameNotFound,
},
}
}
passwordFromStorage := usersMap[args.Username].BCryptedPassword
err = bcrypt.CompareHashAndPassword([]byte(passwordFromStorage), []byte(args.Password))
if err != nil {
log.Println("Hash and password did not match")
return rpcmessages.UserAuthenticateResponse{
ErrorResponse: &rpcmessages.ErrorResponse{
Success: false,
Message: "authentication unsuccessful, incorrect password",
Code: rpcmessages.ErrorAuthenticationPasswordIncorrect,
},
}
}
jwtTokenStr, err := middleware.jwtAuth.GenerateToken(args.Username)
if err != nil {
return rpcmessages.UserAuthenticateResponse{
ErrorResponse: &rpcmessages.ErrorResponse{
Success: false,
Message: "authentication unsuccessful, jwt error",
Code: rpcmessages.ErrorAuthenticationFailed,
},
}
}
return rpcmessages.UserAuthenticateResponse{
ErrorResponse: &rpcmessages.ErrorResponse{
Success: true,
},
Token: jwtTokenStr,
}
}
// UserChangePassword returns an ErrorResponse struct in response to a rpcserver request
// The function first validates the current password with redis, then replaces it with the new password.
// Passwords need to be longer than or equal to 8 chars.
func (middleware *Middleware) UserChangePassword(args rpcmessages.UserChangePasswordArgs) rpcmessages.ErrorResponse {
if len(args.NewPassword) < 8 {
return rpcmessages.ErrorResponse{
Success: false,
Message: "password change unsuccessful, the password needs to be at least 8 characters in length",
Code: rpcmessages.ErrorPasswordTooShort,
}
}
usersMap, err := middleware.getAuthStructure()
if err != nil {
return rpcmessages.ErrorResponse{
Success: false,
Message: "authentication unsuccessful, see middleware logs for more information",
Code: rpcmessages.ErrorAuthenticationFailed,
}
}
//TODO: Once we support multiple users work over the ErrorPasswordChangeUsernameNotExist message. It reveals information about the database.
if _, ok := usersMap[args.Username]; !ok {
return rpcmessages.ErrorResponse{
Success: false,
Message: "username does not exist",
Code: rpcmessages.ErrorPasswordChangeUsernameNotExist,
}
}
passwordFromStorage := usersMap[args.Username].BCryptedPassword
err = bcrypt.CompareHashAndPassword([]byte(passwordFromStorage), []byte(args.Password))
if err != nil {
log.Println("Hash and password did not match")
return rpcmessages.ErrorResponse{
Success: false,
Message: "password change unsuccessful, current password was incorrect",
Code: rpcmessages.ErrorPasswordChangePasswordIncorrect,
}
}
bcryptedPassword, err := bcrypt.GenerateFromPassword([]byte(args.NewPassword), 12)
if err != nil {
return rpcmessages.ErrorResponse{
Success: false,
Message: "password change unsuccessful",
Code: rpcmessages.ErrorPasswordChangeFailed,
}
}
userAuthSecrets := usersMap[args.Username]
userAuthSecrets.BCryptedPassword = string(bcryptedPassword)
userAuthSecrets.Role = "admin"
usersMap[args.Username] = userAuthSecrets
usersMapByteStr, err := json.Marshal(usersMap)
if err != nil {
log.Println("Failed marshaling the new user data for redis")
return rpcmessages.ErrorResponse{
Success: false,
Message: "password change unsuccessful",
Code: rpcmessages.ErrorPasswordChangeFailed,
}
}
err = middleware.redisClient.SetString(redis.MiddlewareAuth, string(usersMapByteStr))
if err != nil {
log.Println("Failed committing the new password to redis")
return rpcmessages.ErrorResponse{
Success: false,
Message: "password change unsuccessful",
Code: rpcmessages.ErrorPasswordChangeFailed,
}
}
if !middleware.isMiddlewarePasswordSet {
err := middleware.redisClient.SetString(redis.MiddlewarePasswordSet, "1")
if err != nil {
log.Println("Failed setting middleware password set to true")
}
middleware.isMiddlewarePasswordSet = true // the change of the admin password completes the setup process (for now)
}
return rpcmessages.ErrorResponse{Success: true}
}
// ValidateToken validates a jwt token string and returns an error if not valid and nil otherwise.
func (middleware *Middleware) ValidateToken(token string) error {
return middleware.jwtAuth.ValidateToken(token)
}
// SetHostname sets the systems hostname
func (middleware *Middleware) SetHostname(args rpcmessages.SetHostnameArgs) rpcmessages.ErrorResponse {
log.Println("Setting the hostname via the config script")
var r = regexp.MustCompile(`^[a-z][a-z0-9-]{0,22}[a-z0-9]$`)
hostname := args.Hostname
if r.MatchString(hostname) {
out, err := middleware.runBBBConfigScript([]string{"set", "hostname", hostname})
if err != nil {
errorCode := handleBBBScriptErrorCode(out, err, []rpcmessages.ErrorCode{
rpcmessages.ErrorSetHostnameInvalidValue,
})
return rpcmessages.ErrorResponse{
Success: false,
Message: strings.Join(out, "\n"),
Code: errorCode,
}
}
err = middleware.setHSMConfig()
if err != nil {
log.Printf("Error: could not set the HSM config: %s", err)
}
return rpcmessages.ErrorResponse{Success: true}
}
return rpcmessages.ErrorResponse{Success: false, Message: "invalid hostname"}
}
// EnableTor enables/disables the tor.service and configures bitcoind and lightningd based on the passed ToggleSettingArgsEnable/Disable argument
// and returns a ErrorResponse indicating if the call was successful.
func (middleware *Middleware) EnableTor(toggleAction rpcmessages.ToggleSettingArgs) rpcmessages.ErrorResponse {
log.Printf("Executing 'Enable Tor: %t' via the config script.\n", toggleAction.ToggleSetting)
out, err := middleware.runBBBConfigScript([]string{determineEnableValue(toggleAction), "tor"})
if err != nil {
errorCode := handleBBBScriptErrorCode(out, err, nil)
return rpcmessages.ErrorResponse{
Success: false,
Message: strings.Join(out, "\n"),
Code: errorCode,
}
}
return rpcmessages.ErrorResponse{Success: true}
}
// EnableTorMiddleware enables/disables the tor hidden service for the middleware based on the passed ToggleSettingArgsEnable/Disable argument
// and returns a ErrorResponse indicating if the call was successful.
func (middleware *Middleware) EnableTorMiddleware(toggleAction rpcmessages.ToggleSettingArgs) rpcmessages.ErrorResponse {
log.Printf("Executing 'Enable Tor for middleware: %t' via the config script.\n", toggleAction.ToggleSetting)
out, err := middleware.runBBBConfigScript([]string{determineEnableValue(toggleAction), "tor_bbbmiddleware"})
if err != nil {
errorCode := handleBBBScriptErrorCode(out, err, nil)
return rpcmessages.ErrorResponse{
Success: false,
Message: strings.Join(out, "\n"),
Code: errorCode,
}
}
return rpcmessages.ErrorResponse{Success: true}
}
// EnableTorElectrs enables/disables the tor hidden service for electrs based on the passed ToggleSettingArgsEnable/Disable argument
// and returns a ErrorResponse indicating if the call was successful.
func (middleware *Middleware) EnableTorElectrs(toggleAction rpcmessages.ToggleSettingArgs) rpcmessages.ErrorResponse {
log.Printf("Executing 'Enable Tor for electrs: %t' via the config script.\n", toggleAction.ToggleSetting)
out, err := middleware.runBBBConfigScript([]string{determineEnableValue(toggleAction), "tor_electrs"})
if err != nil {
errorCode := handleBBBScriptErrorCode(out, err, nil)
return rpcmessages.ErrorResponse{
Success: false,
Message: strings.Join(out, "\n"),
Code: errorCode,
}
}
return rpcmessages.ErrorResponse{Success: true}
}
// EnableTorSSH enables/disables the tor hidden service for ssh based on the passed ToggleSettingArgsEnable/Disable argument
// and returns a ErrorResponse indicating if the call was successful.
func (middleware *Middleware) EnableTorSSH(toggleAction rpcmessages.ToggleSettingArgs) rpcmessages.ErrorResponse {
log.Printf("Executing 'Enable Tor for ssh: %t' via the config script.\n", toggleAction.ToggleSetting)
out, err := middleware.runBBBConfigScript([]string{determineEnableValue(toggleAction), "tor_ssh"})
if err != nil {
errorCode := handleBBBScriptErrorCode(out, err, nil)
return rpcmessages.ErrorResponse{
Success: false,
Message: strings.Join(out, "\n"),
Code: errorCode,
}
}
return rpcmessages.ErrorResponse{Success: true}
}
// EnableClearnetIBD enables/disables the initial block download over clearnet based on the passed ToggleSettingArgsEnable/Disable argument
func (middleware *Middleware) EnableClearnetIBD(toggleAction rpcmessages.ToggleSettingArgs) rpcmessages.ErrorResponse {
log.Printf("Executing 'Enable clearnet IBD: %t' via the config script.\n", toggleAction.ToggleSetting)
out, err := middleware.runBBBConfigScript([]string{determineEnableValue(toggleAction), "bitcoin_ibd_clearnet"})
if err != nil {
errorCode := handleBBBScriptErrorCode(out, err, []rpcmessages.ErrorCode{
rpcmessages.ErrorSetNeedsTwoArguments,
})
return rpcmessages.ErrorResponse{
Success: false,
Message: strings.Join(out, "\n"),
Code: errorCode,
}
}
return rpcmessages.ErrorResponse{Success: true}
}
// ShutdownBase shuts the Base down.
// The shutdown is executed in a goroutine with a delay of a few seconds.
// Prior to starting the goroutine the path for the `shutdown` executable is checked.
// If the executable is found, a ErrorResponse indicating success is returned.
// Otherwise a ExecutableNotFound Code is returned.
func (middleware *Middleware) ShutdownBase() rpcmessages.ErrorResponse {
const shutdownDelay time.Duration = 5 * time.Second
log.Printf("Shutting down the Base in %s\n", shutdownDelay)
if middleware.config.IsRedisMock() {
return rpcmessages.ErrorResponse{Success: true}
}
_, err := exec.LookPath("shutdown")
if err != nil {
return rpcmessages.ErrorResponse{
Success: false,
Message: fmt.Sprintf("could not shut the Base down: %s", err.Error()),
Code: rpcmessages.ExecutableNotFound,
}
}
go func(delay time.Duration) {
time.Sleep(delay)
cmd := exec.Command("shutdown", "now")
err = cmd.Start()
if err != nil {
log.Printf("Could not shutdown the Base: %s", err.Error())
}
}(shutdownDelay)
return rpcmessages.ErrorResponse{Success: true}
}
// RebootBase reboots the Base.
// The reboot is executed in a goroutine with a delay of a few seconds.
// Prior to starting the goroutine the path for the `reboot` executable is checked.
// If the executable is found, a ErrorResponse indicating success is returned.
// Otherwise a ExecutableNotFound Code is returned.
func (middleware *Middleware) RebootBase() rpcmessages.ErrorResponse {
const rebootDelay time.Duration = 5 * time.Second
log.Printf("Rebooting the Base in %s\n", rebootDelay)
if middleware.config.IsRedisMock() {
return rpcmessages.ErrorResponse{Success: true}
}
_, err := exec.LookPath("reboot")
if err != nil {
return rpcmessages.ErrorResponse{
Success: false,
Message: fmt.Sprintf("could not reboot the Base: %s", err.Error()),
Code: rpcmessages.ExecutableNotFound,
}
}
go func(delay time.Duration) {
time.Sleep(delay)
cmd := exec.Command("reboot")
err = cmd.Start()
if err != nil {
log.Printf("Could not reboot the Base: %s", err.Error())
}
}(rebootDelay)
return rpcmessages.ErrorResponse{Success: true}
}
// GetBaseUpdateProgress returns the Base update progress.
// This RPC should only be called by the app after receiving an OpBaseUpdateProgressChanged notification.
func (middleware *Middleware) GetBaseUpdateProgress() rpcmessages.GetBaseUpdateProgressResponse {
return middleware.baseUpdateProgress
}
// UpdateBase executes a over-the-air Base update. The version is to be passed as an argument.
// This is archived by running the `bbb-cmd.sh mender-update install <version>` command.
// The current update download progress is read from stdout, parsed and saved as the current state (BaseUpdateState).
// Every time the `BaseUpdateState` of the middleware changes a websocket notification is emitted to the App backend.
// Once the download is complete and the update is applied without errors a Base reboot is scheduled to be executed in 5 seconds.
// The call returns ErrorResponse.Success when a reboot has been scheduled.
func (middleware *Middleware) UpdateBase(args rpcmessages.UpdateBaseArgs) rpcmessages.ErrorResponse {
log.Println("Starting the Base Update process.")
// don't allow another update while the states are either downloading, applying or rebooting
if middleware.baseUpdateProgress.State == rpcmessages.UpdateDownloading ||
middleware.baseUpdateProgress.State == rpcmessages.UpdateApplying ||
middleware.baseUpdateProgress.State == rpcmessages.UpdateRebooting {
return rpcmessages.ErrorResponse{
Success: false,
Message: "Could not start the update process. A Base update is already in progress or the Base has to be rebooted.",
Code: rpcmessages.ErrorMenderUpdateAlreadyInProgress,
}
}
cmd := exec.Command(middleware.config.GetBBBCmdScript(), "mender-update", "install", args.Version)
stdout, err := cmd.StdoutPipe()
if err != nil {
log.Printf("Could not get the StdoutPipe to read command progress from: %s", err.Error())
return rpcmessages.ErrorResponse{
Success: false,
Message: "Could not start the update process. Please see the Middleware log for more detail.",
Code: rpcmessages.ErrorMenderUpdateInstallFailed,
}
}
defer func() {
err := stdout.Close()
if err != nil {
log.Printf("Could not close the stdout pipe %s", err)
}
}()
stdoutScanner := bufio.NewScanner(stdout)
stderr, err := cmd.StderrPipe()
if err != nil {
log.Printf("Could not get the StderrPipe to read command progress from: %s", err.Error())
return rpcmessages.ErrorResponse{
Success: false,
Message: "Could not start the update process. Please see the Middleware log for more detail.",
Code: rpcmessages.ErrorMenderUpdateInstallFailed,
}
}
defer func() {
err := stderr.Close()
if err != nil {
log.Printf("Could not close the stderr pipe %s", err)
}
}()
stderrScanner := bufio.NewScanner(stderr)
err = cmd.Start()
if err != nil {
log.Printf("Could not run the Base update command: %s", err.Error())
return rpcmessages.ErrorResponse{
Success: false,
Message: "Could not start the update process. Please see the Middleware log for more detail.",
Code: rpcmessages.ErrorMenderUpdateInstallFailed,
}
}
errOutLines := make([]string, 0)
// This goroutine uses the bufio.Scanner to .Scan() `stderr` lines.
// This is done in a goroutine, since .Scan() blocks when there is no input available.
// Every line read is appended to errOutLines, a string slice with stderr lines.
// The goroutine exits once EOF for `stderr` is reached.
// Once `stdout` reaches EOF the `stderr` pipe is closed (see below).
go func() {
for {
hasReadSomething := stderrScanner.Scan()
if hasReadSomething {
// Lines written to stderr are captured in errOutLines and processed if os.Wait returns an error
lineErr := stderrScanner.Text()
errOutLines = append(errOutLines, strings.TrimSuffix(lineErr, "\n"))
} else {
if stderrScanner.Err() != nil {
log.Printf("GetBaseUpdateProgress: Could not read from stderr scanner: %s", stderrScanner.Err())
err := stderr.Close()
if err != nil {
log.Printf("Could not close the stderr pipe %s", err)
}
return
}
// When scanner.Scan() returns `false` and scanner.Err() is `nil` then EOF of `stderr` is reached. The goroutine exits.
return
}
}
}()
for {
hasReadSomething := stdoutScanner.Scan()
if hasReadSomething {
lineOut := stdoutScanner.Text()
log.Println(lineOut)
containsProgressUpdateInfo, percentage, downloadedKiB := parseBaseUpdateStdout(lineOut)
if containsProgressUpdateInfo {
middleware.baseUpdateProgress.ProgressPercentage = percentage
middleware.baseUpdateProgress.ProgressDownloadedKiB = downloadedKiB
if percentage < 98 {
middleware.setBaseUpdateStateAndNotify(rpcmessages.UpdateDownloading)
} else {
// switch State from `UpdateDownloading` to `UpdateApplying`
// This is done at 98% or above since the mender-install script does
// only log 100% after applying the update.
middleware.setBaseUpdateStateAndNotify(rpcmessages.UpdateApplying)
}
}
} else {
if stdoutScanner.Err() != nil {
log.Printf("GetBaseUpdateProgress: Could not read from stdout scanner: %s", stdoutScanner.Err())
middleware.setBaseUpdateStateAndNotify(rpcmessages.UpdateFailed)
err := stderr.Close()
if err != nil {
log.Printf("Could not close the stderr pipe %s", err)
}
return rpcmessages.ErrorResponse{
Success: false,
Message: "An error occurred while performing the Base update. Please see the Middleware log for more detail.",
Code: rpcmessages.ErrorMenderUpdateInstallFailed,
}
}
// When scanner.Scan() returns `false` and scanner.Err() is `nil` then EOF of `stdout` is reached.
err := stderr.Close()
if err != nil {
log.Printf("Could not close the stderr pipe %s", err)
}
break
}
}
err = cmd.Wait()
if err != nil {
errorCode := handleBBBScriptErrorCode(errOutLines, err, []rpcmessages.ErrorCode{
rpcmessages.ErrorMenderUpdateImageNotMenderEnabled,
rpcmessages.ErrorMenderUpdateInstallFailed,
rpcmessages.ErrorMenderUpdateInvalidVersion,
rpcmessages.ErrorMenderUpdateNoVersion,
})
middleware.setBaseUpdateStateAndNotify(rpcmessages.UpdateFailed)
return rpcmessages.ErrorResponse{
Success: false,
Message: strings.Join(errOutLines, "\n"),
Code: errorCode,
}
}
middleware.setBaseUpdateStateAndNotify(rpcmessages.UpdateRebooting)
resp := middleware.RebootBase()
if !resp.Success {
return resp
}
return rpcmessages.ErrorResponse{Success: true}
}
// EnableRootLogin enables/disables the ssh login of the root user
// and returns a ErrorResponse indicating if the call was successful.
func (middleware *Middleware) EnableRootLogin(toggleAction rpcmessages.ToggleSettingArgs) rpcmessages.ErrorResponse {
log.Printf("Executing 'Enable root login: %t' via the config script.\n", toggleAction.ToggleSetting)
out, err := middleware.runBBBConfigScript([]string{determineEnableValue(toggleAction), "rootlogin"})
if err != nil {
errorCode := handleBBBScriptErrorCode(out, err, nil)
return rpcmessages.ErrorResponse{
Success: false,
Message: strings.Join(out, "\n"),
Code: errorCode,
}
}
return rpcmessages.ErrorResponse{Success: true}
}
// EnableSSHPasswordLogin enables/disables the ssh login with a password (in addition to ssh keys)
// and returns a ErrorResponse indicating if the call was successful.
func (middleware *Middleware) EnableSSHPasswordLogin(toggleAction rpcmessages.ToggleSettingArgs) rpcmessages.ErrorResponse {
log.Printf("Executing 'Enable password login: %t' via the config script.\n", toggleAction.ToggleSetting)
out, err := middleware.runBBBConfigScript([]string{determineEnableValue(toggleAction), "sshpwlogin"})
if err != nil {
errorCode := handleBBBScriptErrorCode(out, err, nil)
return rpcmessages.ErrorResponse{
Success: false,
Message: strings.Join(out, "\n"),
Code: errorCode,
}
}
return rpcmessages.ErrorResponse{Success: true}
}
// SetLoginPassword sets the system main ssh/login password
func (middleware *Middleware) SetLoginPassword(args rpcmessages.SetLoginPasswordArgs) rpcmessages.ErrorResponse {
log.Println("Setting a new login password via the config script")
password := args.LoginPassword
// Unicode passwords are allowed, but each Unicode rune is only counted as one when comparing the length
// len("₿") = 3
// len([]rune("₿")) = 1
if len([]rune(password)) >= 8 {
out, err := middleware.runBBBConfigScript([]string{"set", "loginpw", password})
if err != nil {
errorCode := handleBBBScriptErrorCode(out, err, []rpcmessages.ErrorCode{
rpcmessages.ErrorSetNeedsTwoArguments,
})
return rpcmessages.ErrorResponse{
Success: false,
Message: strings.Join(out, "\n"),
Code: errorCode,
}
}
return rpcmessages.ErrorResponse{Success: true}
}