Repository navigation
feat(rbac): combination-escalation predicates (escalate, bind, impersonate, privileged pod + SA) - #105
Conversation
0180e8f to
2691c71
Compare
rrskris
left a comment
There was a problem hiding this comment.
First, the roadmap decision, because it's the bigger question and it goes your way: I'm accepting this as the Effective Access Graph foundation. #85 was originally scoped to build on #84 (build_effective_access()), which nobody ever started. You didn't wait, built your own subject-aggregation in effective_access.py, and it's the right shape — so #84 gets closed as superseded by this, and #86/#87/#88 get re-pointed at effective_access.py rather than the API that never materialised. _flatten_rules_for_subject + evaluate_combo_findings become the canonical aggregation path. Thank you for pushing ahead instead of waiting on absent work.
I ran the suite (19/19, 96 total) and then went through the logic with a reproducer rather than by eye. The predicates themselves are sound — aggregating across every binding before testing verb combinations is exactly the insight #85 was asking for, and treating escalate/bind as the second half of a two-part grant is correct. One thing needs fixing before I merge, because this becomes the base for three more issues.
Required: privileged_pod_creation false-positives across unrelated namespaces
_build_privileged_namespaces() records s.get("namespace") for privileged SA subjects. When a ServiceAccount subject has no namespace key, that inserts None into the set — and then line 324's or None in privileged_namespaces makes every pod-creating subject in the graph match, regardless of namespace.
Reproducer — innocent lives in a namespace with no privileged SA anywhere near it:
g = {'roles': [], 'cluster_roles': [
{'name':'admin','kind':'ClusterRole','rules':[{'verbs':['*'],'resources':['*'],'api_groups':['*']}]},
{'name':'podmaker','kind':'ClusterRole','rules':[{'verbs':['create'],'resources':['pods'],'api_groups':['']}]}],
'role_bindings': [], 'cluster_role_bindings': [
{'name':'priv','roleRef':{'kind':'ClusterRole','name':'admin'},
'subjects':[{'kind':'ServiceAccount','name':'powerful'}]}, # no namespace
{'name':'pods','roleRef':{'kind':'ClusterRole','name':'podmaker'},
'subjects':[{'kind':'ServiceAccount','name':'innocent','namespace':'totally-unrelated-ns'}]}]}privileged_namespaces = {None}
...
privileged_pod_creation subject=innocent ns=totally-unrelated-ns ← false positive
The root cause is a docstring/code disagreement worth resolving explicitly: _build_privileged_namespaces documents None = cluster scope, and line 324 treats None as "a cluster-scope privileged SA, so every namespace is in scope". But the builder never intentionally adds None — it only ever adds a concrete SA namespace, so None only ever appears from missing input. Either skip SA subjects with no namespace (a real ServiceAccount always has one), or, if cluster-scope propagation was the intent, record it under a distinct sentinel instead of None so the two cases can't be confused.
Worth fixing rather than deferring because this PR itself opens the paths that reach it: POST /combo-scan invites hand-written graphs where omitting namespace is trivial, and --manifests mode parses YAML that can be an unrendered template. Live-cluster mode is safe — the apiserver requires the field.
A test pinning "privileged SA in namespace A does not flag a pod-creator in namespace B" would lock it down.
Non-blocking — happy to merge without these
role_indexusesr["name"]while everything else uses.get().evaluate_combo_findings({'cluster_roles':[{'kind':'ClusterRole','rules':[]}]}, {})raisesKeyError: 'name', which surfaces as a 500 from/combo-scanrather than a clean 422. Now reachable since the endpoint takes arbitrary bodies.- Predicates ignore
api_groups._has_resourcematches on resource name alone, soimpersonateon ausersresource in some unrelated API group would fire. Your demo graph setsapi_groupscorrectly, but the predicates never read it. _flatten_rules_for_subject(subject_key, all_bindings, ...)re-scans every binding for every subject — quadratic — whensubject_to_bindings[key]already holds exactly the bindings for that subject. Passingbindingsinstead makes it linear and drops the inner_subject_keycomparison./combo-scanscores against a hardcoded_DEFAULT_CONTEXTinstead of the tenant's storedScanContext. Every other scoring path resolves context from the tenant —scan_rbac()doescve_service._context_to_dict(cve_service.get_or_create_scan_context(db, tenant_id)). As written, a PCI/PHI tenant gets combo findings silently scored as production/internal with no compliance scope. Takingdb: Session = Depends(get_db)and defaulting to the tenant's context (lettingbody.contextoverride) would make it consistent.- No body-size guard on
/combo-scan. The comparable ingest design indocs/trivy-grype-integration.mdmandates one (env var, default 20 MB); this evaluates an unbounded user-supplied graph. GET /combo-scan/demois well outside #85 and lands permanently in the public OpenAPI surface at/docs. Genuinely useful for smoke-testing, so I'd rather keep the capability than delete it — but as a fixture underhack/dev/or a test, not a shipped route. Your call; flagging it so it's a decision rather than an accident.
Heads-up, not your bug: remediation reads Role '?'
build_remediation() has no entries for the four new rule_types, so it falls through to the generic template — and since combo findings carry subject/bindings rather than role, the output is:
"action": "Review and narrow Role '?' to least privilege.",
"audit_note": "Record the narrowing of Role '?' in your access-review log."That's #88's job, not this PR's, and I'm not asking you to fix it here. Recording it because it means #88 has to land before these findings reach users — the remediation object is the whole differentiator, and Role '?' undercuts it. I'll note that on #88.
Fix the namespace issue and I'll merge this. The rest can be follow-ups, and if you'd rather hand any of items 1–6 to someone else, say so and I'll file them separately.
Add four combination-escalation predicates to effective_access.py: - combo_role_escalation (create roles + escalate) - combo_bind_escalation (create rolebindings + bind) - impersonation_grant (impersonate on users/groups/SAs) - privileged_pod_creation (create pods + privileged SA in namespace) Fix namespace isolation false-positive: _build_privileged_namespaces now skips SA subjects with no namespace key instead of inserting None, which previously caused every pod-creating subject to match regardless of namespace. Adds regression test pinning the fix. Also: linear flatten (O(n) not O(n^2)), KeyError guard on role index. Closes kaaval#85 Signed-off-by: Maqbool Ahmed <[email protected]>
2691c71 to
9dd6f9e
Compare
Namespace isolation fix is in — skipping SA subjects with no namespace key in |
|
Verified and merging. I re-ran my own reproducer rather than reading the diff and trusting it. The namespace fix holds. Same graph as before — No The belt-and-braces I also see you picked up two of the non-blocking items without being asked:
Suite is green: 21 in Merging, and what happens to the roadmapAs said in the last review, this becomes the Effective Access Graph foundation. Actioning that now:
Your question — yes, take themYou asked whether to open the remaining items yourself or have me file them. I've filed them, so they're tracked and someone else can pick one up if you'd rather move on, but they're yours first if you want them — say the word on any and I'll assign it:
I'd take them in that order — #4 is the one with a real correctness cost, since a PCI tenant currently gets combo findings scored as generic internal. One I noticed on this pass and did not hold the merge for: Thanks for turning this around in under an hour, and for fixing more than the one thing I blocked on. |
|
Merged. Follow-ups are filed — @Maqbool61, first refusal on all of these is yours, comment on any and I'll assign it:
Roadmap bookkeeping is done: #84 closed as superseded by this PR, #86 / #87 / #88 re-pointed at One thing surfaced while writing those up that's worth flagging to you directly: #88 now blocks #87. Changelog credit is in #130. Nothing else needed from you here — thanks for the fast turnaround. |
…130) Signed-off-by: Vamshi Krishna Santhapuri <[email protected]>
…al#88) Add remediation.py entries for the four combination-escalation rule_types shipped in kaaval#105: - combo_role_escalation → CIS 5.1.8 + RBAC Good Practices - combo_bind_escalation → CIS 5.1.8 + RBAC Good Practices - impersonation_grant → CIS 5.1.8 - privileged_pod_creation → CIS 5.1.4 + RBAC Good Practices Add TestComboRemediationCoverage (3 tests) asserting no combo rule_type falls through to the generic Role '?' template. Closes kaaval#88 Signed-off-by: Maqbool Ahmed <[email protected]>
…output (#157) The fixture YAML is right, but three of its explanatory comments describe behaviour the scanner does not produce, which would send the next person working on #84 chasing a phantom: - combo-role-writer was documented as producing NO per-role finding; its ClusterRoleBinding raises segmentation_violation like every other ClusterRoleBinding over a namespaced ServiceAccount. - combo-escalate-gate was documented as privilege_escalation_verbs MEDIUM; the rule scores HIGH whenever the role is cluster-scoped, and MEDIUM only for a namespaced Role. - The verify block said combo_role_escalation arrives once #84 lands. evaluate_combo_findings() already reports it today (#105/#131/#145) — what #84 adds is surfacing it through the per-role scan path. Verified by running the scan and evaluate_combo_findings() against the fixture. Follow-up to #152 (@Maqbool61). Signed-off-by: Vamshi Krishna Santhapuri <[email protected]>
Issue #85 — Combination-Escalation Predicates
What the Issue Was Asking For
The Kaaval RBAC scanner already detected individual dangerous verbs like
escalate,bind, andimpersonate— but only when they appeared in a single role. The issue pointed out a blind spot: some of the most dangerous privilege-escalation paths in Kubernetes only exist as combinations of verbs that a subject holds across two separate roles.For example,
escalatealone is dangerous but limited.create rolesalone is harmless. But hold both at the same time — even via two different role bindings — and you can create a role with whatever permissions you want and immediately escalate into it, achieving full cluster takeover with no dependency on any existing role.The issue asked for four such combination predicates to be added to a new file
control-plane/app/effective_access.py, each returning a distinctrule_typeso the existing scoring engine picks them up with zero changes.The Four Attack Paths
1.
combo_role_escalation— Create Roles + EscalateHalf A:
createonrolesorclusterrolesHalf B:
escalateverb onclusterrolesTogether: the attacker creates a new role with any verbs they want — including
*on*— and then usesescalateto climb into it. The Kubernetes API server normally blocks you from granting yourself permissions you don't already hold, but theescalateverb is explicitly designed to bypass that check. This is a complete privilege escalation path with no dependency on any existing role content.2.
combo_bind_escalation— Create Bindings + BindHalf A:
createonrolebindingsorclusterrolebindingsHalf B:
bindverb onclusterrolesTogether: the attacker creates a new binding that points at any existing role — including
cluster-admin— and assigns it to themselves or any other identity. Thebindverb bypasses the normal restriction that you can only create bindings to roles you already hold. One API call and the attacker iscluster-admin.3.
impersonation_grant— Impersonate Users/Groups/ServiceAccountsTrigger:
impersonateverb onusers,groups,serviceaccounts, oruserextrasThis one fires on a single verb, but it's evaluated at the aggregate rule-set level for consistency with the other predicates. The
impersonateverb lets the holder send any API request as any other identity, completely bypassing all RBAC controls that target those identities. A subject that can impersonatesystem:mastersbypasses RBAC authorization entirely. The resource check (users,groups,serviceaccounts) ensuresimpersonateon non-identity resources (which the API server ignores anyway) doesn't produce false positives.4.
privileged_pod_creation— Create Pods + Privileged SA in NamespaceHalf A:
createonpodsHalf B: the subject's namespace contains a non-
defaultServiceAccount bound to a privileged roleTogether: the attacker spins up a pod that mounts the token of the privileged ServiceAccount (which any pod in the namespace can do by setting
serviceAccountName), then uses that token to act as the privileged identity. The attacker never needs to be directly bound to the powerful role. "Privileged" is defined as: wildcard permissions, secrets read, escalation verbs, or exec/attach access. ThedefaultServiceAccount is excluded because its presence in every namespace is noise, not signal.How We Solved It
New file:
control-plane/app/effective_access.pyThe core of the implementation. Rather than adding more logic to
rbac_service.py(which evaluates risks per individual role), we created a separate module that operates on the aggregated rule set of each subject — all rules flattened across every Role and ClusterRole that subject is bound to.The key design decision: the existing
rbac_service.pyevaluates one role at a time and flags individual verbs. That's correct and intentional —escalatein a single role is still dangerous. But to detect combination paths, you need to look at what a subject can do in total, not what any one role grants. Soeffective_access.pybuilds a per-subject aggregate and runs the four predicates against it.The entry point is:
It accepts the same
graphdict shape as the existingevaluate_rbac_findingsfunction and returns findings in the identical shape — same keys, same scoring, same remediation structure — so nothing downstream needs to change.Internal flow:
rolesandcluster_rolesin the graphcompute_contextual_score(same call asrbac_service.py)Modified file:
control-plane/app/routers/rbac.pyAdded two new endpoints so the predicates can be tested against any synthetic RBAC graph without needing a live Kubernetes cluster:
POST /rbac/combo-scan— accepts a full RBAC graph in the request body (same shape as the live scan), runs all four predicates, returns findings. Useful for testing specific scenarios or integrating into CI.GET /rbac/combo-scan/demo— built-in demo graph that deliberately triggers all four predicates. No request body needed. Good for a quick smoke test after deployment.New file:
control-plane/tests/test_effective_access.py19 pure-function tests against synthetic graph dicts. No database, no network, no live cluster needed.
The acceptance criteria from the issue required at least one positive and one negative test per predicate — meaning the predicate must fire when both halves are held across two separate roles, and must not fire when either half is held alone. Every predicate has both.
Test classes:
TestComboRoleEscalation— 4 tests (positive, negative×2, shape check)TestComboBindEscalation— 4 tests (positive, negative×2, clusterrolebindings variant)TestImpersonationGrant— 5 tests (positive×3 for users/groups/SAs, negative×2)TestPrivilegedPodCreation— 3 tests (positive, negative — no privileged SA, negative — only default SA)TestFindingShape— 3 tests (required scoring keys, sort order, empty graph)Modified file:
docs/rbac-rules.mdAdded a new Combination-escalation rules section with a table documenting all four
rule_typevalues, their triggers, base severities, and attack paths. Added explanatory notes for each predicate covering edge cases like whydefaultSA is excluded from the privileged-pod check, and whyimpersonaterequires a resource check.Test Results
App-level test via FastAPI TestClient (no live cluster or Postgres needed):
Files Changed