forked from lightninglabs/lightning-terminal
-
Notifications
You must be signed in to change notification settings - Fork 0
/
session_rpcserver.go
1565 lines (1317 loc) · 41.4 KB
/
session_rpcserver.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 terminal
import (
"context"
"encoding/json"
"errors"
"fmt"
"strings"
"sync"
"time"
"github.com/btcsuite/btcd/btcec/v2"
"github.com/btcsuite/btcd/btcec/v2/ecdsa"
"github.com/btcsuite/btcd/chaincfg/chainhash"
"github.com/lightninglabs/lightning-node-connect/mailbox"
"github.com/lightninglabs/lightning-terminal/accounts"
"github.com/lightninglabs/lightning-terminal/autopilotserver"
"github.com/lightninglabs/lightning-terminal/firewall"
"github.com/lightninglabs/lightning-terminal/firewalldb"
"github.com/lightninglabs/lightning-terminal/litrpc"
"github.com/lightninglabs/lightning-terminal/perms"
"github.com/lightninglabs/lightning-terminal/rules"
"github.com/lightninglabs/lightning-terminal/session"
"github.com/lightningnetwork/lnd/macaroons"
"google.golang.org/grpc"
"gopkg.in/macaroon-bakery.v2/bakery"
"gopkg.in/macaroon-bakery.v2/bakery/checkers"
"gopkg.in/macaroon.v2"
)
// readOnlyAction defines the keyword that a permission action should be set to
// when the entity is set to "uri" in order to activate the special case that
// will result in all read-only permissions known to lit to be added to a
// session's macaroon. The purpose of the three '*'s is to make this keyword
// an invalid URI and an invalid regex so that it does not ever clash with the
// other special cases.
const readOnlyAction = "***readonly***"
// sessionRpcServer is the gRPC server for the Session RPC interface.
type sessionRpcServer struct {
litrpc.UnimplementedSessionsServer
litrpc.UnimplementedFirewallServer
litrpc.UnimplementedAutopilotServer
cfg *sessionRpcServerConfig
sessionServer *session.Server
// sessRegMu is a mutex that should be held between acquiring an unused
// session ID and key pair from the session store and persisting that
// new session.
sessRegMu sync.Mutex
quit chan struct{}
wg sync.WaitGroup
stopOnce sync.Once
}
// sessionRpcServerConfig holds the values used to configure the
// sessionRpcServer.
type sessionRpcServerConfig struct {
db *session.DB
basicAuth string
grpcOptions []grpc.ServerOption
registerGrpcServers func(server *grpc.Server)
superMacBaker session.MacaroonBaker
firstConnectionDeadline time.Duration
permMgr *perms.Manager
actionsDB *firewalldb.DB
autopilot autopilotserver.Autopilot
ruleMgrs rules.ManagerSet
privMap firewalldb.NewPrivacyMapDB
}
// newSessionRPCServer creates a new sessionRpcServer using the passed config.
func newSessionRPCServer(cfg *sessionRpcServerConfig) (*sessionRpcServer,
error) {
// Create the gRPC server that handles adding/removing sessions and the
// actual mailbox server that spins up the Terminal Connect server
// interface.
server := session.NewServer(
func(opts ...grpc.ServerOption) *grpc.Server {
allOpts := append(cfg.grpcOptions, opts...)
grpcServer := grpc.NewServer(allOpts...)
cfg.registerGrpcServers(grpcServer)
return grpcServer
},
)
return &sessionRpcServer{
cfg: cfg,
sessionServer: server,
quit: make(chan struct{}),
}, nil
}
// start all the components necessary for the sessionRpcServer to start serving
// requests. This includes resuming all non-revoked sessions.
func (s *sessionRpcServer) start() error {
// Start up all previously created sessions.
sessions, err := s.cfg.db.ListSessions(nil)
if err != nil {
return fmt.Errorf("error listing sessions: %v", err)
}
for _, sess := range sessions {
key := sess.LocalPublicKey.SerializeCompressed()
if sess.Type == session.TypeAutopilot {
// We only start the autopilot sessions if the autopilot
// client has been enabled.
if s.cfg.autopilot == nil {
continue
}
// Do a sanity check to ensure that we have the static
// remote pub key stored for this session. This should
// never not be the case.
if sess.RemotePublicKey == nil {
log.Errorf("no static remote key found for "+
"autopilot session %x", key)
continue
}
if sess.State != session.StateInUse &&
sess.State != session.StateCreated {
continue
}
if sess.Expiry.Before(time.Now()) {
continue
}
ctx := context.Background()
ctxc, cancel := context.WithTimeout(
ctx, defaultConnectTimeout,
)
// Register the session with the autopilot client.
perm, err := s.cfg.autopilot.ActivateSession(
ctxc, sess.LocalPublicKey,
)
cancel()
if err != nil {
log.Errorf("error activating autopilot "+
"session (%x) with the client", key,
err)
if perm {
err := s.cfg.db.RevokeSession(
sess.LocalPublicKey,
)
if err != nil {
log.Errorf("error revoking "+
"session: %v", err)
}
continue
}
}
}
if err := s.resumeSession(sess); err != nil {
log.Errorf("error resuming session (%x): %v", key, err)
}
}
return nil
}
// stop cleans up any sessionRpcServer resources.
func (s *sessionRpcServer) stop() error {
var returnErr error
s.stopOnce.Do(func() {
if err := s.cfg.db.Close(); err != nil {
log.Errorf("Error closing session DB: %v", err)
returnErr = err
}
s.sessionServer.Stop()
close(s.quit)
s.wg.Wait()
})
return returnErr
}
// AddSession adds and starts a new Terminal Connect session.
func (s *sessionRpcServer) AddSession(_ context.Context,
req *litrpc.AddSessionRequest) (*litrpc.AddSessionResponse, error) {
expiry := time.Unix(int64(req.ExpiryTimestampSeconds), 0)
if time.Now().After(expiry) {
return nil, fmt.Errorf("expiry must be in the future")
}
typ, err := unmarshalRPCType(req.SessionType)
if err != nil {
return nil, err
}
// Store the entity-action permission pairs in a map in order to
// de-dup any repeat perms.
permissions := make(map[string]map[string]struct{})
// addPerm is a closure that can be used to add entity-action pairs to
// the permissions map.
addPerm := func(entity, action string) {
_, ok := permissions[entity]
if !ok {
permissions[entity] = make(map[string]struct{})
}
permissions[entity][action] = struct{}{}
}
var caveats []macaroon.Caveat
switch typ {
// For the default session types we use empty caveats and permissions,
// the macaroons are baked correctly when creating the session.
case session.TypeMacaroonAdmin, session.TypeMacaroonReadonly:
// For account based sessions we just add the account ID caveat, the
// permissions are added dynamically when creating the session.
case session.TypeMacaroonAccount:
id, err := accounts.ParseAccountID(req.AccountId)
if err != nil {
return nil, fmt.Errorf("invalid account ID: %v", err)
}
cav := checkers.Condition(macaroons.CondLndCustom, fmt.Sprintf(
"%s %x", accounts.CondAccount, id[:],
))
caveats = append(caveats, macaroon.Caveat{
Id: []byte(cav),
})
// For the custom macaroon type, we use the custom permissions specified
// in the request. For the time being, the caveats list will be empty
// for this type.
case session.TypeMacaroonCustom:
if len(req.MacaroonCustomPermissions) == 0 {
return nil, fmt.Errorf("custom macaroon " +
"permissions must be specified for the " +
"custom macaroon session type")
}
for _, op := range req.MacaroonCustomPermissions {
if op.Entity != macaroons.PermissionEntityCustomURI {
addPerm(op.Entity, op.Action)
continue
}
// If the action specified was equal to the
// readOnlyAction keyword, then this is taken to mean
// that the permissions for all read-only URIs should be
// granted.
if op.Action == readOnlyAction {
readPerms := s.cfg.permMgr.ActivePermissions(
true,
)
for _, p := range readPerms {
addPerm(p.Entity, p.Action)
}
continue
}
// First check if this is a regex URI.
uris, isRegex := s.cfg.permMgr.MatchRegexURI(op.Action)
if isRegex {
// This is a regex URI, and so we add each of
// the matching URIs returned from the
// permissions' manager.
for _, uri := range uris {
addPerm(op.Entity, uri)
}
continue
}
// This is not a wild card URI, so just check that the
// permissions' manager is aware of this URI.
_, ok := s.cfg.permMgr.URIPermissions(op.Action)
if !ok {
return nil, fmt.Errorf("URI %s is unknown to "+
"LiT", op.Action)
}
addPerm(op.Entity, op.Action)
}
// No other types are currently supported.
default:
return nil, fmt.Errorf("invalid session type, only admin, " +
"readonly, custom and account macaroon types supported in " +
"LiT. Autopilot sessions must be added using " +
"AddAutoPilotSession method")
}
// Collect the de-duped permissions.
var uniquePermissions []bakery.Op
for entity, actions := range permissions {
for action := range actions {
uniquePermissions = append(uniquePermissions, bakery.Op{
Entity: entity,
Action: action,
})
}
}
s.sessRegMu.Lock()
defer s.sessRegMu.Unlock()
id, localPrivKey, err := s.cfg.db.GetUnusedIDAndKeyPair()
if err != nil {
return nil, err
}
sess, err := session.NewSession(
id, localPrivKey, req.Label, typ, expiry, req.MailboxServerAddr,
req.DevServer, uniquePermissions, caveats, nil, false, nil,
)
if err != nil {
return nil, fmt.Errorf("error creating new session: %v", err)
}
if err := s.cfg.db.CreateSession(sess); err != nil {
return nil, fmt.Errorf("error storing session: %v", err)
}
if err := s.resumeSession(sess); err != nil {
return nil, fmt.Errorf("error starting session: %v", err)
}
rpcSession, err := s.marshalRPCSession(sess)
if err != nil {
return nil, fmt.Errorf("error marshaling session: %v", err)
}
return &litrpc.AddSessionResponse{
Session: rpcSession,
}, nil
}
// resumeSession tries to start an existing session if it is not expired, not
// revoked and a LiT session.
func (s *sessionRpcServer) resumeSession(sess *session.Session) error {
pubKey := sess.LocalPublicKey
pubKeyBytes := pubKey.SerializeCompressed()
// We only start non-revoked, non-expired LiT sessions. Everything else
// we just skip.
if sess.State != session.StateInUse &&
sess.State != session.StateCreated {
log.Debugf("Not resuming session %x with state %d", pubKeyBytes,
sess.State)
return nil
}
// Don't resume an expired session.
if sess.Expiry.Before(time.Now()) {
log.Debugf("Not resuming session %x with expiry %s",
pubKeyBytes, sess.Expiry)
if err := s.cfg.db.RevokeSession(pubKey); err != nil {
return fmt.Errorf("error revoking session: %v", err)
}
return nil
}
var (
caveats []macaroon.Caveat
permissions []bakery.Op
readOnly = sess.Type == session.TypeMacaroonReadonly
)
switch sess.Type {
// For the default session types we use empty caveats and permissions,
// the macaroons are baked correctly when creating the session.
case session.TypeMacaroonAdmin, session.TypeMacaroonReadonly:
permissions = s.cfg.permMgr.ActivePermissions(readOnly)
// For account based sessions we just add the account ID caveat, the
// permissions are added dynamically when creating the session.
case session.TypeMacaroonAccount:
if sess.MacaroonRecipe == nil {
return fmt.Errorf("invalid account session, expected " +
"recipe to be set")
}
caveats = sess.MacaroonRecipe.Caveats
permissions = accounts.MacaroonPermissions
// For custom session types, we use the caveats and permissions that
// were persisted on session creation.
case session.TypeMacaroonCustom, session.TypeAutopilot:
if sess.MacaroonRecipe == nil {
break
}
permissions = sess.MacaroonRecipe.Permissions
caveats = append(caveats, sess.MacaroonRecipe.Caveats...)
// No other types are currently supported.
default:
log.Debugf("Not resuming session %x with type %d", pubKeyBytes,
sess.Type)
return nil
}
// Add the session expiry as a macaroon caveat.
macExpiry := checkers.TimeBeforeCaveat(sess.Expiry)
caveats = append(caveats, macaroon.Caveat{
Id: []byte(macExpiry.Condition),
})
mac, err := s.cfg.superMacBaker(
context.Background(), sess.MacaroonRootKey,
&session.MacaroonRecipe{
Permissions: permissions,
Caveats: caveats,
},
)
if err != nil {
log.Debugf("Not resuming session %x. Could not bake "+
"the necessary macaroon: %w", pubKeyBytes, err)
return nil
}
var (
onNewStatus func(s mailbox.ServerStatus)
firstConnTimout = make(chan struct{})
)
// If this is the first time the session is being spun up then we will
// kick off a timer to revoke the session after a timeout unless an
// initial connection is made. We identify such a session as one that
// we do not yet have a static remote pub key for.
if sess.RemotePublicKey == nil {
deadline := sess.CreatedAt.Add(s.cfg.firstConnectionDeadline)
if deadline.Before(time.Now()) {
log.Debugf("Deadline for session %x has already "+
"passed. Revoking session", pubKeyBytes)
return s.cfg.db.RevokeSession(pubKey)
}
// Start the deadline timer.
deadlineDuration := time.Until(deadline)
deadlineTimer := time.AfterFunc(deadlineDuration, func() {
close(firstConnTimout)
})
log.Warnf("Kicking off deadline timer for first connection "+
"for session %x. A successful connection must be "+
"made in the next %s", pubKeyBytes, deadlineDuration)
var stopTimerOnce sync.Once
onNewStatus = func(s mailbox.ServerStatus) {
// We will only stop the timer if the server status
// indicates that the client has successfully connected.
if s != mailbox.ServerStatusInUse {
return
}
// Stop the deadline timer.
stopTimerOnce.Do(func() {
log.Debugf("First connection for session %x "+
"made in a timely manner",
sess.LocalPublicKey.
SerializeCompressed())
deadlineTimer.Stop()
})
}
}
authData := []byte(fmt.Sprintf("%s: %s", HeaderMacaroon, mac))
sessionClosedSub, err := s.sessionServer.StartSession(
sess, authData, s.cfg.db.UpdateSessionRemotePubKey, onNewStatus,
)
if err != nil {
return err
}
s.wg.Add(1)
go func() {
defer s.wg.Done()
ticker := time.NewTimer(time.Until(sess.Expiry))
defer ticker.Stop()
select {
case <-s.quit:
return
case <-sessionClosedSub:
return
case <-ticker.C:
log.Debugf("Stopping expired session %x with "+
"type %d", pubKeyBytes, sess.Type)
case <-firstConnTimout:
log.Debugf("Deadline exceeded for first connection "+
"for session %x. Stopping and revoking.",
pubKeyBytes)
}
if s.cfg.autopilot != nil {
ctx := context.Background()
ctxc, cancel := context.WithTimeout(
ctx, defaultConnectTimeout,
)
s.cfg.autopilot.SessionRevoked(ctxc, pubKey)
cancel()
}
err = s.sessionServer.StopSession(pubKey)
if err != nil {
log.Debugf("Error stopping session: %v", err)
}
err = s.cfg.db.RevokeSession(pubKey)
if err != nil {
log.Debugf("error revoking session: %v", err)
}
}()
return nil
}
// ListSessions returns all sessions known to the session store.
func (s *sessionRpcServer) ListSessions(_ context.Context,
_ *litrpc.ListSessionsRequest) (*litrpc.ListSessionsResponse, error) {
sessions, err := s.cfg.db.ListSessions(nil)
if err != nil {
return nil, fmt.Errorf("error fetching sessions: %v", err)
}
response := &litrpc.ListSessionsResponse{
Sessions: make([]*litrpc.Session, len(sessions)),
}
for idx, sess := range sessions {
response.Sessions[idx], err = s.marshalRPCSession(sess)
if err != nil {
return nil, fmt.Errorf("error marshaling session: %v",
err)
}
}
return response, nil
}
// RevokeSession revokes a single session and also stops it if it is currently
// active.
func (s *sessionRpcServer) RevokeSession(ctx context.Context,
req *litrpc.RevokeSessionRequest) (*litrpc.RevokeSessionResponse, error) {
pubKey, err := btcec.ParsePubKey(req.LocalPublicKey)
if err != nil {
return nil, fmt.Errorf("error parsing public key: %v", err)
}
if err := s.cfg.db.RevokeSession(pubKey); err != nil {
return nil, fmt.Errorf("error revoking session: %v", err)
}
if s.cfg.autopilot != nil {
s.cfg.autopilot.SessionRevoked(ctx, pubKey)
}
// If the session expired already it might not be running anymore. So we
// only log possible errors here.
if err := s.sessionServer.StopSession(pubKey); err != nil {
log.Debugf("Error stopping session: %v", err)
}
return &litrpc.RevokeSessionResponse{}, nil
}
// PrivacyMapConversion can be used map real values to their pseudo counterpart
// and vice versa.
func (s *sessionRpcServer) PrivacyMapConversion(_ context.Context,
req *litrpc.PrivacyMapConversionRequest) (
*litrpc.PrivacyMapConversionResponse, error) {
var (
groupID session.ID
err error
)
if len(req.GroupId) != 0 {
groupID, err = session.IDFromBytes(req.GroupId)
if err != nil {
return nil, err
}
} else {
sessionID, err := session.IDFromBytes(req.SessionId)
if err != nil {
return nil, err
}
groupID, err = s.cfg.db.GetGroupID(sessionID)
if err != nil {
return nil, err
}
}
var res string
privMap := s.cfg.privMap(groupID)
err = privMap.View(func(tx firewalldb.PrivacyMapTx) error {
var err error
if req.RealToPseudo {
res, err = tx.RealToPseudo(req.Input)
return err
}
res, err = tx.PseudoToReal(req.Input)
return err
})
if err != nil {
return nil, err
}
return &litrpc.PrivacyMapConversionResponse{
Output: res,
}, nil
}
// ListActions will return a list of actions that have been performed on the
// node. The actions that will be persisted depends on the value of the
// `--firewall.request-logger.level` config option. The default value of the
// option is the "interceptor" mode which will persist only the actions (with
// all request parameters) made with macaroons with caveats that force them to
// be checked by an rpc middleware interceptor. If the "all" mode is used then
// all actions will be persisted but only full request parameters will only be
// stored if the actions are interceptor actions, otherwise only the URI and
// timestamp of the actions will be stored. The "full" mode will persist all
// request data for all actions.
func (s *sessionRpcServer) ListActions(_ context.Context,
req *litrpc.ListActionsRequest) (*litrpc.ListActionsResponse, error) {
// If no maximum number of actions is given, use a default of 100.
if req.MaxNumActions == 0 {
req.MaxNumActions = 100
}
// Build a filter function based on the request values.
filterFn := func(a *firewalldb.Action, reversed bool) (bool, bool) {
timeStamp := uint64(a.AttemptedAt.Unix())
if req.EndTimestamp != 0 {
// If actions are being considered in order and the
// timestamp of this action exceeds the given end
// timestamp, then there is no need to continue
// traversing.
if !reversed && timeStamp > req.EndTimestamp {
return false, false
}
// If the actions are in reverse order and the timestamp
// comes after the end timestamp, then the actions is
// not included but the search can continue.
if reversed && timeStamp > req.EndTimestamp {
return false, true
}
}
if req.StartTimestamp != 0 {
// If actions are being considered in order and the
// timestamp of this action comes before the given start
// timestamp, then the action is not included but the
// search can continue.
if !reversed && timeStamp < req.StartTimestamp {
return false, true
}
// If the actions are in reverse order and the timestamp
// comes before the start timestamp, then there is no
// need to continue traversing.
if reversed && timeStamp < req.StartTimestamp {
return false, false
}
}
if req.FeatureName != "" && a.FeatureName != req.FeatureName {
return false, true
}
if req.ActorName != "" && a.ActorName != req.ActorName {
return false, true
}
if req.MethodName != "" && a.RPCMethod != req.MethodName {
return false, true
}
if req.State != 0 {
s, err := marshalActionState(a.State)
if err != nil {
return false, true
}
if s != req.State {
return false, true
}
}
return true, true
}
query := &firewalldb.ListActionsQuery{
IndexOffset: req.IndexOffset,
MaxNum: req.MaxNumActions,
Reversed: req.Reversed,
CountAll: req.CountTotal,
}
var (
db = s.cfg.actionsDB
actions []*firewalldb.Action
lastIndex uint64
totalCount uint64
err error
)
if req.SessionId != nil {
sessionID, err := session.IDFromBytes(req.SessionId)
if err != nil {
return nil, err
}
actions, lastIndex, totalCount, err = db.ListSessionActions(
sessionID, filterFn, query,
)
if err != nil {
return nil, err
}
} else if req.GroupId != nil {
groupID, err := session.IDFromBytes(req.GroupId)
if err != nil {
return nil, err
}
actions, err = db.ListGroupActions(groupID, filterFn)
if err != nil {
return nil, err
}
} else {
actions, lastIndex, totalCount, err = db.ListActions(
filterFn, query,
)
if err != nil {
return nil, err
}
}
resp := make([]*litrpc.Action, len(actions))
for i, a := range actions {
state, err := marshalActionState(a.State)
if err != nil {
return nil, err
}
resp[i] = &litrpc.Action{
SessionId: a.SessionID[:],
ActorName: a.ActorName,
FeatureName: a.FeatureName,
Trigger: a.Trigger,
Intent: a.Intent,
StructuredJsonData: a.StructuredJsonData,
RpcMethod: a.RPCMethod,
RpcParamsJson: string(a.RPCParamsJson),
Timestamp: uint64(a.AttemptedAt.Unix()),
State: state,
ErrorReason: a.ErrorReason,
}
}
return &litrpc.ListActionsResponse{
Actions: resp,
LastIndexOffset: lastIndex,
TotalCount: totalCount,
}, nil
}
// ListAutopilotFeatures fetches all the features supported by the autopilot
// server along with the rules that we need to support in order to subscribe
// to those features.
func (s *sessionRpcServer) ListAutopilotFeatures(ctx context.Context,
_ *litrpc.ListAutopilotFeaturesRequest) (
*litrpc.ListAutopilotFeaturesResponse, error) {
fs, err := s.cfg.autopilot.ListFeatures(ctx)
if err != nil {
return nil, err
}
features := make(map[string]*litrpc.Feature, len(fs))
for i, f := range fs {
rules, upgrade, err := convertRules(s.cfg.ruleMgrs, f.Rules)
if err != nil {
return nil, err
}
features[i] = &litrpc.Feature{
Name: f.Name,
Description: f.Description,
Rules: rules,
PermissionsList: marshalPerms(f.Permissions),
RequiresUpgrade: upgrade,
DefaultConfig: string(f.DefaultConfig),
}
}
return &litrpc.ListAutopilotFeaturesResponse{
Features: features,
}, nil
}
// AddAutopilotSession creates a new LNC session and attempts to register it
// with the Autopilot server.
func (s *sessionRpcServer) AddAutopilotSession(ctx context.Context,
req *litrpc.AddAutopilotSessionRequest) (
*litrpc.AddAutopilotSessionResponse, error) {
if len(req.Features) == 0 {
return nil, fmt.Errorf("must include at least one feature")
}
expiry := time.Unix(int64(req.ExpiryTimestampSeconds), 0)
if time.Now().After(expiry) {
return nil, fmt.Errorf("expiry must be in the future")
}
// If the privacy mapper is being used for this session, then we need
// to keep track of all our known privacy map pairs for this session
// along with any new pairs that we need to persist.
var (
privacy = !req.NoPrivacyMapper
knownPrivMapPairs = firewalldb.NewPrivacyMapPairs(nil)
newPrivMapPairs = make(map[string]string)
)
// If a previous session ID has been set to link this new one to, we
// first check if we have the referenced session, and we make sure it
// has been revoked.
var (
linkedGroupID *session.ID
linkedGroupSession *session.Session
)
if len(req.LinkedGroupId) != 0 {
var groupID session.ID
copy(groupID[:], req.LinkedGroupId)
// Check that the group actually does exist.
groupSess, err := s.cfg.db.GetSessionByID(groupID)
if err != nil {
return nil, err
}
// Ensure that the linked session is in fact the first session
// in its group.
if groupSess.ID != groupSess.GroupID {
return nil, fmt.Errorf("can not link to session "+
"%x since it is not the first in the session "+
"group %x", groupSess.ID, groupSess.GroupID)
}
// Now we need to check that all the sessions in the group are
// no longer active.
ok, err := s.cfg.db.CheckSessionGroupPredicate(
groupID, func(s *session.Session) bool {
return s.State == session.StateRevoked ||
s.State == session.StateExpired
},
)
if err != nil {
return nil, err
}
if !ok {
return nil, fmt.Errorf("a linked session in group "+
"%x is still active", groupID)
}
linkedGroupID = &groupID
linkedGroupSession = groupSess
privDB := s.cfg.privMap(groupID)
err = privDB.View(func(tx firewalldb.PrivacyMapTx) error {
knownPrivMapPairs, err = tx.FetchAllPairs()
return err
})
if err != nil {
return nil, err
}
}
// First need to fetch all the perms that need to be baked into this
// mac based on the features.
allFeatures, err := s.cfg.autopilot.ListFeatures(ctx)
if err != nil {
return nil, err
}
// Create lookup map of all the features that autopilot server offers.
autopilotFeatureMap := make(map[string]*autopilotserver.Feature)
for _, f := range allFeatures {
autopilotFeatureMap[f.Name] = f
}
// allRules represents all the rules that our firewall knows about.
allRules := s.cfg.ruleMgrs.GetAllRules()
// Check that each requested feature is a valid autopilot feature and
// that the necessary rules for the feature have been specified.
featureRules := make(map[string]map[string]string, len(req.Features))
for f, rs := range req.Features {
// Check that the features is known by the autopilot server.
autopilotFeature, ok := autopilotFeatureMap[f]
if !ok {
return nil, fmt.Errorf("%s is not a features "+
"provided by the Autopilot server", f)
}
// reqRules is the rules specified in the request.
var reqRules []rules.Values
if rs.Rules != nil {
reqRules = make([]rules.Values, 0, len(rs.Rules.Rules))
for ruleName, rule := range rs.Rules.Rules {
v, err := s.cfg.ruleMgrs.UnmarshalRuleValues(
ruleName, rule,
)
if err != nil {
return nil, err
}
if privacy {
var privMapPairs map[string]string
v, privMapPairs, err = v.RealToPseudo(
knownPrivMapPairs,
)
if err != nil {
return nil, err
}
// Store the new privacy map pairs in
// the newPrivMap pairs map so that
// they are later persisted to the real
// priv map db.
for k, v := range privMapPairs {
newPrivMapPairs[k] = v
}
// Also add the new pairs to the known
// set of pairs.
err = knownPrivMapPairs.Add(
privMapPairs,
)
if err != nil {
return nil, err
}
}
reqRules = append(reqRules, v)
}
}
// Create a lookup map for the rules specified in this feature.
// Also check that each of the rules in the request is one known
// to us.
frs := make(map[string]rules.Values)
for _, r := range reqRules {
frs[r.RuleName()] = r
_, ok := allRules[r.RuleName()]
if !ok {
return nil, fmt.Errorf("%s is not a known rule",
r.RuleName())
}
}
// For each of the specified rules, we check that the values
// set for those rules are sane given the bounds provided by
// the autopilot server for the given feature.
for _, r := range reqRules {
ruleName := r.RuleName()
autopilotSpecs, ok := autopilotFeature.Rules[ruleName]
if !ok {
return nil, fmt.Errorf("autopilot did not "+
"specify %s as a rule for feature %s",
ruleName, autopilotFeature.Name)