/
policy.go
2268 lines (2038 loc) · 72.3 KB
/
policy.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 rest
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net"
"net/http"
"reflect"
"sort"
"strconv"
"strings"
"syscall"
"time"
"github.com/julienschmidt/httprouter"
log "github.com/sirupsen/logrus"
"github.com/neuvector/neuvector/controller/access"
"github.com/neuvector/neuvector/controller/api"
"github.com/neuvector/neuvector/controller/common"
"github.com/neuvector/neuvector/controller/rpc"
"github.com/neuvector/neuvector/controller/ruleid"
"github.com/neuvector/neuvector/share"
"github.com/neuvector/neuvector/share/cluster"
"github.com/neuvector/neuvector/share/utils"
)
var cfgTypeMap2Api = map[share.TCfgType]string{
share.Learned: api.CfgTypeLearned,
share.UserCreated: api.CfgTypeUserCreated,
share.GroundCfg: api.CfgTypeGround,
share.FederalCfg: api.CfgTypeFederal,
}
var cfgTypeMapping = map[string]share.TCfgType{
api.CfgTypeLearned: share.Learned,
api.CfgTypeUserCreated: share.UserCreated,
api.CfgTypeGround: share.GroundCfg,
api.CfgTypeFederal: share.FederalCfg,
}
func compareRESTRules(r1, r2 *api.RESTPolicyRule) bool {
e := *r1
r := *r2
e.CreatedTS = 0
e.LastModTS = 0
r.CreatedTS = 0
r.LastModTS = 0
return reflect.DeepEqual(e, r)
}
func compareCLUSRules(r1, r2 *share.CLUSPolicyRule) bool {
e := *r1
r := *r2
e.CreatedAt = time.Time{}
e.LastModAt = time.Time{}
r.CreatedAt = time.Time{}
r.LastModAt = time.Time{}
return reflect.DeepEqual(e, r)
}
func isLearnedPolicyID(id uint32) bool {
//return id >= api.PolicyLearnedIDBase && id < 0x7fffffff
return id >= api.PolicyLearnedIDBase && id < api.PolicyFedRuleIDBase
}
func isSecurityPolicyID(id uint32) bool {
return id >= api.PolicyGroundRuleIDBase
}
func isFedPolicyID(id uint32) bool {
return id >= api.PolicyFedRuleIDBase && id < api.PolicyFedRuleIDMax
}
func handlerPolicyRuleList(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
log.WithFields(log.Fields{"URL": r.URL.String()}).Debug("")
defer r.Body.Close()
acc, login := getAccessControl(w, r, "")
if acc == nil {
return
}
query := restParseQuery(r)
scope, _ := query.pairs[api.QueryScope] // empty string means fed & local rules
var resp api.RESTPolicyRulesData
resp.Rules = make([]*api.RESTPolicyRule, 0)
rules := cacher.GetAllPolicyRules(scope, acc)
// Filter
if len(rules) <= query.start {
restRespSuccess(w, r, &resp, acc, login, nil, "Get policy rule list")
return
}
if query.limit == 0 {
resp.Rules = rules[query.start:]
} else {
var end int
if query.start+query.limit > len(rules) {
end = len(rules)
} else {
end = query.start + query.limit
}
resp.Rules = rules[query.start:end]
}
for _, rule := range resp.Rules {
if rule.Learned && rule.CfgType == "" {
rule.CfgType = api.CfgTypeLearned
}
}
log.WithFields(log.Fields{"entries": len(resp.Rules)}).Debug("Response")
restRespSuccess(w, r, &resp, acc, login, nil, "Get policy rule list")
}
func handlerPolicyRuleShow(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
log.WithFields(log.Fields{"URL": r.URL.String()}).Debug("")
defer r.Body.Close()
acc, login := getAccessControl(w, r, "")
if acc == nil {
return
}
id, err := strconv.Atoi(ps.ByName("id"))
if err != nil || id <= 0 {
log.WithFields(log.Fields{"id": id}).Error("Invalid ID")
restRespError(w, http.StatusBadRequest, api.RESTErrInvalidRequest)
return
}
var resp api.RESTPolicyRuleData
// Retrieve the policy rule
rule, err := cacher.GetPolicyRule(uint32(id), acc)
if rule == nil {
restRespNotFoundLogAccessDenied(w, login, err)
return
}
if rule.Learned && rule.CfgType == "" {
rule.CfgType = api.CfgTypeLearned
}
resp.Rule = rule
restRespSuccess(w, r, &resp, acc, login, nil, "Get policy rule detail")
}
type portRange struct {
proto, low, high int
}
type portRangeSorter struct {
ports []portRange
}
func (s *portRangeSorter) Len() int {
return len(s.ports)
}
func (s *portRangeSorter) Swap(i, j int) {
s.ports[i], s.ports[j] = s.ports[j], s.ports[i]
}
func (s *portRangeSorter) Less(i, j int) bool {
if s.ports[i].proto < s.ports[j].proto {
return true
} else if s.ports[i].proto > s.ports[j].proto {
return false
} else if s.ports[i].low < s.ports[j].low {
return true
} else if s.ports[i].low > s.ports[j].low {
return false
} else if s.ports[i].high < s.ports[j].high {
return true
}
return false
}
// Parse port string in "80, 8080, 8500-8508, tcp/443, tcp/3306-3307, udp/53"
func parseRange(s string) (int, int, error) {
var low, high int
var err error
if dash := strings.Index(s, "-"); dash != -1 {
if low, err = strconv.Atoi(s[:dash]); err != nil {
return 0, 0, err
}
if high, err = strconv.Atoi(s[dash+1:]); err != nil {
return 0, 0, err
}
return low, high, nil
} else {
if low, err = strconv.Atoi(s); err != nil {
return 0, 0, err
}
return low, low, nil
}
}
func normalizePorts(s string) (string, error) {
s = strings.Trim(s, " ")
if len(s) == 0 || strings.ToUpper(s) == strings.ToUpper(api.PolicyPortAny) {
return api.PolicyPortAny, nil
}
// Split the string with , and space
fs := strings.FieldsFunc(s, func(r rune) bool {
return r == ',' || r == ' '
})
var tcpAny, udpAny, icmp bool
var err error
ports := make([]portRange, 0)
for _, f := range fs {
var low, high int
proto := syscall.IPPROTO_TCP
if strings.HasPrefix(f, "tcp/") || strings.HasPrefix(f, "TCP/") {
if strings.ToUpper(f[4:]) == strings.ToUpper(api.PolicyPortAny) {
tcpAny = true
continue
} else {
low, high, err = parseRange(f[4:])
}
} else if strings.HasPrefix(f, "udp/") || strings.HasPrefix(f, "UDP/") {
if strings.ToUpper(f[4:]) == strings.ToUpper(api.PolicyPortAny) {
udpAny = true
continue
} else {
proto = syscall.IPPROTO_UDP
low, high, err = parseRange(f[4:])
}
} else if f == "icmp" {
icmp = true
continue
} else {
if strings.ToUpper(f) == strings.ToUpper(api.PolicyPortAny) {
tcpAny = true
udpAny = true
continue
} else {
low, high, err = parseRange(f)
}
}
if err != nil {
return "", err
}
if low < 0 || low > 65535 || high < 0 || high > 65535 || low > high {
return "", errors.New("Invalid ports format")
}
ports = append(ports, portRange{proto: proto, low: low, high: high})
}
sorter := portRangeSorter{ports: make([]portRange, 0)}
for _, port := range ports {
if tcpAny && port.proto == syscall.IPPROTO_TCP {
continue
} else if udpAny && port.proto == syscall.IPPROTO_UDP {
continue
} else {
sorter.ports = append(sorter.ports, port)
}
}
sort.Sort(&sorter)
// Join sorted port list
strs := make([]string, 0)
if icmp {
strs = append(strs, "icmp")
}
if tcpAny && udpAny {
strs = append(strs, api.PolicyPortAny)
} else if tcpAny {
strs = append(strs, fmt.Sprintf("tcp/%v", api.PolicyPortAny))
} else if udpAny {
strs = append(strs, fmt.Sprintf("udp/%v", api.PolicyPortAny))
}
for _, port := range sorter.ports {
var proto string
switch port.proto {
case syscall.IPPROTO_TCP:
proto = "tcp"
case syscall.IPPROTO_UDP:
proto = "udp"
default:
continue
}
if port.low == port.high {
strs = append(strs, fmt.Sprintf("%v/%v", proto, port.low))
} else {
strs = append(strs, fmt.Sprintf("%v/%v-%v", proto, port.low, port.high))
}
}
return strings.Join(strs, ","), nil
}
// Empty array means 'any' application
func appNames2IDs(apps []string) []uint32 {
if len(apps) == 0 {
return []uint32{}
}
var ids []uint32 = make([]uint32, 0)
for _, app := range apps {
if strings.ToUpper(app) == strings.ToUpper(api.PolicyAppAny) {
return []uint32{}
}
if id := utils.GetAppIDByName(app); id != 0 {
ids = append(ids, id)
}
}
return ids
}
// Empty string array means 'any' application
func normalizeApps(apps []string) ([]string, error) {
if len(apps) == 0 {
return []string{api.PolicyAppAny}, nil
}
appSet := utils.NewSet()
for _, app := range apps {
if strings.ToUpper(app) == strings.ToUpper(api.PolicyAppAny) {
return []string{api.PolicyAppAny}, nil
}
if id := utils.GetAppIDByName(app); id != 0 {
if appSet.Contains(id) {
return nil, fmt.Errorf("duplicated application name: %s", app)
}
appSet.Add(id)
} else {
return nil, fmt.Errorf("Unknonwn application name: %s", app)
}
}
i := 0
names := make([]string, appSet.Cardinality())
for id := range appSet.Iter() {
names[i], _ = utils.AppNameMap[id.(uint32)]
i++
}
sort.Strings(names)
return names, nil
}
func validateGroupForPolicy(ruleCfgType share.TCfgType, group string, groupMap map[string]*share.CLUSGroup, hosts []*api.RESTHost, isFrom bool) (bool, string, error) {
if group == api.LearnedExternal || group == api.AllHostGroup || (isFrom && group == api.WorkloadTunnelIF) {
return true, "", nil
}
if group == api.AllContainerGroup && ruleCfgType != share.FederalCfg {
return false, "", nil
}
if grp, ok := groupMap[group]; ok {
if (ruleCfgType == share.FederalCfg && grp.CfgType != share.FederalCfg) || (ruleCfgType != share.FederalCfg && grp.CfgType == share.FederalCfg) {
err := fmt.Errorf("Rule cannot be applied to group %s", group)
return false, "", err
}
} else if strings.HasPrefix(group, api.LearnedHostPrefix) {
if net.ParseIP(group[len(api.LearnedHostPrefix):]) != nil {
return true, "", nil
} else {
for _, host := range hosts {
if host.Name == group[len(api.LearnedHostPrefix):] {
return true, host.ID, nil
}
}
err := fmt.Errorf("Cannot find host %s", group[len(api.LearnedHostPrefix):])
return true, "", err
}
} else if strings.HasPrefix(group, api.LearnedWorkloadPrefix) {
if group[len(api.LearnedWorkloadPrefix):] == api.EndpointIngress {
return true, "", nil
} else if net.ParseIP(group[len(api.LearnedWorkloadPrefix):]) != nil {
return true, "", nil
} else {
err := fmt.Errorf("Invalid workload format %s", group)
return true, "", err
}
} else if _, ok := groupMap[group]; !ok {
err := fmt.Errorf("Cannot find group %s", group)
return false, "", err
}
return false, "", nil
}
// Validate a cluster policy rule; fill in host id information if the group is a managed host
func validateClusterPolicyRule(r *share.CLUSPolicyRule,
groupMap map[string]*share.CLUSGroup, hosts []*api.RESTHost) error {
if groupMap != nil {
var fromSpecial, toSpecial bool
var err error
if fromSpecial, r.FromHost, err = validateGroupForPolicy(r.CfgType, r.From, groupMap, hosts, true); err != nil {
log.WithFields(log.Fields{"id": r.ID, "from": r.From}).Error(err.Error())
return err
//} else if fromSpecial && r.From != api.LearnedExternal {
// err := fmt.Errorf("Policy rule from %s is not supported", r.From)
// return err
}
if toSpecial, r.ToHost, err = validateGroupForPolicy(r.CfgType, r.To, groupMap, hosts, false); err != nil {
log.WithFields(log.Fields{"id": r.ID, "to": r.To}).Error(err.Error())
return err
} else if toSpecial && fromSpecial {
err = errors.New("From/To group cannot both be special address group")
log.WithFields(log.Fields{"id": r.ID}).Error(err.Error())
return err
}
}
return nil
}
// Validate rest policy rule config; normalize port and app
func validateRestPolicyRuleConfig(r *api.RESTPolicyRuleConfig) error {
/*
if r.ID == 0 {
log.WithFields(log.Fields{"id": r.ID}).Error("Rule ID cannot be 0")
return errors.New("Rule ID cannot be 0")
}
*/
if r.Action != nil {
if *r.Action != share.PolicyActionAllow && *r.Action != share.PolicyActionDeny {
log.WithFields(log.Fields{"id": r.ID, "action": *r.Action}).Error("Invalid action")
return errors.New("Invalid action")
}
}
if r.Ports != nil {
if ports, err := normalizePorts(*r.Ports); err == nil {
*r.Ports = ports
} else {
log.WithFields(log.Fields{
"id": r.ID, "ports": *r.Ports,
}).Error("Invalid ports format")
return errors.New("Invalid ports format")
}
}
if r.Applications != nil {
if apps, err := normalizeApps(*r.Applications); err == nil {
*r.Applications = apps
} else {
log.WithFields(log.Fields{
"id": r.ID, "error": err,
}).Error("Invalid applications")
return err
}
}
if r.Priority != 0 {
if r.Priority < 0 || r.Priority > 100 {
log.WithFields(log.Fields{"id": r.ID, "Priority": r.Priority}).Error("Prioty out of range [0-100]")
return errors.New("Priority out of range")
}
}
return nil
}
func validateRestPolicyRule(r *api.RESTPolicyRule) error {
fedPolicy := isFedPolicyID(r.ID)
if (fedPolicy && r.CfgType != api.CfgTypeFederal) || (!fedPolicy && r.CfgType == api.CfgTypeFederal) {
e := fmt.Sprintf("ID is reserved for federal rule. Use ID between %v and %v.", api.PolicyFedRuleIDBase, api.PolicyFedRuleIDMax)
err := errors.New(e)
log.WithFields(log.Fields{"id": r.ID}).Error(err)
return err
}
rc := &api.RESTPolicyRuleConfig{
ID: r.ID,
Action: &r.Action,
Ports: &r.Ports,
Applications: &r.Applications,
}
return validateRestPolicyRuleConfig(rc)
}
func policyRule2Cluster(r *api.RESTPolicyRule) *share.CLUSPolicyRule {
rule := &share.CLUSPolicyRule{
ID: r.ID,
Comment: r.Comment,
From: r.From,
To: r.To,
Ports: r.Ports,
Applications: appNames2IDs(r.Applications),
Action: r.Action,
Disable: r.Disable,
}
rule.CfgType, _ = cfgTypeMapping[r.CfgType]
return rule
}
func policyRuleConf2Cluster(r *api.RESTPolicyRuleConfig) *share.CLUSPolicyRule {
return &share.CLUSPolicyRule{
ID: r.ID,
Comment: *r.Comment,
From: *r.From,
To: *r.To,
}
}
func deletePolicyRules(txn *cluster.ClusterTransact, dels utils.Set) {
for id := range dels.Iter() {
clusHelper.DeletePolicyRuleTxn(txn, id.(uint32))
}
}
func writePolicyRules(txn *cluster.ClusterTransact, crs []*share.CLUSPolicyRule) {
for _, cr := range crs {
clusHelper.PutPolicyRuleTxn(txn, cr)
}
}
// param crhs: a list of existing CLUSRuleHead
// param after: nil: last; 0: first; +id: after rule 'id'; -id: before rule 'id'
// param moveIDx: original idx of the moving item. < 0 if it's for insert op
// returns (location idx to use for the entry, _)
func locatePosition(crhs []*share.CLUSRuleHead, after *int, moveIDx int) (int, int) {
var pos uint
var before bool
if after == nil {
if moveIDx < 0 {
return len(crhs), len(crhs) // the first new item will be after crhs
} else {
return len(crhs) - 1, len(crhs) - 1 // move the item to the end of crhs
}
} else if *after == 0 {
return 0, 0
} else if *after > 0 {
pos = uint(*after)
} else {
before = true
pos = uint(-*after)
}
for i, crh := range crhs {
if crh.ID == uint32(pos) {
if before {
if moveIDx >= 0 && moveIDx < i {
return i - 1, *after // moving downwards to before an item
} else {
return i, *after
}
} else {
if moveIDx >= 0 && moveIDx < i {
return i, *after // moving downwards to after an item
} else {
return i + 1, *after
}
}
}
}
return -1, *after
}
// this function assumes crhs is already sorted by (1) federal rules (2) ground rules (3) others
// param id: id of the existing item to move
// param ruleCfgType: CfgType of the existing item to move
// param after: nil: last; 0: first; +id: after rule 'id'; -id: before rule 'id'
func moveRuleID(crhs []*share.CLUSRuleHead, id uint32, ruleCfgType share.TCfgType, after *int) error {
var moveIdx int = -1 // original idx of the moving item
var topIdx int = 0 // the top-most idx that the new location could be
var bottomIdx int = -1 // the bottom-most idx that the new location could be
for i, crh := range crhs {
if crh.ID == id {
if crh.CfgType == share.GroundCfg {
e := "Can't move Base Rule"
log.WithFields(log.Fields{"move": id}).Error(e)
return fmt.Errorf(e) // break from here if the moving item is ground rule. i.e. ground rule cannot be moved
}
moveIdx = i
}
if ruleCfgType == share.FederalCfg {
// the moving item is a federal rule. it can be moved to any existing federal rule's position
if crh.CfgType == share.FederalCfg {
bottomIdx++
}
} else {
// the moving item is not a federal/ground rule. it can be moved to any position after federal/ground rules
if crh.CfgType == share.FederalCfg || crh.CfgType == share.GroundCfg {
topIdx++
}
}
}
if moveIdx == -1 {
e := "Rule to move doesn't exist"
log.WithFields(log.Fields{"move": id}).Error(e)
return fmt.Errorf(e)
}
toIdx, af := locatePosition(crhs, after, moveIdx)
if toIdx == -1 {
e := "Move-to position cannot be found"
log.WithFields(log.Fields{"after": af}).Error(e)
return fmt.Errorf(e)
}
if bottomIdx == -1 {
bottomIdx = len(crhs) - 1
}
if toIdx < topIdx {
toIdx = topIdx
} else if toIdx > bottomIdx {
toIdx = bottomIdx
}
if moveIdx == toIdx { // same location meaning no move
return nil
} else if moveIdx < toIdx { // move downwards
mr := crhs[moveIdx]
for i := moveIdx; i < toIdx; i++ {
crhs[i] = crhs[i+1]
}
crhs[toIdx] = mr
} else { // move upwards
mr := crhs[moveIdx]
for i := moveIdx; i > toIdx; i-- {
crhs[i] = crhs[i-1]
}
crhs[toIdx] = mr
}
return nil
}
func movePolicyRule(w http.ResponseWriter, r *http.Request, move *api.RESTPolicyRuleMove,
acc *access.AccessControl, login *loginSession) (error, share.TCfgType) {
log.Debug("")
crule, err := cacher.GetPolicyRuleCache(move.ID, acc)
if crule == nil {
restRespNotFoundLogAccessDenied(w, login, err)
return err, 0
}
// No need to authorize again as it's done in the GetPolicyRuleCache()
lock, err := clusHelper.AcquireLock(share.CLUSLockPolicyKey, clusterLockWait)
if err != nil {
e := "Failed to acquire cluster lock"
log.WithFields(log.Fields{"error": err}).Error(e)
restRespErrorMessage(w, http.StatusInternalServerError, api.RESTErrFailLockCluster, e)
return err, 0
}
defer clusHelper.ReleaseLock(lock)
// Read ID list from cluster
crhs := clusHelper.GetPolicyRuleList()
if len(crhs) == 0 {
e := "Policy rule doesn't exist"
log.WithFields(log.Fields{"move": move.ID}).Error(e)
restRespError(w, http.StatusNotFound, api.RESTErrObjectNotFound)
return fmt.Errorf(e), 0
}
if move.After != nil && *move.After != 0 && *move.After == int(move.ID) {
// move an item after/before itself means no move
return nil, crule.CfgType
}
if err := moveRuleID(crhs, move.ID, crule.CfgType, move.After); err != nil {
restRespErrorMessage(w, http.StatusNotFound, api.RESTErrObjectNotFound, err.Error())
return err, 0
}
// Put policy rule heads
if err := clusHelper.PutPolicyRuleList(crhs); err != nil {
log.WithFields(log.Fields{"error": err}).Error("")
restRespError(w, http.StatusInternalServerError, api.RESTErrFailWriteCluster)
return err, 0
}
return nil, crule.CfgType
}
func isLocalReservedId(id uint32) error {
var err error
var ruleype string
if isLearnedPolicyID(id) {
ruleype = "learned"
} else if isSecurityPolicyID(id) {
ruleype = "ground"
}
if ruleype != "" {
err = fmt.Errorf("ID is reserved for %s rule. Use ID between 1 and %v.", ruleype, api.PolicyLearnedIDBase)
}
return err
}
// this function assumes crhs is already sorted by (1) federal rules (2) ground rules (3) other rules
func insertPolicyRule(scope string, w http.ResponseWriter, r *http.Request, insert *api.RESTPolicyRuleInsert,
acc *access.AccessControl, login *loginSession) error {
var topIdx int // the top-most idx that the first new item could be at
var bottomIdx int // the bottom-most idx that the first new item could be at
log.Debug("")
lock, err := clusHelper.AcquireLock(share.CLUSLockPolicyKey, clusterLockWait)
if err != nil {
e := "Failed to acquire cluster lock"
log.WithFields(log.Fields{"error": err}).Error(e)
restRespErrorMessage(w, http.StatusInternalServerError, api.RESTErrFailLockCluster, e)
return err
}
defer clusHelper.ReleaseLock(lock)
// Read ID list from cluster
crhs := clusHelper.GetPolicyRuleList()
ids := utils.NewSet()
for _, crh := range crhs {
ids.Add(crh.ID)
if scope == share.ScopeFed {
// the new items are federal rules. they could be inserted before any existing non-federal rule
if crh.CfgType == share.FederalCfg {
bottomIdx++
}
} else if scope == share.ScopeLocal {
// the new items are not federal rules. they could be inserted after the last ground rule
bottomIdx++
if crh.CfgType == share.FederalCfg || crh.CfgType == share.GroundCfg {
topIdx++
}
}
}
toIdx, after := locatePosition(crhs, insert.After, -1)
if toIdx == -1 {
e := "Insert position cannot be found"
log.WithFields(log.Fields{"scope": scope, "after": after}).Error(e)
restRespError(w, http.StatusNotFound, api.RESTErrObjectNotFound)
return fmt.Errorf(e)
}
if toIdx < topIdx {
toIdx = topIdx
} else if toIdx > bottomIdx {
toIdx = bottomIdx
}
// Validate rules
accReadAll := access.NewReaderAccessControl()
groups := clusHelper.GetAllGroups(scope, accReadAll)
hosts := cacher.GetAllHosts(accReadAll)
newRules := make([]*share.CLUSPolicyRule, 0, len(insert.Rules))
for _, rr := range insert.Rules {
if rr == nil {
continue
} else if rr.CfgType == "" {
if scope == share.ScopeFed {
rr.CfgType = api.CfgTypeFederal
} else {
rr.CfgType = api.CfgTypeUserCreated
}
}
cfgType, _ := cfgTypeMapping[rr.CfgType]
if (cfgType == share.FederalCfg && scope == share.ScopeLocal) || (cfgType != share.FederalCfg && scope == share.ScopeFed) {
e := "Mismatched rule CfgType with request"
log.WithFields(log.Fields{"id": rr.ID}).Error(e)
restRespErrorMessage(w, http.StatusBadRequest, api.RESTErrInvalidRequest, e)
return fmt.Errorf(e)
}
if ids.Contains(rr.ID) {
e := "Duplicate rule ID"
log.WithFields(log.Fields{"id": rr.ID}).Error(e)
restRespErrorMessage(w, http.StatusBadRequest, api.RESTErrInvalidRequest, e)
return fmt.Errorf(e)
}
if cfgType == share.Learned || cfgType == share.GroundCfg {
e := "Cannot create learned/Base policy rule"
log.WithFields(log.Fields{"id": rr.ID}).Error(e)
restRespErrorMessage(w, http.StatusBadRequest, api.RESTErrInvalidRequest, e)
return fmt.Errorf(e)
}
if e := isLocalReservedId(rr.ID); e != nil {
log.WithFields(log.Fields{"id": rr.ID}).Error(e)
restRespErrorMessage(w, http.StatusBadRequest, api.RESTErrInvalidRequest, e.Error())
return e
}
if rr.ID == api.PolicyAutoID {
rr.ID = common.GetAvailablePolicyID(ids, cfgType)
if rr.ID == 0 {
e := "Failed to locate available rule ID"
log.WithFields(log.Fields{"id": rr.ID}).Error(e)
restRespErrorMessage(w, http.StatusBadRequest, api.RESTErrInvalidRequest, e)
return err
}
}
if err := validateRestPolicyRule(rr); err != nil {
log.WithFields(log.Fields{"id": rr.ID, "error": err}).Error("")
restRespErrorMessage(w, http.StatusBadRequest, api.RESTErrInvalidRequest, err.Error())
return err
}
cr := policyRule2Cluster(rr)
cr.CreatedAt = time.Now().UTC()
cr.LastModAt = cr.CreatedAt
if err := validateClusterPolicyRule(cr, groups, hosts); err != nil {
log.WithFields(log.Fields{"id": cr.ID, "error": err}).Error("")
restRespErrorMessage(w, http.StatusBadRequest, api.RESTErrInvalidRequest, err.Error())
return err
}
if !acc.Authorize(cr, func(g string) share.AccessObject {
if cg, ok := groups[g]; ok {
return cg
} else {
return nil
}
}) {
restRespAccessDenied(w, login)
return common.ErrObjectAccessDenied
}
ids.Add(cr.ID)
newRules = append(newRules, cr)
}
txn := cluster.Transact()
defer txn.Close()
writePolicyRules(txn, newRules)
// Insert to policy rule heads
var cfgType share.TCfgType = share.UserCreated
if scope == share.ScopeFed {
cfgType = share.FederalCfg
}
news := make([]*share.CLUSRuleHead, len(insert.Rules))
for i, r := range insert.Rules {
news[i] = &share.CLUSRuleHead{
ID: r.ID,
CfgType: cfgType,
}
}
crhs = append(crhs[:toIdx], append(news, crhs[toIdx:]...)...)
// Put policy rule heads
clusHelper.PutPolicyRuleListTxn(txn, crhs)
if ok, err := txn.Apply(); err != nil {
log.WithFields(log.Fields{"error": err}).Error("")
restRespError(w, http.StatusInternalServerError, api.RESTErrFailWriteCluster)
return err
} else if !ok {
e := "Atomic write to the cluster failed"
log.Error(e)
restRespErrorMessage(w, http.StatusInternalServerError, api.RESTErrFailWriteCluster, e)
return err
}
return nil
}
func checkReadOnlyRules(scope string, crhs []*share.CLUSRuleHead, rules []*api.RESTPolicyRule, accWrite *access.AccessControl) (int, int, utils.Set, utils.Set, []uint32) {
var checkLocal, checkFed bool
switch scope {
case share.ScopeLocal:
checkLocal = true
case share.ScopeFed:
checkFed = true
default:
return 0, 0, utils.NewSet(), utils.NewSet(), nil
}
var errorIDs []uint32 // IDs of read-only rules that are deleted/modified in the 'rules' payload
var writableLearnedRules int
var writableUserCreatedRules int
readOnlyRuleIDs := utils.NewSet()
writableRuleIDs := utils.NewSet() // id of rules (based on scope) that can be modified by the caller
payloadRulesIDs := utils.NewSet() // all rules' id in rules param
accRead := accWrite.NewWithOp(access.AccessOPRead) // for finding out what policies could be in the rules param
for _, crh := range crhs {
if (checkFed && crh.CfgType == share.FederalCfg) || (checkLocal && crh.CfgType != share.FederalCfg) {
_, readable, writable := cacher.CheckPolicyRuleAccess(crh.ID, accRead, accWrite)
if writable {
writableRuleIDs.Add(crh.ID)
if crh.CfgType == share.Learned {
writableLearnedRules++
} else if crh.CfgType == share.UserCreated {
writableUserCreatedRules++
}
} else if readable {
readOnlyRuleIDs.Add(crh.ID)
}
}
}
for _, r := range rules {
if r.ID != api.PolicyAutoID {
payloadRulesIDs.Add(r.ID)
}
}
if readOnlyRuleIDs.Cardinality() > 0 {
// Check whether some read-only rules are deleted in payload:
if deletedIDs := readOnlyRuleIDs.Difference(payloadRulesIDs); deletedIDs.Cardinality() > 0 { // id in readOnlyRuleIDs but not in rulesIDs, meaning some read-only rules are deleted in payload
errorIDs = make([]uint32, 0, deletedIDs.Cardinality()+8)
for id := range deletedIDs.Iter() {
errorIDs = append(errorIDs, id.(uint32))
}
}
// Now check whether any read-only rule is modified in payload:
for _, rr := range rules {
if readOnlyRuleIDs.Contains(rr.ID) {
if rr.From == "" && rr.To == "" && rr.CfgType == "" && rr.Applications == nil {
// the rule is not modified. no need to compare
} else {
// the rule could be modified. need to compare to know the answer
if oldcr, _ := clusHelper.GetPolicyRule(rr.ID); oldcr != nil {
cachedRule := cacher.PolicyRule2REST(oldcr)
if !compareRESTRules(rr, cachedRule) {
errorIDs = append(errorIDs, rr.ID)
}
}
}
}
}
}
return writableLearnedRules, writableUserCreatedRules, readOnlyRuleIDs, writableRuleIDs, errorIDs
}
//-------------------------------------------------------------------------------------------------------------------------------------------------------
// caller rules param ignored entries in rules param note
//-------------------------------------------------------------------------------------------------------------------------------------------------------
// admin(scope=local) all rules fed/ground rules fed/ground rules are not affected during replacement
// nsUser(scope=local) rules this user can see fed/ground rules namespace-user-non-accessible rules are not affected during replacement
// fedAdmin(scope=local) all rules fed/ground rules fed/ground rules are not affected during replacement
// fedAdmin(scope=fed) all rules ground/learned/user-created rules ground/learned/user-created rules are not affected during replacement
//-------------------------------------------------------------------------------------------------------------------------------------------------------
// 1. rules param contains the whole (updated) rules list that this user can see/config. it's from GET("/v1/policy/rule") plus some update/delete/add operations
// 2. ground(crd) rules cannot be updated/deleted/added by this function
// 3. accessible learned rules can be deleted, but not updated, by this function
// 4. delRuleIDs param means ids of the learned rules to delete. nil/[] means do not delete any learned rule
func replacePolicyRule(scope string, w http.ResponseWriter, r *http.Request, rules []*api.RESTPolicyRule, delRuleIDs utils.Set,
acc *access.AccessControl) error {
log.Debug("")
// Policy modification requires the permission on both From/To of the policy
nsUser := false
nsLearnedRules := 0
nsUserCreatedRules := 0
readOnlyRuleIDs := utils.NewSet() // id of rules (based on scope) that can be viewed but not modified by the caller
accessibleRuleIDs := utils.NewSet() // id of rules (based on scope) that can be modified by the caller
lock, err := clusHelper.AcquireLock(share.CLUSLockPolicyKey, clusterLockWait)
if err != nil {
e := "Failed to acquire cluster lock"
log.WithFields(log.Fields{"error": err}).Error(e)
restRespErrorMessage(w, http.StatusInternalServerError, api.RESTErrFailLockCluster, e)
return err
}
defer clusHelper.ReleaseLock(lock)
accReadAll := access.NewReaderAccessControl()
groups := clusHelper.GetAllGroups(scope, accReadAll)
hosts := cacher.GetAllHosts(accReadAll)
// Read ID list from cluster
crhs := clusHelper.GetPolicyRuleList()
if !acc.HasGlobalPermissions(share.PERMS_RUNTIME_POLICIES, share.PERMS_RUNTIME_POLICIES) { // special treatment for namespace users
nsUser = true
var errorIDs []uint32
// A namespace user with rt_policy:w permission may be able to read a policy but not to modify it (i.e. in Authorize() only one of d1/d2 passes the authz)
// So it's possible those readable-but-not-writable policies are included in the rules param that we need to filter out those rules first before replacement with rules
nsLearnedRules, nsUserCreatedRules, readOnlyRuleIDs, accessibleRuleIDs, errorIDs = checkReadOnlyRules(scope, crhs, rules, acc)
if len(errorIDs) > 0 {
err := fmt.Errorf("Some rules are read-only to current login user and cannot be updated")
log.WithFields(log.Fields{"error": err, "ids": errorIDs}).Error("Request error")
restRespErrorReadOnlyRules(w, http.StatusBadRequest, api.RESTErrReadOnlyRules, err.Error(), errorIDs)
return err
}
}
del := utils.NewSet() // rules to delete eventually, could contain learned/user-created/federal rules
idInUse := utils.NewSet() // rest-created rule IDs in use (user-created rules when scope=local, federal rules when scope=fed)
keep := make([]*share.CLUSRuleHead, 0, len(rules)) // existing rh to keep (contains federal/ground rules when scope=local, contains local rules when scope=fed)
new := make([]*share.CLUSRuleHead, 0) // changed rh to use (contains learned/userCreated rules when scope=local, contains federal rules when scope=fed)
var accessibleLearnedSpotIndices []int // all accessible learned rh spots' indices in keep slice for namespace user
var accessibleUserSpotIndices []int // all accessible user-created rhspots' indices in keep slice for namespace user
var reusedLearnedSpotIndex, reusedUserSpotIndex int