From aae1f4f87aeb8b7237aac6f3bd9d2ab88bd5ba71 Mon Sep 17 00:00:00 2001 From: Gaurav Chaudhary Date: Sat, 28 Nov 2026 22:50:14 +0530 Subject: [PATCH] fix(C-0225): harden RBAC and preserve default account provisioning Signed-off-by: Gaurav Chaudhary --- .github/workflows/main.yaml | 28 +++++++++++ .../default-serviceaccount-mutation.yaml | 29 +++++++++++ controls/C-0225/policy.yaml | 18 ++++--- controls/C-0225/tests.json | 49 +++++++++++++++++-- ...ault-service-account-rbac-and-automount.md | 23 ++++++--- 5 files changed, 128 insertions(+), 19 deletions(-) create mode 100644 controls/C-0225/default-serviceaccount-mutation.yaml diff --git a/.github/workflows/main.yaml b/.github/workflows/main.yaml index 2fabe66..ec1c52d 100644 --- a/.github/workflows/main.yaml +++ b/.github/workflows/main.yaml @@ -46,4 +46,32 @@ jobs: pip install -r requirements.txt python3 -m unittest discover -s scripts -p 'test_*.py' ./scripts/run-all-control-tests.sh + - name: Test C-0225 namespace provisioning + run: | + kubectl create -f controls/C-0225/default-serviceaccount-mutation.yaml + kubectl create -f controls/C-0225/policy.yaml + kubectl create -f - <<'EOF' + apiVersion: admissionregistration.k8s.io/v1 + kind: ValidatingAdmissionPolicyBinding + metadata: + name: c0225-provisioning-test + spec: + policyName: kubescape-c-0225-deny-default-service-account-rbac-and-automount + validationActions: [Deny] + EOF + # Confirm the validating binding is active before the controller creates the account. + for attempt in {1..30}; do + if ! output=$(kubectl -n default patch serviceaccount default --dry-run=server \ + --type=merge -p '{"automountServiceAccountToken":true}' 2>&1); then + break + fi + sleep 1 + done + printf '%s\n' "$output" + [[ "$output" == *"with binding 'c0225-provisioning-test' denied request"* && + "$output" == *"Set automountServiceAccountToken to false."* ]] + kubectl create namespace c0225-provisioning + kubectl -n c0225-provisioning wait --for=create serviceaccount/default --timeout=30s + kubectl -n c0225-provisioning wait --for=jsonpath='{.automountServiceAccountToken}'=false \ + serviceaccount/default --timeout=30s diff --git a/controls/C-0225/default-serviceaccount-mutation.yaml b/controls/C-0225/default-serviceaccount-mutation.yaml new file mode 100644 index 0000000..5035df8 --- /dev/null +++ b/controls/C-0225/default-serviceaccount-mutation.yaml @@ -0,0 +1,29 @@ +apiVersion: admissionregistration.k8s.io/v1 +kind: MutatingAdmissionPolicy +metadata: + name: kubescape-c-0225-default-serviceaccount-automount +spec: + failurePolicy: Fail + matchConstraints: + resourceRules: + - apiGroups: [""] + apiVersions: ["v1"] + operations: ["CREATE"] + resources: ["serviceaccounts"] + matchConditions: + - name: default-serviceaccount-without-automount-setting + expression: >- + has(object.metadata.name) && object.metadata.name == 'default' && + !has(object.automountServiceAccountToken) + reinvocationPolicy: Never + mutations: + - patchType: ApplyConfiguration + applyConfiguration: + expression: "Object{automountServiceAccountToken: false}" +--- +apiVersion: admissionregistration.k8s.io/v1 +kind: MutatingAdmissionPolicyBinding +metadata: + name: kubescape-c-0225-default-serviceaccount-automount +spec: + policyName: kubescape-c-0225-default-serviceaccount-automount diff --git a/controls/C-0225/policy.yaml b/controls/C-0225/policy.yaml index 5ec531d..241537c 100644 --- a/controls/C-0225/policy.yaml +++ b/controls/C-0225/policy.yaml @@ -41,28 +41,32 @@ spec: # Rule 1: nobody should be granting extra permissions to the `default` ServiceAccount, # which every pod in a namespace gets unless it names another one. # - # The bootstrap-label exemption is load bearing. Kubernetes labels its own built-in - # bindings with `kubernetes.io/bootstrapping: rbac-defaults`, and several of them bind - # the default ServiceAccount on purpose. Without this the policy fires on the cluster's - # own bindings everywhere and becomes noise. + # The API server reconciles built-in bindings through its privileged loopback + # client, including bindings to the all-ServiceAccounts group. Require that + # authenticated identity as well as the bootstrap label. - expression: > !(object.kind in ['RoleBinding','ClusterRoleBinding']) || !has(object.subjects) || ( + has(request.userInfo.username) && + request.userInfo.username == 'system:apiserver' && + has(request.userInfo.groups) && + 'system:masters' in request.userInfo.groups && has(object.metadata.labels) && 'kubernetes.io/bootstrapping' in object.metadata.labels && object.metadata.labels['kubernetes.io/bootstrapping'] == 'rbac-defaults' ) || object.subjects.all(subject, (subject.kind != 'ServiceAccount' || subject.name != 'default') && - (subject.kind != 'User' || !subject.name.matches('^system:serviceaccount:[^:]+:default$')) + (subject.kind != 'User' || !subject.name.matches('^system:serviceaccount:[^:]+:default$')) && + (subject.kind != 'Group' || !subject.name.matches('^system:serviceaccounts(:[^:]+)?$')) ) messageExpression: > object.kind + '/' + object.metadata.name + ' grants permissions to the default ServiceAccount, which every pod in the namespace gets by default. Bind a dedicated ServiceAccount instead. (see more at https://kubescape.io/docs/controls/c-0225/)' # Rule 2: the default ServiceAccount should not hand out its token automatically. # - # Unset fails as well as true. Kubernetes mounts the token when the field is absent, - # so silence means yes, same as C-0034. Only an explicit false passes. + # Only an explicit false passes. Install the companion mutating policy to + # supply it when Kubernetes creates the default ServiceAccount. - expression: > object.kind != 'ServiceAccount' || object.metadata.name != 'default' || diff --git a/controls/C-0225/tests.json b/controls/C-0225/tests.json index de70bfd..3f48494 100644 --- a/controls/C-0225/tests.json +++ b/controls/C-0225/tests.json @@ -45,9 +45,9 @@ ] }, { - "name": "RoleBinding granting the default ServiceAccount but carrying the bootstrap label is allowed, that is how Kubernetes marks its own bindings", + "name": "RoleBinding granting the default ServiceAccount is denied even with the bootstrap label", "template": "role-binding.yaml", - "expected": "pass", + "expected": "fail", "field_change_list": [ "subjects=[{\"kind\": \"ServiceAccount\", \"name\": \"default\", \"namespace\": \"default\"}]", "metadata.labels={\"admission-policy-test\": \"abc\", \"kubernetes.io/bootstrapping\": \"rbac-defaults\"}" @@ -76,9 +76,9 @@ "expected": "pass" }, { - "name": "ClusterRoleBinding granting the default ServiceAccount but carrying the bootstrap label is allowed", + "name": "ClusterRoleBinding granting the default ServiceAccount is denied even with the bootstrap label", "template": "cluster-role-binding.yaml", - "expected": "pass", + "expected": "fail", "field_change_list": [ "subjects=[{\"kind\": \"ServiceAccount\", \"name\": \"default\", \"namespace\": \"default\"}]", "metadata.labels={\"admission-policy-test\": \"abc\", \"kubernetes.io/bootstrapping\": \"rbac-defaults\"}" @@ -145,5 +145,46 @@ "field_change_list": [ "subjects=[{\"kind\": \"User\", \"name\": \"system:serviceaccount:test-namespace:my-app\", \"apiGroup\": \"rbac.authorization.k8s.io\"}]" ] + }, + { + "name": "RoleBinding granting the all-ServiceAccounts group is blocked", + "template": "role-binding.yaml", + "expected": "fail", + "field_change_list": [ + "subjects=[{\"kind\": \"Group\", \"name\": \"system:serviceaccounts\", \"apiGroup\": \"rbac.authorization.k8s.io\"}]" + ] + }, + { + "name": "RoleBinding granting the ServiceAccounts group from another namespace is blocked", + "template": "role-binding.yaml", + "expected": "fail", + "field_change_list": [ + "metadata.namespace=test-namespace", + "subjects=[{\"kind\": \"Group\", \"name\": \"system:serviceaccounts:default\", \"apiGroup\": \"rbac.authorization.k8s.io\"}]" + ] + }, + { + "name": "ClusterRoleBinding granting the all-ServiceAccounts group is blocked", + "template": "cluster-role-binding.yaml", + "expected": "fail", + "field_change_list": [ + "subjects=[{\"kind\": \"Group\", \"name\": \"system:serviceaccounts\", \"apiGroup\": \"rbac.authorization.k8s.io\"}]" + ] + }, + { + "name": "ClusterRoleBinding granting a namespace ServiceAccounts group is blocked", + "template": "cluster-role-binding.yaml", + "expected": "fail", + "field_change_list": [ + "subjects=[{\"kind\": \"Group\", \"name\": \"system:serviceaccounts:test-namespace\", \"apiGroup\": \"rbac.authorization.k8s.io\"}]" + ] + }, + { + "name": "RoleBinding granting an unrelated group is allowed", + "template": "role-binding.yaml", + "expected": "pass", + "field_change_list": [ + "subjects=[{\"kind\": \"Group\", \"name\": \"developers\", \"apiGroup\": \"rbac.authorization.k8s.io\"}]" + ] } ] diff --git a/docs/policies-based-on-kubescape-controls/kubescape-c-0225-deny-default-service-account-rbac-and-automount.md b/docs/policies-based-on-kubescape-controls/kubescape-c-0225-deny-default-service-account-rbac-and-automount.md index a680585..408749b 100644 --- a/docs/policies-based-on-kubescape-controls/kubescape-c-0225-deny-default-service-account-rbac-and-automount.md +++ b/docs/policies-based-on-kubescape-controls/kubescape-c-0225-deny-default-service-account-rbac-and-automount.md @@ -19,17 +19,24 @@ Two things follow, and this policy checks both. Granting the `default` ServiceAc This policy is two independent checks under one control ID, each matching different kinds. On a RoleBinding or ClusterRoleBinding: -* If any subject is a ServiceAccount named `default`, the binding is denied from being deployed in the cluster. -* Unless the binding carries the label `kubernetes.io/bootstrapping: rbac-defaults`, which is how Kubernetes marks its own built-in bindings. Several of those bind the `default` ServiceAccount on purpose, so without this exemption the policy would fire on the cluster's own RBAC in every namespace. +* The policy denies bindings to a ServiceAccount named `default`, to its fully qualified username, or to the Kubernetes group for all ServiceAccounts or all ServiceAccounts in one namespace. These groups include the default account even when the binding itself lives in another namespace. +* Kubernetes' API server can still reconcile its built-in bindings. The exemption requires both the API server's privileged loopback identity and the `kubernetes.io/bootstrapping: rbac-defaults` label. A live admission request supplies the identity. On a ServiceAccount: -* If it is named `default` and `automountServiceAccountToken` is not explicitly `false`, it is denied. -* An absent field counts as a failure, not a pass. Kubernetes mounts the token when nothing says otherwise, so silence means yes. This is the same reasoning as [C-0034](/docs/policies-based-on-kubescape-controls/kubescape-c-0034-deny-resources-with-automount-service-account-token-enabled.md). - -A ServiceAccount with any other name is not touched by this policy, whatever it does with its token. +* For the account named `default`, the validator requires an explicit `automountServiceAccountToken: false` after mutation, on both creation and update. +* The companion mutating policy fills in a missing field on creation. Kubernetes' ServiceAccount controller can therefore provision the account automatically. An explicit `true` is still denied. +* Dedicated ServiceAccounts can set their own token automount behavior. ## How to satisfy it: -Give each workload its own ServiceAccount, bind permissions to that, and set `automountServiceAccountToken: false` on the `default` one in every namespace so nothing picks up a token by accident. +Give each workload that needs permissions its own ServiceAccount and bind permissions to that account. Set `automountServiceAccountToken: false` on existing default ServiceAccounts. The companion policy applies to new accounts, including accounts the controller recreates. ## Implementing this policy in the Cluster: -[Refer here for using the policy in the cluster](https://github.com/kubescape/cel-admission-library#using-the-library) +Install and bind mutation before enabling the validating binding with the `Deny` action. Kubernetes creates each default ServiceAccount without the field, so validation alone blocks that provisioning. + +On Kubernetes 1.36 and later, install the [companion mutating policy and binding](/controls/C-0225/default-serviceaccount-mutation.yaml) from the same checkout as the validator. + +```sh +kubectl apply -f controls/C-0225/default-serviceaccount-mutation.yaml +``` + +On clusters without the stable MutatingAdmissionPolicy API, use a mutating admission webhook to set the missing field to `false` on CREATE for the default ServiceAccount. Ensure the mutator covers every namespace where the validating binding applies. See the [Kubernetes mutating admission policy documentation](https://kubernetes.io/docs/reference/access-authn-authz/mutating-admission-policy/) and the [library installation instructions](https://github.com/kubescape/cel-admission-library#using-the-library).