Service Account Impersonation & Delegation
Vì Sao Quantum Trọng
Trong large cloud-native deployments, service accounts thường cần delegate permissions đến other subjects (users, other SAs). Ví dụ:
- CI/CD system needs run kubectl commands as berbeda service accounts depending on environment
- Admin user needs debug pod issue nhưng không muốn run entire session as cluster-admin
- Multi-tenant control plane needs admin để trigger operation atas behalf tenants (with audit trail)
Kubernetes support delegation via impersonation — ability để run request as different user/group. Nhưng impersonation punya subtle security implications:
- Privilege escalation risk nếu design sai
- Audit complexity — track siapa really issued commands
- Delegation chains — transitive privilege boundaries
Memahami impersonation mechanics crucial để safe delegation patterns.
Impersonation Basics
The impersonate Verb
Để impersonate subject lain, user/SA phải have explicit permission:
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: impersonator
rules:
- apiGroups: [""]
resources: ["users", "groups", "serviceaccounts"]
verbs: ["impersonate"]Permission terdiri từ:
- Resource type:
users,groups,serviceaccounts,userextras - Verb:
impersonate
How Impersonation Works
- Request with impersonation headers:
kubectl get pods \
--as=system:serviceaccount:default:my-app \
--as-group=developersInternally, kubectl gửi HTTP request với headers:
Impersonate-User: system:serviceaccount:default:my-app
Impersonate-Group: developers- API server checks permission:
request.user (original requester) = alice
request.impersonate_user = system:serviceaccount:default:my-app
request.impersonate_groups = [developers]
Check: Does alice have {verb: impersonate, resource: serviceaccounts, name: *}?
YES → Allow impersonation, evaluate request AS impersonated subject
NO → Deny impersonation- Request evaluated as impersonated subject:
Original request identity: alice
Becomes: system:serviceaccount:default:my-app (trong group "developers")
Authorization: Is system:serviceaccount:default:my-app allowed get pods?
(Check RBAC bindings để SA, not để alice)- Audit logged with both identities:
{
"user": {
"username": "alice",
"uid": "...",
"groups": ["developers", "system:authenticated"]
},
"impersonatedUser": {
"username": "system:serviceaccount:default:my-app"
},
"verb": "get",
"objectRef": {"resource": "pods"}
}Both original user (alice) và impersonated subject recorded.
Privilege Escalation Prevention
Constraint 1: Cannot Impersonate More-Privileged Users
User không có thể impersonate subject với more privileges than themselves.
Example:
Alice punya permissions: pods: [get, list]
Alice tries:
kubectl create rolebinding alice-admin \
--clusterrole=cluster-admin \
--user=alice
# This fails: alice không punya escalate verb trên cluster-admin roleBahkan với impersonate:
kubectl --as=system:serviceaccount:kube-system:admin create clusterrole ...
# Fails: Alice không punya impersonate trên that SA (implicit check)Mechanism:
When user A tries to impersonate user B:
1. Does A have "impersonate" permission? → Check
2. Does A have ALL groups that B has?
for each group in B.groups:
if group NOT in A.groups:
DENY (prevent escalation via group membership)
3. Are all transitive privileges of B ≤ A's privileges?
(this is NOT explicitly checked; implicit via RBAC membership)Constraint 2: Transitive Privilege Boundary
Impersonation respects transitive privilege boundaries. User cannot use impersonation to indirectly escalate.
Scenario:
Alice punya permissions: [get pods]
ServiceAccount my-app di namespace default punya permissions: [get secrets, update deployments]
Alice tanya: Can I impersonate my-app?
Check 1: Does alice have impersonate verb on serviceaccounts?
(Assume: NO)
→ DENY immediately
Check 2: (If alice had impersonate permission)
Even if alice impersonate my-app, authorization check akan evaluate
sebagai my-app, not alice.
Jadi alice không có thể accidentally escalate via impersonate
(nhưng có thể intentionally use my-app's elevated privilege để accomplish tasks)Resource-Name Scoped Impersonation
Impersonate với Resource Names
Permissions có thể scoped đến specific subjects via resourceNames:
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
namespace: default
rules:
# Alice có thể impersonate CHỈ my-app SA
- apiGroups: [""]
resources: ["serviceaccounts"]
verbs: ["impersonate"]
resourceNames: ["my-app"] # Restrict to specific SAResult: Alice có thể impersonate my-app nhưng không other-app.
# Works
kubectl get pods --as=system:serviceaccount:default:my-app
# Fails: alice không punya impersonate permission để other-app
kubectl get pods --as=system:serviceaccount:default:other-appDelegation Chains: Complex Scenarios
Scenario 1: CI/CD Delegating to Service Accounts
CI/CD system runs under service account ci-runner. Nó needs trigger deployments via different SAs per environment:
# Global CI runner SA
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ServiceAccount
metadata:
namespace: ci-system
name: ci-runner
---
# Grant ci-runner ability to impersonate env-specific SAs
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: delegated-deployer
rules:
- apiGroups: [""]
resources: ["serviceaccounts"]
verbs: ["impersonate"]
resourceNames:
- system:serviceaccount:prod:deployer
- system:serviceaccount:staging:deployer
- apiGroups: [""]
resources: ["serviceaccounts"]
verbs: ["get"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: ci-delegated-deployer
roleRef:
kind: ClusterRole
name: delegated-deployer
subjects:
- kind: ServiceAccount
namespace: ci-system
name: ci-runnerCI/CD có thể run:
kubectl --as=system:serviceaccount:prod:deployer apply -f deployment.yamlAudit trail shows:
- Original requester:
ci-runner - Impersonated as:
system:serviceaccount:prod:deployer - Action:
applydeployment
Scenario 2: Multi-Tenant Control Plane
Platform administrator needs manage multiple tenants. Có thể impersonate per-tenant SAs:
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: tenant-admin-delegator
rules:
# Admin có thể impersonate any tenant SA
- apiGroups: [""]
resources: ["serviceaccounts"]
verbs: ["impersonate"]
resourceNames:
- system:serviceaccount:tenant-a:admin
- system:serviceaccount:tenant-b:admin
# ... for each tenant
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: platform-admin-delegator
roleRef:
kind: ClusterRole
name: tenant-admin-delegator
subjects:
- kind: User
name: platform-admin@example.comPlatform admin có thể manage tenant-a via:
kubectl --as=system:serviceaccount:tenant-a:admin create ...Với full audit trail linking platform-admin → tenant-a actions.
Audit Trail & Compliance
Impersonation Audit Records
Mỗi impersonation fully logged trong audit trail:
{
"level": "RequestResponse",
"auditID": "...",
"stage": "ResponseComplete",
"requestObject": {...},
"responseObject": {...},
"user": {
"username": "alice",
"uid": "...",
"groups": ["developers", "system:authenticated"]
},
"impersonatedUser": {
"username": "system:serviceaccount:default:my-app",
"groups": ["system:serviceaccounts", "system:serviceaccounts:default"]
},
"verb": "create",
"objectRef": {
"apiVersion": "v1",
"kind": "Pod",
"namespace": "default"
},
"sourceIPs": ["10.0.0.5"]
}Key audit fields:
user— original requesterimpersonatedUser— subject impersonation dijalankan as- Both identities present → makes delegation traceable
Compliance Implications
Audit trail fully traceable:
- Who (original user) initiated action
- As whom (impersonated subject) action executed
- What (verb, object, namespace) was done
- When (timestamp) occurred
- Source (IP, user agent) of request
Tất cả tersimpan atomically với single audit record. Không có "hidden" delegation.
Security Best Practices
Best Practice 1: Minimize Impersonation Scope
Instead từ:
# BAD: Too broad
rules:
- resources: ["serviceaccounts"]
verbs: ["impersonate"]Use resourceNames:
# GOOD: Explicit allowlist
rules:
- resources: ["serviceaccounts"]
verbs: ["impersonate"]
resourceNames: ["my-app", "other-app"]Smaller blast radius nếu credential compromised.
Best Practice 2: Separate Impersonation from Action
Create distinct roles:
# Role 1: Ability to deploy
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: deployer
namespace: prod
rules:
- resources: ["deployments"]
verbs: ["get", "list", "update", "patch"]
---
# Role 2: Ability to impersonate deployer
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: deployer-impersonator
rules:
- apiGroups: [""]
resources: ["serviceaccounts"]
verbs: ["impersonate"]
resourceNames: ["deployer"]Separation memudahkan audit và revocation.
Best Practice 3: Audit Impersonation Usage
Enable high-level audit logging để detect impersonation abuse:
# audit-policy.yaml
rules:
- level: RequestResponse
impersonatedUser: {} # Log any impersonation
omitStages:
- RequestReceivedRegular audit review để flag unusual impersonation patterns.
Best Practice 4: No Delegation of Delegation
Avoid nested delegation chains:
BAD:
User A → impersonate B → B impersonate C → C does actionChains become audit nightmare. Better:
User A → impersonate C (direct)Anti-Patterns
Anti-Pattern 1: Over-Trusting Impersonation
# RISKY: Grant impersonate on ALL SAs
rules:
- resources: ["serviceaccounts"]
verbs: ["impersonate"]
# No resourceNames = can impersonate ANY SANếu credential leaked, attacker có thể impersonate any SA trong cluster. Always use resourceNames.
Anti-Pattern 2: Impersonating cluster-admin
# DANGEROUS
- resources: ["users"]
verbs: ["impersonate"]
resourceNames: ["cluster-admin"]Nếu user có thể impersonate cluster-admin user, chúng effectively cluster-admin. Avoid.
Anti-Pattern 3: Implicit Trust of Impersonated Identity
# Don't assume impersonation cannot escalate
# Always verify impersonated subject has necessary permissionsEven nếu A impersonate B, authorization still check B's permissions. Nếu B không punya permission để action, impersonation DENIED.
Troubleshooting Impersonation
Issue 1: Impersonation Permission Denied
# Error: User "alice" cannot impersonate resource "serviceaccounts"
# in API group "" in the namespace "default"
# Check if alice has impersonate permission
kubectl auth can-i impersonate serviceaccounts --as=alice
# NO
# Grant permission
kubectl create rolebinding alice-impersonator \
--clusterrole=impersonator \
--user=aliceIssue 2: Impersonated Subject Not Found
# Error: Cannot impersonate user "nonexistent@example.com"
# Service account must exist (username expansion)
# Check if SA exists
kubectl get sa my-app -n default
# If SA doesn't exist, create or use existing SA nameSummary
Impersonation là powerful delegation mechanism với strong safeguards:
- Explicit permission —
impersonateverb required - Privilege escalation prevention — transitive boundaries enforced
- Audit trail — both original và impersonated user logged
- Resource scoping — resourceNames limit impersonation scope
Safe delegation requires:
- Explicit
impersonaterole with resourceNames - Separate roles per responsibility
- Audit monitoring
- Minimal delegation chains