forked from neuvector/neuvector
-
Notifications
You must be signed in to change notification settings - Fork 0
/
admission.go
1546 lines (1407 loc) · 50.7 KB
/
admission.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"
"fmt"
"io/ioutil"
"net/http"
"os"
"reflect"
"strconv"
"strings"
"time"
cmetav1 "github.com/ericchiang/k8s/apis/meta/v1"
"github.com/ghodss/yaml"
"github.com/julienschmidt/httprouter"
log "github.com/sirupsen/logrus"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"github.com/neuvector/neuvector/controller/access"
"github.com/neuvector/neuvector/controller/api"
"github.com/neuvector/neuvector/controller/cache"
"github.com/neuvector/neuvector/controller/common"
"github.com/neuvector/neuvector/controller/kv"
"github.com/neuvector/neuvector/controller/nvk8sapi/nvvalidatewebhookcfg"
"github.com/neuvector/neuvector/controller/nvk8sapi/nvvalidatewebhookcfg/admission"
"github.com/neuvector/neuvector/controller/resource"
"github.com/neuvector/neuvector/share"
"github.com/neuvector/neuvector/share/cluster"
"github.com/neuvector/neuvector/share/utils"
)
const (
_writeHeader = true
_noWriteHeader = false
)
type admissionRequestObject struct {
ApiVersion string `json:"apiVersion,omitempty"`
Kind string `json:"kind,omitempty"`
ObjectMeta metav1.ObjectMeta `json:"metadata,omitempty"`
}
func getAdmCtrlRuleTypes(query *restQuery, defScope string) ([]string, string) {
var ok bool
var scope string
ruleTypes := make([]string, 0, 4)
if query == nil {
scope = defScope
} else if scope, ok = query.pairs[api.QueryScope]; !ok { // if not specified, use default value
scope = defScope
}
if scope == share.ScopeLocal {
ruleTypes = append(ruleTypes, api.ValidatingExceptRuleType, api.ValidatingDenyRuleType)
} else if scope == share.ScopeFed {
ruleTypes = append(ruleTypes, share.FedAdmCtrlExceptRulesType, share.FedAdmCtrlDenyRulesType)
} else if scope == share.ScopeAll {
ruleTypes = append(ruleTypes, share.FedAdmCtrlExceptRulesType, share.FedAdmCtrlDenyRulesType, api.ValidatingExceptRuleType, api.ValidatingDenyRuleType)
}
return ruleTypes, scope
}
func getRuleId(w http.ResponseWriter, ps httprouter.Params) (uint32, error) {
id, err := strconv.Atoi(ps.ByName("id"))
if err != nil || id <= 0 || id > 4294967295 {
log.WithFields(log.Fields{"id": id}).Error("Invalid ID")
restRespError(w, http.StatusBadRequest, api.RESTErrInvalidRequest)
return 0, common.ErrObjectNotFound
}
return uint32(id), nil
}
func validateAdmCtrlCriteria(criteria []*share.CLUSAdmRuleCriterion, options map[string]*api.RESTAdmissionRuleOption) error {
if criteria != nil && options == nil {
return fmt.Errorf("Invalid criteria options")
}
numOps := utils.NewSet(share.CriteriaOpLessEqualThan, share.CriteriaOpBiggerEqualThan, share.CriteriaOpBiggerThan)
for _, crt := range criteria {
var allowedOp, allowedValue bool
if option, exist := options[crt.Name]; exist {
if len(option.Ops) == 0 {
allowedOp = true
} else {
for _, op := range option.Ops {
if op == crt.Op {
allowedOp = true
break
}
}
}
if len(option.Values) > 0 {
for _, value := range option.Values {
if value == crt.Value {
allowedValue = true
break
}
}
} else {
numberVal := false
for _, opOption := range option.Ops {
if numOps.Contains(opOption) {
numberVal = true
break
}
}
if numberVal {
if _, err := strconv.ParseFloat(crt.Value, 64); err == nil {
allowedValue = true // meaning any valid float value is allowed
}
} else {
allowedValue = true // meaning any valid float value is allowed
}
}
if !allowedOp {
return fmt.Errorf("Invalid criterion operator: %s", crt.Op)
}
if !allowedValue {
return fmt.Errorf("Invalid criterion value: %s", crt.Value)
}
if crt.Name == share.CriteriaKeyCVEScoreCount && len(crt.SubCriteria) == 0 {
crt.SubCriteria = []*share.CLUSAdmRuleCriterion{
&share.CLUSAdmRuleCriterion{
Name: share.SubCriteriaCount,
Op: share.CriteriaOpBiggerEqualThan,
Value: "1",
},
}
}
if len(crt.SubCriteria) > 0 {
if err := validateAdmCtrlCriteria(crt.SubCriteria, option.SubOptions); err != nil {
return err
}
}
} else {
return fmt.Errorf("Unsupported criterion name: %s", crt.Name)
}
}
return nil
}
// cluster lock is owned by caller
func setAdmCtrlStateInCluster(enable *bool, mode, defaultAction, admClientMode, failurePolicy *string,
cfgType share.TCfgType) (int, int, *share.CLUSAdmissionState, *share.CLUSAdmissionState) {
var cconf *share.CLUSAdmissionState
var rev uint64
var origConf *share.CLUSAdmissionState
retry := 0
for retry < retryClusterMax {
cconf, rev = clusHelper.GetAdmissionStateRev(resource.NvAdmSvcName)
if cconf == nil {
return http.StatusNotFound, api.RESTErrObjectNotFound, nil, nil
}
origConf = &share.CLUSAdmissionState{
Enable: cconf.Enable,
Mode: cconf.Mode,
DefaultAction: cconf.DefaultAction,
AdmClientMode: cconf.AdmClientMode,
FailurePolicy: cconf.FailurePolicy,
CfgType: cconf.CfgType,
}
// we should be notified by consul watcher and update cache in the handler function
if enable != nil {
cconf.Enable = *enable
if ctrlState, exist := cconf.CtrlStates[admission.NvAdmValidateType]; exist {
ctrlState.Enable = *enable
}
}
if mode != nil {
cconf.Mode = *mode
}
if defaultAction != nil {
cconf.DefaultAction = *defaultAction
}
if admClientMode != nil {
cconf.AdmClientMode = *admClientMode
}
/* do not allow admission control webhook's FailurePolicy to be configurable yet
if failurePolicy != nil {
cconf.FailurePolicy = *failurePolicy
}
*/
cconf.CfgType = cfgType
if err := clusHelper.PutAdmissionStateRev(resource.NvAdmSvcName, cconf, rev); err == nil {
break
}
retry++
}
if retry >= retryClusterMax {
return http.StatusInternalServerError, api.RESTErrFailWriteCluster, nil, nil
}
return http.StatusOK, 0, origConf, cconf
}
func sameRuleSettings(ruleCfg *api.RESTAdmissionRuleConfig, clusConf *share.CLUSAdmissionRule) bool { // return true means same settings
if (ruleCfg.Category != nil && *ruleCfg.Category != clusConf.Category) || (ruleCfg.Comment != nil && *ruleCfg.Comment != clusConf.Comment) {
return false
} else if ruleCfg.Criteria != nil {
if len(ruleCfg.Criteria) != len(clusConf.Criteria) {
return false
}
for idx, ruleCrt := range ruleCfg.Criteria {
clusCrt := clusConf.Criteria[idx]
if ruleCrt.Name != clusCrt.Name || ruleCrt.Op != clusCrt.Op || ruleCrt.Value != clusCrt.Value {
return false
}
}
}
return true
}
func getAdmissionRule(id uint32, acc *access.AccessControl) (*api.RESTAdmissionRule, error) {
var rule *api.RESTAdmissionRule
err := common.ErrObjectNotFound
var ruleType string
var ruleTypes []string
if id > api.StartingFedAdmRespRuleID && id < api.MaxFedAdmRespRuleID {
ruleTypes = []string{share.FedAdmCtrlExceptRulesType, share.FedAdmCtrlDenyRulesType}
} else {
ruleTypes = []string{api.ValidatingExceptRuleType, api.ValidatingDenyRuleType}
}
for _, ruleType = range ruleTypes {
if rule, err = cacher.GetAdmissionRule(admission.NvAdmValidateType, ruleType, id, acc); err == nil {
break
}
}
if err != nil {
log.WithFields(log.Fields{"id": id, "ruleType": ruleType, "error": err}).Error()
}
return rule, err
}
func applyTransact(w http.ResponseWriter, txn *cluster.ClusterTransact) error {
if ok, err := txn.Apply(); err != nil {
log.WithFields(log.Fields{"error": err}).Error()
if w != nil {
restRespError(w, http.StatusInternalServerError, api.RESTErrFailWriteCluster)
}
return err
} else if !ok {
e := "Atomic write to the cluster failed"
log.Error(e)
if w != nil {
restRespErrorMessage(w, http.StatusInternalServerError, api.RESTErrFailWriteCluster, e)
}
return fmt.Errorf(e)
}
return nil
}
func handlerAdmissionStatistics(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
log.WithFields(log.Fields{"URL": r.URL.String()}).Debug()
if !k8sPlatform {
restRespError(w, http.StatusPreconditionFailed, api.RESTErrAdmCtrlUnSupported)
return
}
acc, login := getAccessControl(w, r, "")
if acc == nil {
return
}
stats, err := cacher.GetAdmissionStats(acc)
if err != nil {
restRespNotFoundLogAccessDenied(w, login, err)
return
}
resp := api.RESTAdmissionStatsData{Stats: stats}
restRespSuccess(w, r, &resp, acc, login, nil, "Get admission control statistics")
}
func handlerGetAdmissionState(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
log.WithFields(log.Fields{"URL": r.URL.String()}).Debug()
acc, login := getAccessControl(w, r, "")
if acc == nil {
return
}
state, err := cacher.GetAdmissionState(acc)
if err != nil {
restRespNotFoundLogAccessDenied(w, login, err)
return
}
if k8sPlatform {
var ok bool
if ok, err = admission.VerifyAdmClusterRole(); ok {
_, err = admission.VerifyAdmClusterRoleBinding()
}
if err != nil {
restRespErrorMessage(w, http.StatusNotFound, api.RESTErrClusterRoleForAdmCtrl, err.Error())
return
}
}
/*[2019/Apr.] do not enable ConfigMap support for env vars yet
if !admission.VerifyConfigMapPermission() {
restRespError(w, http.StatusNotFound, api.RESTErrNvPermission)
return
}*/
if k8sPlatform {
var svcInfo *admission.ValidateWebhookSvcInfo
err, svcInfo = admission.GetValidateWebhookSvcInfo(resource.NvAdmSvcName)
if err != nil {
restRespError(w, http.StatusNotFound, svcInfo.Status)
return
}
state.AdmSvcType = &svcInfo.SvcType
state.FailurePolicy = state.FailurePolicy
/* do not allow admission control webhook's FailurePolicy to be configurable yet
if admission.IsNsSelectorSupported() {
state.FailurePolicyChangable = true
}
*/
state.AdmClientModeOptions = map[string]string{
share.AdmClientModeSvc: fmt.Sprintf("%s.%s.svc", resource.NvAdmSvcName, resource.NvAdmSvcNamespace),
share.AdmClientModeUrl: fmt.Sprintf("https://%s.%s.svc:%d", resource.NvAdmSvcName, resource.NvAdmSvcNamespace, svcInfo.SvcNodePort),
}
} else {
enable := false
mode := share.AdmCtrlModeProtect
defaultAction := share.AdmCtrlActionAllow
state = &api.RESTAdmissionState{
Enable: &enable,
Mode: &mode,
DefaultAction: &defaultAction,
}
}
var resp = api.RESTAdmissionConfigData{
State: state,
K8sEnv: k8sPlatform,
}
restRespSuccess(w, r, &resp, acc, login, nil, "Get admission control state")
}
func handlerPatchAdmissionState(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
log.WithFields(log.Fields{"URL": r.URL.String()}).Debug()
if !k8sPlatform {
restRespError(w, http.StatusPreconditionFailed, api.RESTErrAdmCtrlUnSupported)
return
}
acc, login := getAccessControl(w, r, "")
if acc == nil {
return
}
currState, err := cacher.GetAdmissionState(acc)
if err != nil {
restRespNotFoundLogAccessDenied(w, login, err)
return
} else {
if currState.CfgType == api.CfgTypeGround {
restRespError(w, http.StatusBadRequest, api.RESTErrOpNotAllowed)
return
}
}
var ok bool
if ok, err = admission.VerifyAdmClusterRole(); ok {
_, err = admission.VerifyAdmClusterRoleBinding()
}
if err != nil {
restRespErrorMessage(w, http.StatusNotFound, api.RESTErrClusterRoleForAdmCtrl, err.Error())
return
}
if err, svcInfo := admission.GetValidateWebhookSvcInfo(resource.NvAdmSvcName); err != nil {
restRespError(w, http.StatusNotFound, svcInfo.Status)
return
}
body, _ := ioutil.ReadAll(r.Body)
var rconf api.RESTAdmissionConfigData
err = json.Unmarshal(body, &rconf)
if err != nil || rconf.State == nil {
log.WithFields(log.Fields{"error": err}).Error("Request error")
restRespError(w, http.StatusBadRequest, api.RESTErrInvalidRequest)
return
}
state := rconf.State
if state == nil || (state.Mode != nil && *state.Mode != share.AdmCtrlModeMonitor && *state.Mode != share.AdmCtrlModeProtect) ||
(state.DefaultAction != nil && *state.DefaultAction != share.AdmCtrlActionAllow && *state.DefaultAction != share.AdmCtrlActionDeny) ||
(state.AdmClientMode != nil && *state.AdmClientMode != share.AdmClientModeSvc && *state.AdmClientMode != share.AdmClientModeUrl) {
log.Error("Request contains invalid data")
restRespError(w, http.StatusBadRequest, api.RESTErrInvalidRequest)
return
} else if state.FailurePolicy != nil {
/* do not allow admission control webhook's FailurePolicy to be configurable yet
invalidFailurePolicy := false
if admission.IsNsSelectorSupported() {
if *state.FailurePolicy != resource.IgnoreLower && *state.FailurePolicy != resource.FailLower {
invalidFailurePolicy = true
}
} else if state.FailurePolicy != nil && *state.FailurePolicy != *currState.FailurePolicy {
invalidFailurePolicy = true
}
if invalidFailurePolicy {
e := fmt.Errorf("Request contains invalid FailurePolicy: %s", *state.FailurePolicy)
log.Error(e)
restRespErrorMessage(w, http.StatusBadRequest, api.RESTErrInvalidRequest, e.Error())
}
*/
}
if state.Mode != nil && *state.Mode == share.AdmCtrlModeProtect {
if licenseAllowEnforce() == false {
e := "The policy mode is not enabled in the license"
log.WithFields(log.Fields{"mode": *state.Mode}).Error(e)
restRespErrorMessage(w, http.StatusBadRequest, api.RESTErrLicenseFail, e)
}
}
if !*currState.Enable && (state.Enable == nil || !*state.Enable) && (state.Mode != nil || state.DefaultAction != nil || state.AdmClientMode != nil || state.FailurePolicy != nil) {
restRespError(w, http.StatusBadRequest, api.RESTErrWebhookIsDisabled)
return
}
var lock cluster.LockInterface
if lock, err = lockClusKey(w, share.CLUSLockAdmCtrlKey); err != nil {
return
}
defer clusHelper.ReleaseLock(lock)
status, code, origConf, cconf := setAdmCtrlStateInCluster(state.Enable, state.Mode, state.DefaultAction, state.AdmClientMode, state.FailurePolicy, share.UserCreated)
if status != http.StatusOK {
restRespError(w, status, code)
return
}
time.Sleep(time.Second)
const msg = "Patch admission control state"
var msgState string
msgFinal := msg
if cconf.Enable {
msgState = "enabled"
} else {
msgState = "disabled"
}
if ctrlState, exist := cconf.CtrlStates[admission.NvAdmValidateType]; exist {
admClientMode := origConf.AdmClientMode
if state.AdmClientMode != nil {
admClientMode = *state.AdmClientMode
}
/* do not allow admission control webhook's FailurePolicy to be configurable yet
failurePolicy := origConf.FailurePolicy
if state.FailurePolicy != nil {
failurePolicy = *state.FailurePolicy
}
if failurePolicy == resource.FailLower {
failurePolicy = resource.Fail
} else {
failurePolicy = resource.Ignore
}
*/
failurePolicy := resource.Ignore
k8sResInfo := admission.ValidatingWebhookConfigInfo{
Name: resource.NvAdmValidatingName,
WebhooksInfo: []*admission.WebhookInfo{
&admission.WebhookInfo{
Name: resource.NvAdmValidatingWebhookName,
ClientConfig: admission.ClientConfig{
ClientMode: admClientMode,
ServiceName: resource.NvAdmSvcName,
Path: ctrlState.Uri,
},
FailurePolicy: failurePolicy,
TimeoutSeconds: resource.DefTimeoutSeconds,
},
&admission.WebhookInfo{
Name: resource.NvStatusValidatingWebhookName,
ClientConfig: admission.ClientConfig{
ClientMode: admClientMode,
ServiceName: resource.NvAdmSvcName,
Path: ctrlState.NvStatusUri,
},
FailurePolicy: resource.Ignore,
TimeoutSeconds: resource.DefTimeoutSeconds,
},
},
}
skip, err := admission.ConfigK8sAdmissionControl(k8sResInfo, ctrlState)
if !skip {
var id share.TLogEvent
admResult := &nvsysadmission.AdmResult{}
if err == nil {
id = share.CLUSEvAdmCtrlK8sConfigured
admResult.Msg = fmt.Sprintf("Admission control is %s.", msgState)
} else {
id = share.CLUSEvAdmCtrlK8sConfigFailed
admResult.Msg = "Failed to configure admission control state."
}
cacher.CacheAdmCtrlEvent(id, admResult)
}
if err == nil {
messages := make([]string, 0, 3)
if cconf.Enable != origConf.Enable {
messages = append(messages, fmt.Sprintf("state: %s", msgState))
}
if len(cconf.Mode) > 0 && cconf.Mode != origConf.Mode {
messages = append(messages, fmt.Sprintf("mode: %s", *state.Mode))
}
if len(cconf.DefaultAction) > 0 && cconf.DefaultAction != origConf.DefaultAction {
messages = append(messages, fmt.Sprintf("default action: %s", *state.DefaultAction))
}
if len(cconf.AdmClientMode) > 0 && cconf.AdmClientMode != origConf.AdmClientMode {
messages = append(messages, fmt.Sprintf("client mode: %s", *state.AdmClientMode))
}
/* do not allow admission control webhook's FailurePolicy to be configurable yet
if len(cconf.FailurePolicy) > 0 && cconf.FailurePolicy != origConf.FailurePolicy {
messages = append(messages, fmt.Sprintf("failure policy: %s", *state.FailurePolicy))
}
*/
if len(messages) > 0 {
msgFinal = fmt.Sprintf("%s (%s)", msgFinal, strings.Join(messages, ", "))
}
} else {
log.WithFields(log.Fields{"origConf": origConf, "err": err}).Info("Gonna revert admission control state in cluster")
status, code, _, _ := setAdmCtrlStateInCluster(&origConf.Enable, &origConf.Mode, &origConf.DefaultAction, &origConf.AdmClientMode, &origConf.FailurePolicy, share.UserCreated)
if status != http.StatusOK {
log.WithFields(log.Fields{"status": status, "code": code}).Info("Failed to revert admission control state in cluster")
}
restRespErrorMessage(w, http.StatusInternalServerError, api.RESTErrFailKubernetesApi, err.Error())
return
}
}
restRespSuccess(w, r, nil, acc, login, &rconf, msgFinal)
}
func handlerGetAdmissionOptions(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
log.WithFields(log.Fields{"URL": r.URL.String()}).Debug()
acc, login := getAccessControl(w, r, "")
if acc == nil {
return
} else if !acc.Authorize(&share.CLUSAdmissionState{}, nil) {
restRespAccessDenied(w, login)
return
}
resp := &api.RESTAdmissionConfigData{
Options: &api.RESTAdmRuleTypeOptions{
DenyOptions: nvsysadmission.GetAdmRuleTypeOptions(api.ValidatingDenyRuleType),
ExceptionOptions: nvsysadmission.GetAdmRuleTypeOptions(api.ValidatingExceptRuleType),
},
K8sEnv: k8sPlatform,
}
keys := []string{share.CriteriaKeyRunAsPrivileged, share.CriteriaKeyRunAsRoot, share.CriteriaKeySharePidWithHost,
share.CriteriaKeyShareIpcWithHost, share.CriteriaKeyShareNetWithHost, share.CriteriaKeyAllowPrivEscalation}
pspCollection := make([]*api.RESTAdmRuleCriterion, 0, 6)
for _, key := range keys {
crit := &api.RESTAdmRuleCriterion{
Name: key,
Op: share.CriteriaOpEqual,
Value: "true",
}
pspCollection = append(pspCollection, crit)
}
resp.Options.PspCollection = pspCollection
restRespSuccess(w, r, resp, acc, login, nil, "Get admission control rule options")
}
// caller has been verified for federal admin access right
func replaceFedAdmissionRules(ruleType string, rulesNew *share.CLUSAdmissionRules) bool {
if ruleType != share.FedAdmCtrlExceptRulesType && ruleType != share.FedAdmCtrlDenyRulesType {
return false
}
var err error
var lock cluster.LockInterface
if lock, err = lockClusKey(nil, share.CLUSLockAdmCtrlKey); err != nil {
return false
}
defer clusHelper.ReleaseLock(lock)
// get current rules header list first
rhsExisting, _ := clusHelper.GetAdmissionRuleList(admission.NvAdmValidateType, ruleType)
// count total modified keys because of transaction's 64 keys limit
modKeysCount := 0
rhlChanged := false
delRules := make([]uint32, 0, len(rhsExisting))
patchedRules := make(map[uint32]*share.CLUSAdmissionRule, len(rulesNew.RuleMap))
for _, rhExisting := range rhsExisting {
if _, ok := rulesNew.RuleMap[rhExisting.ID]; !ok {
delRules = append(delRules, rhExisting.ID)
}
}
for _, ruleNew := range rulesNew.RuleMap {
if ruleNew != nil {
ruleExisting := clusHelper.GetAdmissionRule(admission.NvAdmValidateType, ruleType, ruleNew.ID)
if ruleExisting == nil || !reflect.DeepEqual(*ruleNew, *ruleExisting) {
patchedRules[ruleNew.ID] = ruleNew
}
}
}
if !reflect.DeepEqual(rulesNew.RuleHeads, rhsExisting) {
rhlChanged = true
modKeysCount++
}
modKeysCount += len(delRules)
modKeysCount += len(patchedRules)
if modKeysCount < _maxTransacKeys { // less then 64 keys modified. use transaction
txn := cluster.Transact()
defer txn.Close()
// delete obsolete id keys
for _, id := range delRules {
clusHelper.DeleteAdmissionRuleTxn(txn, admission.NvAdmValidateType, ruleType, id)
}
// write updated id keys
for _, ruleNew := range patchedRules {
clusHelper.PutAdmissionRuleTxn(txn, admission.NvAdmValidateType, ruleType, ruleNew)
}
// overwrite rule headers list
if rhlChanged {
clusHelper.PutAdmissionRuleListTxn(txn, admission.NvAdmValidateType, ruleType, rulesNew.RuleHeads)
}
return applyTransact(nil, txn) == nil
} else {
// delete obsolete id keys
for _, id := range delRules {
clusHelper.DeleteAdmissionRule(admission.NvAdmValidateType, ruleType, id)
}
// write updated id keys
for _, ruleNew := range patchedRules {
clusHelper.PutAdmissionRule(admission.NvAdmValidateType, ruleType, ruleNew)
}
// overwrite rule headers list
if rhlChanged {
if err := clusHelper.PutAdmissionRuleList(admission.NvAdmValidateType, ruleType, rulesNew.RuleHeads); err != nil {
return false
}
}
}
return true
}
func handlerGetAdmissionRules(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
log.WithFields(log.Fields{"URL": r.URL.String()}).Debug()
acc, login := getAccessControl(w, r, "")
if acc == nil {
return
}
query := restParseQuery(r)
ruleTypes, _ := getAdmCtrlRuleTypes(query, share.ScopeAll) // internal rule types: "exception", "deny", "fed_admctrl_exception" or "fed_admctrl_deny"
if len(ruleTypes) == 0 {
restRespError(w, http.StatusBadRequest, api.RESTErrInvalidRequest)
return
}
allRules := make(map[string][]*api.RESTAdmissionRule, 7)
for _, ruleType := range ruleTypes {
rules := cacher.GetAdmissionRules(admission.NvAdmValidateType, ruleType, acc)
switch ruleType {
case share.FedAdmCtrlExceptRulesType, share.FedAdmCtrlDenyRulesType:
allRules[ruleType] = rules
case api.ValidatingExceptRuleType, api.ValidatingDenyRuleType:
critRules := make([]*api.RESTAdmissionRule, 0, 4)
crdRules := make([]*api.RESTAdmissionRule, 0, len(rules))
userRules := make([]*api.RESTAdmissionRule, 0, len(rules))
for _, rule := range rules {
if rule.Critical {
critRules = append(critRules, rule)
} else if rule.CfgType == api.CfgTypeGround {
crdRules = append(crdRules, rule)
} else {
userRules = append(userRules, rule)
}
}
if ruleType == api.ValidatingExceptRuleType {
allRules[share.CriticalAdmCtrlExceptRulesType] = critRules
allRules[share.CrdAdmCtrlExceptRulesType] = crdRules
} else {
allRules[share.CrdAdmCtrlDenyRulesType] = crdRules
}
allRules[ruleType] = userRules
}
}
totalCount := 0
for _, rules := range allRules {
totalCount += len(rules)
}
// query.start: start idx(inclusive) of the rule to get in the union of all admission rules
end := totalCount // end idx(exclusive) of the rule to get in the union of all admission rules
if query.limit > 0 && query.limit < totalCount {
end = query.start + query.limit
}
// ruleTypes is in display order
ruleTypes = []string{share.CriticalAdmCtrlExceptRulesType, share.FedAdmCtrlExceptRulesType, share.FedAdmCtrlDenyRulesType,
share.CrdAdmCtrlExceptRulesType, share.CrdAdmCtrlDenyRulesType, api.ValidatingExceptRuleType, api.ValidatingDenyRuleType}
resp := api.RESTAdmissionRulesData{Rules: make([]*api.RESTAdmissionRule, 0, end-query.start)}
startIdxTotal := 0 // current idx in the union of all admission rules
for _, ruleType := range ruleTypes {
if rules, ok := allRules[ruleType]; ok && len(rules) > 0 {
endIdxTotal := startIdxTotal + len(rules) // idx of the last rule(for this rule type) in the union of all admission rules
if (endIdxTotal < query.start) || (startIdxTotal >= end) {
startIdxTotal += len(rules)
continue
}
endIdxTotal = startIdxTotal + len(rules)
collectStartIdx := 0 // start idx(inclusive) of the rule to collect in this rule type
collectEndIdx := len(rules) // end idx(exclusive) of the rule to collect in this rule type
if startIdxTotal < query.start {
collectStartIdx = query.start - startIdxTotal
}
if endIdxTotal > end {
collectEndIdx = len(rules) - (endIdxTotal - end)
}
target := rules[collectStartIdx:collectEndIdx]
resp.Rules = append(resp.Rules, target...)
startIdxTotal += len(rules)
}
}
restRespSuccess(w, r, &resp, acc, login, nil, "Get admission control rules list")
}
// caller must own CLUSLockAdmCtrlKey lock
func deleteAdmissionRules(w http.ResponseWriter, scope string, ruleTypeKeys []string, acc *access.AccessControl) (error, []string) {
type delRulesMetadata struct {
delRules utils.Set // id of rules to delete
keepRuleList []*share.CLUSRuleHead // new rule head list after deletion
}
delRuleTypes := make(map[string]*delRulesMetadata, len(ruleTypeKeys))
for _, ruleTypeKey := range ruleTypeKeys {
cachedRules := cacher.GetAdmissionRules(admission.NvAdmValidateType, ruleTypeKey, acc)
if len(cachedRules) == 0 {
continue
}
keepRules := make([]*share.CLUSRuleHead, 0)
delRules := utils.NewSet()
for _, cr := range cachedRules {
if cr.Critical || (scope == share.ScopeLocal && cr.CfgType != api.CfgTypeUserCreated) ||
(scope == share.ScopeFed && cr.CfgType != api.CfgTypeFederal) {
continue
}
delRules.Add(cr.ID)
}
delRuleType := &delRulesMetadata{delRules: utils.NewSet()}
delRuleTypes[ruleTypeKey] = delRuleType
arhs, _ := clusHelper.GetAdmissionRuleList(admission.NvAdmValidateType, ruleTypeKey)
for _, arh := range arhs {
if delRules.Contains(arh.ID) {
delRuleType.delRules.Add(arh.ID)
} else {
keepRules = append(keepRules, arh)
}
}
delRuleType.keepRuleList = keepRules
}
modKeysCount := 0
for _, delRuleType := range delRuleTypes {
modKeysCount += delRuleType.delRules.Cardinality()
modKeysCount++
}
delFedRuleTypes := make([]string, 0, 2)
if modKeysCount < _maxTransacKeys {
txn := cluster.Transact()
txn.Close()
for ruleTypeKey, delRuleType := range delRuleTypes {
clusHelper.PutAdmissionRuleListTxn(txn, admission.NvAdmValidateType, ruleTypeKey, delRuleType.keepRuleList)
for id := range delRuleType.delRules.Iter() {
clusHelper.DeleteAdmissionRuleTxn(txn, admission.NvAdmValidateType, ruleTypeKey, id.(uint32))
}
if ruleTypeKey == share.FedAdmCtrlExceptRulesType || ruleTypeKey == share.FedAdmCtrlDenyRulesType {
delFedRuleTypes = append(delFedRuleTypes, ruleTypeKey)
}
}
if err := applyTransact(w, txn); err != nil {
return err, nil
}
} else {
for ruleTypeKey, delRuleType := range delRuleTypes {
if err := clusHelper.PutAdmissionRuleList(admission.NvAdmValidateType, ruleTypeKey, delRuleType.keepRuleList); err != nil {
break
} else {
for id := range delRuleType.delRules.Iter() {
clusHelper.DeleteAdmissionRule(admission.NvAdmValidateType, ruleTypeKey, id.(uint32))
}
if ruleTypeKey == share.FedAdmCtrlExceptRulesType || ruleTypeKey == share.FedAdmCtrlDenyRulesType {
delFedRuleTypes = append(delFedRuleTypes, ruleTypeKey)
}
}
}
}
return nil, delFedRuleTypes
}
func handlerDeleteAdmissionRules(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
log.WithFields(log.Fields{"URL": r.URL.String()}).Debug()
acc, login := getAccessControl(w, r, "")
if acc == nil {
return
} else if !acc.HasGlobalPermissions(0, share.PERM_ADM_CONTROL) {
restRespAccessDenied(w, login)
return
}
query := restParseQuery(r)
ruleTypeKeys, scope := getAdmCtrlRuleTypes(query, share.ScopeLocal) // internal rule types: "exception", "deny", "fed_admctrl_exception" or "fed_admctrl_deny"
if scope != share.ScopeFed && scope != share.ScopeLocal {
restRespError(w, http.StatusBadRequest, api.RESTErrInvalidRequest)
return
}
var err error
var lock cluster.LockInterface
if lock, err = lockClusKey(w, share.CLUSLockAdmCtrlKey); err != nil {
return
}
defer clusHelper.ReleaseLock(lock)
err, delFedRuleTypes := deleteAdmissionRules(w, scope, ruleTypeKeys, acc)
if len(delFedRuleTypes) > 0 {
updateFedRulesRevision(delFedRuleTypes, acc, login)
}
if err == nil {
restRespSuccess(w, r, nil, acc, login, nil, "Delete all admission control rules")
}
}
func handlerGetAdmissionRule(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
log.WithFields(log.Fields{"URL": r.URL.String()}).Debug()
acc, login := getAccessControl(w, r, "")
if acc == nil {
return
}
id, err := getRuleId(w, ps)
if err != nil {
restRespNotFoundLogAccessDenied(w, login, err)
return
}
rule, err := getAdmissionRule(id, acc)
if err != nil {
restRespNotFoundLogAccessDenied(w, login, err)
return
}
resp := api.RESTAdmissionRuleData{Rule: rule}
restRespSuccess(w, r, &resp, acc, login, nil, "Get admission control rule")
}
func handlerAddAdmissionRule(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
log.WithFields(log.Fields{"URL": r.URL.String()}).Debug()
acc, login := getAccessControl(w, r, "")
if acc == nil {
return
}
var confData api.RESTAdmissionRuleConfigData
body, _ := ioutil.ReadAll(r.Body)
err := json.Unmarshal(body, &confData)
if err != nil || confData.Config == nil {
log.WithFields(log.Fields{"error": err}).Error("Request error")
restRespError(w, http.StatusBadRequest, api.RESTErrInvalidRequest)
return
}
ruleCfg := confData.Config
cfgType, _ := cfgTypeMapping[ruleCfg.CfgType]
if (cfgType != share.UserCreated && cfgType != share.FederalCfg) ||
(ruleCfg.RuleType != api.ValidatingExceptRuleType && ruleCfg.RuleType != api.ValidatingDenyRuleType) {
restRespError(w, http.StatusBadRequest, api.RESTErrInvalidRequest)
return
}
if !acc.Authorize(&share.CLUSAdmissionRule{CfgType: cfgType}, nil) {
restRespAccessDenied(w, login)
return
}
var ruleTypeKey string // "exception", "deny", "fed_admctrl_exception" or "fed_admctrl_deny"
if cfgType == share.FederalCfg {
if ruleCfg.RuleType == api.ValidatingExceptRuleType {
ruleTypeKey = share.FedAdmCtrlExceptRulesType
} else if ruleCfg.RuleType == api.ValidatingDenyRuleType {
ruleTypeKey = share.FedAdmCtrlDenyRulesType
}
} else {
ruleTypeKey = ruleCfg.RuleType
}
if ruleCfg.ID != 0 {
if _, err := getAdmissionRule(ruleCfg.ID, acc); err == nil {
restRespError(w, http.StatusBadRequest, api.RESTErrInvalidRequest)
return
}
}
var lock cluster.LockInterface
if lock, err = lockClusKey(w, share.CLUSLockAdmCtrlKey); err != nil {
return
}
defer clusHelper.ReleaseLock(lock)
ids := utils.NewSet()
var arhsAll [2][]*share.CLUSRuleHead
if cfgType == share.FederalCfg {
arhsAll[0], _ = clusHelper.GetAdmissionRuleList(admission.NvAdmValidateType, share.FedAdmCtrlExceptRulesType)
arhsAll[1], _ = clusHelper.GetAdmissionRuleList(admission.NvAdmValidateType, share.FedAdmCtrlDenyRulesType)
} else {
arhsAll[0], _ = clusHelper.GetAdmissionRuleList(admission.NvAdmValidateType, api.ValidatingExceptRuleType)
arhsAll[1], _ = clusHelper.GetAdmissionRuleList(admission.NvAdmValidateType, api.ValidatingDenyRuleType)
}
for _, arhs := range arhsAll {
for _, arh := range arhs {
ids.Add(arh.ID)
}
}
ruleCfg.ID = getAvailableRuleID(ruleTypeAdmCtrl, ids, cfgType)
if ruleCfg.ID == 0 {
// if the POST request specifies a rule ID that alreadys exists, return error
restRespError(w, http.StatusInternalServerError, api.RESTErrClusterWrongData)
return
}
clusConf := &share.CLUSAdmissionRule{ID: ruleCfg.ID, CfgType: cfgType, RuleType: ruleCfg.RuleType}
clusConf.Category = admission.AdmRuleCatK8s
if ruleCfg.Comment != nil {
clusConf.Comment = *ruleCfg.Comment
}
if ruleCfg.Criteria != nil {
clusConf.Criteria, err = cache.AdmCriteria2CLUS(ruleCfg.Criteria)
if err != nil {
restRespErrorMessage(w, http.StatusBadRequest, api.RESTErrInvalidRequest, err.Error())
return
}
}
if ruleCfg.Disable != nil {
clusConf.Disable = *ruleCfg.Disable
}
ruleOptions := nvsysadmission.GetAdmRuleTypeOptions(ruleCfg.RuleType)
if err := validateAdmCtrlCriteria(clusConf.Criteria, ruleOptions.K8sOptions.RuleOptions); err != nil {
log.WithFields(log.Fields{"error": err}).Error("Admission rule validation failed")
restRespErrorMessage(w, http.StatusBadRequest, api.RESTErrInvalidRequest, err.Error())
return
}
txn := cluster.Transact()
defer txn.Close()
clusHelper.PutAdmissionRuleTxn(txn, admission.NvAdmValidateType, ruleTypeKey, clusConf)
arhs, _ := clusHelper.GetAdmissionRuleList(admission.NvAdmValidateType, ruleTypeKey)
rh := &share.CLUSRuleHead{
ID: ruleCfg.ID,
CfgType: cfgType,
}
arhs = append(arhs, rh)
clusHelper.PutAdmissionRuleListTxn(txn, admission.NvAdmValidateType, ruleTypeKey, arhs)
if applyTransact(w, txn) != nil {
return
}
if cfgType == share.FederalCfg {
updateFedRulesRevision([]string{ruleTypeKey}, acc, login)
}
// returns the final rule ID that is created in response payload
resp := api.RESTAdmissionRuleData{
Rule: &api.RESTAdmissionRule{
ID: ruleCfg.ID,
Category: clusConf.Category,
Comment: clusConf.Comment,
Disable: clusConf.Disable,
Critical: clusConf.Critical,
CfgType: ruleCfg.CfgType,
RuleType: clusConf.RuleType,
},
}
if ruleCfg.Criteria != nil {
resp.Rule.Criteria = make([]*api.RESTAdmRuleCriterion, len(ruleCfg.Criteria))
for idx, c := range ruleCfg.Criteria {
resp.Rule.Criteria[idx] = c
}
}
restRespSuccess(w, r, &resp, acc, login, &confData, "Add admission control rule")
}
func handlerPatchAdmissionRule(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
log.WithFields(log.Fields{"URL": r.URL.String()}).Debug()