Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions enforcer/pkg/control/common/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -273,6 +273,7 @@ const (
REASON_VALID_SIG
REASON_VERIFIED_OWNER
REASON_UPDATE_BY_SA
REASON_VERIFIED_SA
REASON_NO_MUTATION
REASON_NOT_ENFORCED
REASON_SKIP_DELETE
Expand Down Expand Up @@ -306,6 +307,10 @@ var ReasonCodeMap = map[int]ReasonCode{
Message: "updated by creator",
Code: "updated-by-sa",
},
REASON_VERIFIED_SA: {
Message: "operated by verified sa",
Code: "verified-sa",
},
REASON_NO_MUTATION: {
Message: "allowed because no mutation found",
Code: "no-mutation",
Expand Down
48 changes: 25 additions & 23 deletions enforcer/pkg/control/common/reqcontext.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@ import (
logger "github.com/IBM/integrity-enforcer/enforcer/pkg/logger"
"github.com/IBM/integrity-enforcer/enforcer/pkg/mapnode"
v1beta1 "k8s.io/api/admission/v1beta1"
v1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/runtime/schema"
)

Expand All @@ -53,28 +52,27 @@ type ObjectMetadata struct {
}

type ReqContext struct {
RawObject []byte `json:"-"`
RawOldObject []byte `json:"-"`
RequestJsonStr string `json:"request"`
RequestUid string `json:"requestUid"`
Namespace string `json:"namespace"`
Name string `json:"name"`
ApiGroup string `json:"apiGroup"`
ApiVersion string `json:"apiVersion"`
Kind string `json:"kind"`
Operation string `json:"operation"`
IntegrityValue *IntegrityValue `json:"integrityValues"`
OrgMetadata *ObjectMetadata `json:"orgMetadata"`
ClaimedMetadata *ObjectMetadata `json:"claimedMetadata"`
UserInfo string `json:"userInfo"`
ObjLabels string `json:"objLabels"`
ObjMetaName string `json:"objMetaName"`
UserName string `json:"userName"`
UserGroups []string `json:"userGroups"`
Type string `json:"Type"`
ServiceAccount *v1.ServiceAccount `json:"serviceAccount"`
ObjectHashType string `json:"objectHashType"`
ObjectHash string `json:"objectHash"`
RawObject []byte `json:"-"`
RawOldObject []byte `json:"-"`
RequestJsonStr string `json:"request"`
RequestUid string `json:"requestUid"`
Namespace string `json:"namespace"`
Name string `json:"name"`
ApiGroup string `json:"apiGroup"`
ApiVersion string `json:"apiVersion"`
Kind string `json:"kind"`
Operation string `json:"operation"`
IntegrityValue *IntegrityValue `json:"integrityValues"`
OrgMetadata *ObjectMetadata `json:"orgMetadata"`
ClaimedMetadata *ObjectMetadata `json:"claimedMetadata"`
UserInfo string `json:"userInfo"`
ObjLabels string `json:"objLabels"`
ObjMetaName string `json:"objMetaName"`
UserName string `json:"userName"`
UserGroups []string `json:"userGroups"`
Type string `json:"Type"`
ObjectHashType string `json:"objectHashType"`
ObjectHash string `json:"objectHash"`
}

func (reqc *ReqContext) OwnerRef() *ResourceRef {
Expand Down Expand Up @@ -132,6 +130,10 @@ func (rc *ReqContext) IsSecret() bool {
return rc.Kind == "Secret" && rc.GroupVersion() == "v1"
}

func (rc *ReqContext) IsServiceAccount() bool {
return rc.Kind == "ServiceAccount" && rc.GroupVersion() == "v1"
}

type ParsedRequest struct {
UID string
JsonStr string
Expand Down
73 changes: 54 additions & 19 deletions enforcer/pkg/control/enforcer/checkcontext.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ import (
policy "github.com/IBM/integrity-enforcer/enforcer/pkg/policy"
log "github.com/sirupsen/logrus"
v1beta1 "k8s.io/api/admission/v1beta1"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

Expand All @@ -40,11 +41,12 @@ import (

type CheckContext struct {
// request context
config *config.EnforcerConfig
policy *policy.Policy
ReqC *common.ReqContext `json:"-"`
DryRun bool `json:"dryRun"`
Unverified bool `json:"unverified"`
config *config.EnforcerConfig
policy *policy.Policy
ReqC *common.ReqContext `json:"-"`
ServiceAccount *v1.ServiceAccount `json:"serviceAccount"`
DryRun bool `json:"dryRun"`
Unverified bool `json:"unverified"`

Result *CheckResult `json:"result"`

Expand All @@ -63,13 +65,14 @@ type CheckContext struct {
}

type CheckResult struct {
InternalRequest bool `json:"internal"`
AllowedByRule bool `json:"allowedByRule"`
PermitIfVerifiedOwner bool `json:"permitIfVerifiedOwner"`
PermitIfFirstUser bool `json:"permitIfFirstUser"`
SignPolicyEvalResult *common.SignPolicyEvalResult `json:"signpolicy"`
ResolveOwnerResult *common.ResolveOwnerResult `json:"owner"`
MutationEvalResult *common.MutationEvalResult `json:"mutation"`
InternalRequest bool `json:"internal"`
AllowedByRule bool `json:"allowedByRule"`
PermitIfVerifiedOwner bool `json:"permitIfVerifiedOwner"`
PermitIfFirstUser bool `json:"permitIfFirstUser"`
PermitIfVerifiedServiceAccount bool `json:"permitIfVerifiedServiceAccount"`
SignPolicyEvalResult *common.SignPolicyEvalResult `json:"signpolicy"`
ResolveOwnerResult *common.ResolveOwnerResult `json:"owner"`
MutationEvalResult *common.MutationEvalResult `json:"mutation"`
}

func NewCheckContext(config *config.EnforcerConfig, policy *policy.Policy) *CheckContext {
Expand Down Expand Up @@ -128,7 +131,7 @@ func (self *CheckContext) ProcessRequest(req *v1beta1.AdmissionRequest) *v1beta1
self.Result.InternalRequest = policyChecker.IsAllowedForInternalRequest()
self.Result.AllowedByRule = policyChecker.IsAllowedByRule()
self.Result.PermitIfVerifiedOwner = policyChecker.PermitIfVerifiedOwner()
self.Result.PermitIfFirstUser = policyChecker.PermitIfCreator()
self.Result.PermitIfVerifiedServiceAccount = policyChecker.PermitIfVerifiedServiceAccount()

if !self.Ignored && self.config.Log.ConsoleLog.IsInScope(self.ReqC) {
self.ConsoleLogEnabled = true
Expand Down Expand Up @@ -185,23 +188,26 @@ func (self *CheckContext) ProcessRequest(req *v1beta1.AdmissionRequest) *v1beta1
}

//resolve owner
if !self.Aborted && !allowed && self.ReqC.IsCreateRequest() {
if !self.Aborted && !allowed && self.ReqC.IsCreateRequest() && self.ReqC.IsServiceAccount() {
if r, err := self.resolveOwner(); err != nil {
self.abort("Error when resolving owner", err)
} else {
self.Result.ResolveOwnerResult = r
if self.Result.PermitIfVerifiedOwner &&
r.Checked && r.Verified {
r.Checked && r.Verified &&
self.IsVerifiedServiceAccount() {
allowed = true
evalReason = common.REASON_VERIFIED_OWNER
}
}
}

//update by first user
if !self.Aborted && !allowed && self.ReqC.IsUpdateRequest() && self.Result.PermitIfFirstUser {
//check verified user
if !self.Aborted && !allowed &&
self.Result.PermitIfVerifiedServiceAccount &&
self.IsVerifiedServiceAccount() {
allowed = true
evalReason = common.REASON_UPDATE_BY_SA
evalReason = common.REASON_VERIFIED_SA
}

//check mutation
Expand Down Expand Up @@ -310,7 +316,12 @@ func (self *CheckContext) createAdmissionResponse() *v1beta1.AdmissionResponse {
deleteKeys = append(deleteKeys, "integrityUnverified")
} else if self.Result.PermitIfVerifiedOwner &&
self.Result.ResolveOwnerResult.Checked &&
self.Result.ResolveOwnerResult.Verified {
self.Result.ResolveOwnerResult.Verified &&
self.IsVerifiedServiceAccount() {
annotations["integrityVerified"] = "true"
deleteKeys = append(deleteKeys, "integrityUnverified")
} else if self.Result.PermitIfVerifiedServiceAccount &&
self.IsVerifiedServiceAccount() {
annotations["integrityVerified"] = "true"
deleteKeys = append(deleteKeys, "integrityUnverified")
} else {
Expand Down Expand Up @@ -377,6 +388,30 @@ func (self *CheckContext) resolveOwner() (*common.ResolveOwnerResult, error) {
}
}

func (self *CheckContext) IsVerifiedServiceAccount() bool {

sa := self.ServiceAccount
if sa == nil {
v, err := GetServiceAccount(self.ReqC.UserName)
if err != nil || v == nil {
return false
}
sa = v
}

if self.ReqC.Namespace != sa.ObjectMeta.Namespace {
return false
}
if s, ok := sa.Annotations["integrityVerified"]; ok {
if b, err := strconv.ParseBool(s); err != nil {
return false
} else {
return b
}
}
return false
}

func (self *CheckContext) evalMutation() (*common.MutationEvalResult, error) {
reqc := self.ReqC
r := self.Result.ResolveOwnerResult
Expand Down
46 changes: 46 additions & 0 deletions enforcer/pkg/control/enforcer/serviceaccount.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
//
// Copyright 2020 IBM Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

package enforcer

import (
"strings"

"github.com/IBM/integrity-enforcer/enforcer/pkg/kubeutil"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
v1cli "k8s.io/client-go/kubernetes/typed/core/v1"
)

func GetServiceAccount(userName string) (*v1.ServiceAccount, error) {

if !strings.HasPrefix(userName, "system:") {
return nil, nil
}

config, err := kubeutil.GetKubeConfig()
if err != nil {
return nil, err
}
v1client := v1cli.NewForConfigOrDie(config)

name := strings.Split(userName, ":")
saName := name[len(name)-1]
namespace := name[len(name)-2]

return v1client.ServiceAccounts(namespace).Get(saName, metav1.GetOptions{})

}
5 changes: 1 addition & 4 deletions enforcer/pkg/policy/policy.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,6 @@ type Policy struct {
AllowedByRule []RequestMatchPattern `json:"allowedByRule,omitempty"`
AllowedChange []AllowedChangeCondition `json:"allowedChange,omitempty"`
PermitIfVerifiedOwner []AllowedUserPattern `json:"permitIfVerifiedOwner,omitempty"`
PermitIfCreator []AllowedUserPattern `json:"permitIfCreator,omitempty"`
Namespace string `json:"namespace,omitempty"`
PolicyType PolicyType `json:"policyType,omitempty"`
}
Expand All @@ -75,8 +74,7 @@ func (self *Policy) CheckFormat() (bool, string) {
hasAllowRule := len(self.AllowedByRule) > 0
hasAllowChange := len(self.AllowedChange) > 0
hasVOwner := len(self.PermitIfVerifiedOwner) > 0
hasFUser := len(self.PermitIfCreator) > 0
if hasEnforce || hasIgnore || hasInternal || hasAllowRule || hasAllowChange || hasVOwner || hasFUser {
if hasEnforce || hasIgnore || hasInternal || hasAllowRule || hasAllowChange || hasVOwner {
return false, fmt.Sprintf("%s must contain only AllowedSigner rule", pType)
}
}
Expand Down Expand Up @@ -197,7 +195,6 @@ func (p *Policy) Merge(p2 *Policy) *Policy {
AllowedByRule: append(p.AllowedByRule, p2.AllowedByRule...),
AllowedChange: append(p.AllowedChange, p2.AllowedChange...),
PermitIfVerifiedOwner: append(p.PermitIfVerifiedOwner, p2.PermitIfVerifiedOwner...),
PermitIfCreator: append(p.PermitIfCreator, p2.PermitIfCreator...),
AllowUnverified: append(p.AllowUnverified, p2.AllowUnverified...),
}
}
Loading