امنیت Kubernetes: RBAC، ServiceAccount، Pod Security Admission، Policy Engine و Audit
"All parts of an API request must be allowed by some authorization mechanism in order to proceed. In other words: access is denied by default." — Kubernetes documentation, Authorization
خلاصه (Summary): هر تغییر در خوشه (Cluster) یک درخواست HTTPS به kube-apiserver است و از احراز هویت (Authentication) و مجوز (Authorization) میگذرد. درخواستهای create، update، patch و delete سپس به کنترل پذیرش (Admission control) میرسند تا پذیرفتنی بودن شیء بررسی شود و بعد ذخیره شوند. ممیزی (Audit) در کنار این مراحل انجام میشود. درخواست CONNECT برای زیرمنبع (Subresource) مانند pods/exec، pods/attach، pods/portforward و proxy هم از Admission میگذرد، اما شیئی ذخیره نمیکند. خواندن با get، list و watch اصلاً وارد Admission نمیشود: "reads bypass the admission control layer". این فصل تنظیم این دروازهها برای انسان، خط لوله (Pipeline) و Pod را توضیح میدهد. سیاست شبکه (NetworkPolicy) نیز مشخص میکند Pod تسخیرشده پس از اجرا به کجا دسترسی داشته باشد. تمرکز (Focus): مسیر درخواست؛ گواهی کلاینت (Client certificate)، OIDC و توکن ServiceAccount با عمر محدود، وابسته به شیء (Bound) و درجشده در Volume ترکیبی (Projected)، TokenRequest API و automountServiceAccountToken؛ کنترل دسترسی مبتنی بر نقش (RBAC) با Role، ClusterRole، RoleBinding، ClusterRoleBinding، فعلها (Verbs)، منابع (Resources)، pods/exec و pods/log، nonResourceURLs، resourceNames، ClusterRole تجمیعی (Aggregated ClusterRole) و نقشهای view، edit، admin و cluster-admin؛ بررسی با kubectl auth can-i و ایفای هویت دیگر (Impersonation) با --as؛ کمترین امتیاز (Least privilege) و افزایش امتیاز (Privilege escalation) از راه escalate، bind، ساخت Pod، nodes/proxy و system:masters؛ هویت بار کاری (Workload identity) در IRSA، EKS Pod Identity، GKE Workload Identity و Azure Workload Identity؛ برچسب (Label)، حالت، نسخه و استثنای PSA؛ Admission webhook و failurePolicy، ValidatingAdmissionPolicy و CEL، Kyverno و OPA Gatekeeper با سه قاعدهٔ غیر root، منع Tag با مقدار latest و الزام Limits؛ بررسی امضای تصویر (Image signature verification) با cosign و Kyverno؛ ثبت ممیزی (Audit logging)، سطحها، مرحلهها، Backend و هشدارها؛ NetworkPolicy، منع پیشفرض (Default deny)، ورودی (Ingress)، خروجی (Egress)، گزینشگر (Selector)، ipBlock، DNS و پشتیبانی CNI، سپس قواعد L7 در Cilium و Calico؛ دسترسی Secret، مقاومسازی API server و kubelet با CIS Kubernetes Benchmark و kube-bench؛ چندمستأجری (Multi-tenancy)، مرز Namespace، Namespace سلسلهمراتبی و vCluster؛ سرویس Go با client-go برای خواندن ConfigMap در Namespace خودش و Pod برنامهٔ Laravel بدون دسترسی API. هدف یادگیری (Learning goal): از روی هر Binding بگویید دقیقاً چه مجوزی میدهد؛ برای سرویس، تیم و CI بدون cluster-admin، ServiceAccount و Role و Binding طراحی کنید؛ PSA را با Label روی Namespace اعمال و Policy Engine را بدون قطعی مستقر کنید؛ سیاست Audit برای تشخیص exec و خواندن Secret بنویسید، بدون ثبت مقدار Secret؛ Namespace را با NetworkPolicy محدود کنید و بدانید چه زمانی CNI آن را نادیده میگیرد؛ و به سرویس Go فقط همان مجوز لازم را بدهید که هنگام شروع خودش آن را بررسی کند.
این فصل امنیت سمت API در گروه Kubernetes را پوشش میدهد. محدودیتهای Pod Security Standards، securityContext، قابلیتها (Capabilities)، seccomp، اسکن و امضای Image در امنیت کانتینر هستند؛ API server، etcd، kubeconfig و مدل شیء در معماری و راهاندازی Kubernetes؛ Pod، Deployment و کاوشگر سلامت (Probe) در بارهای کاری Kubernetes؛ انواع Secret، رمزنگاری در حالت سکون (At rest) و External Secrets در پیکربندی، Secret و ذخیرهسازی؛ خواندن Audit و Event در عیبیابی در مشاهدهپذیری و عیبیابی Kubernetes؛ RBAC خود Argo CD در GitOps؛ و Runner و اعتماد فدرهٔ OIDC آن در خط لولههای CI/CD توضیح داده شدهاند. نظریهٔ RBAC، ABAC و Zero trust را در مجوز: RBAC، ABAC و Zero Trust، خود OIDC را در OAuth 2.0، OIDC و SSO، mTLS بین سرویسها را در mTLS و امنیت سرویس، فرایند رخداد را در SDLC امن و پاسخ به رخداد، دیوارهٔ آتش Node و ابر را در دیوارهٔ آتش، iptables، nftables و Security Group، و بررسی توکن در Go را در احراز هویت در Go بخوانید.
نقشهٔ صفحه (Page map)
| دنبال چه هستید | کجا بروید |
|---|---|
| مرور فصل در سه جدول | همهچیز در یک دقیقه |
| دلیل چهار دروازهٔ API server | چرا وجود دارد |
| گذار از ABAC به RBAC، از PSP به PSA، از Secret token به Bound token و از Webhook به CEL | از کجا آمده |
| مسیر Authentication → Authorization → Admission control | مسیر درخواست |
| گواهی کلاینت، OIDC، تنظیم ساختیافته و درخواست ناشناس | احراز هویت |
| توکن ServiceAccount، Bound و Projected، TokenRequest API و automountServiceAccountToken | ServiceAccount |
| نقش Role، ClusterRole، RoleBinding و ClusterRoleBinding | اشیای RBAC |
فعلهای get list watch create update patch delete، منبع، زیرمنبع و nonResourceURLs | قاعدهها |
| نقشهای پیشفرض view edit admin cluster-admin و ClusterRole تجمیعی | نقشهای پیشفرض و تجمیعی |
بررسی kubectl auth can-i، ایفای هویت با --as و SelfSubjectAccessReview | بررسی دسترسی |
| کمترین امتیاز، escalate و bind و افزایش امتیاز از راه create pods | راههای افزایش امتیاز |
| هویت بار کاری در IRSA، EKS Pod Identity، GKE و Azure Workload Identity | هویت بار کاری |
| Label، حالتهای audit و warn، نسخه و استثناهای PSA | Pod Security Admission |
| Webhookهای Admission، ValidatingWebhookConfiguration، MutatingWebhookConfiguration و failurePolicy | Admission webhook |
| قواعد ValidatingAdmissionPolicy، CEL و MutatingAdmissionPolicy | ValidatingAdmissionPolicy |
| Kyverno با ClusterPolicy و ValidatingPolicy، و ConstraintTemplate در OPA Gatekeeper | موتورهای سیاست |
| بررسی امضای Image با cosign و verifyImages در Kyverno | فقط Image امضاشده |
| ثبت ممیزی، سطحهای None Metadata Request RequestResponse و Backendها | ثبت ممیزی |
| NetworkPolicy، Default deny، podSelector namespaceSelector ipBlock و خروجی DNS | NetworkPolicy |
| گسترش سیاست با Cilium، Calico، CiliumNetworkPolicy در L7 و toFQDNs | افزونههای سیاست CNI |
| RBAC برای Secret و لینک رمزنگاری در حالت سکون | دسترسی Secret |
| پرچمهای anonymous-auth و authorization-mode، احراز هویت kubelet، CIS و kube-bench | مقاومسازی |
| چندمستأجری، مرز Namespace، Namespace سلسلهمراتبی و vCluster | چندمستأجری |
| ترتیب ارزیابی، JWT توکن، ترتیب Admission، تنظیمها و خطاها | سازوکار |
| قطعهکدها | Go، Laravel |
| هشت مسئلهٔ کلاسیک و راهحل آنها | حل مسئلهها |
| انتخاب لایهٔ سیاست، ورود انسان، هویت workload، CNI و مدل مستأجر | انتخاب |
| از یک Namespace تا چندین Cluster | در معماری |
| فرمانها با خروجی مورد انتظار | آزمایشگاه |
| باورهای غلط، مرور، پرسش و اصطلاحها | بدفهمیها، برگهٔ تقلب، خودآزمایی، واژهنامه |
همهچیز در یک دقیقه (Everything in one minute)
چهار دروازهٔ یک درخواست در kube-apiserver، Kubernetes v1.37.
| دروازه | پرسش | محل تنظیم | شکست | ابزارهای معمول |
|---|---|---|---|---|
| احراز هویت (Authentication) | فراخواننده کیست؟ | --client-ca-file، --authentication-config برای JWT در OIDC، کلیدهای توکن ServiceAccount | 401 Unauthorized؛ یا در نبود Credential و با anonymous فعال، system:anonymous | Client certificate، Dex، Keycloak، Okta، Entra ID، EKS access entries |
| مجوز (Authorization) | این کاربر اجازهٔ این فعل روی این منبع را دارد؟ | --authorization-mode=Node,RBAC یا --authorization-config | 403 Forbidden | اشیای RBAC، kubectl auth can-i |
| کنترل پذیرش (Admission control) | شیء پذیرفتنی است و باید تغییر کند؟ برای create/update/patch/delete و CONNECT شامل exec، attach، portforward و proxy؛ خواندن get/list/watch عبور نمیکند | Plugin داخلی، Labelهای PSA، ValidatingAdmissionPolicy، Webhook | admission webhook ... denied the request، violates PodSecurity | PSA، CEL، Kyverno، OPA Gatekeeper |
| ذخیرهسازی (Persistence) | ذخیره شود | etcd، --encryption-provider-config | ندارد؛ شیء موجود است | KMS provider برای Secret |
| ممیزی (Audit)، کنار همهٔ مراحل | چه اتفاقی افتاد و کار چه کسی بود؟ | --audit-policy-file، Backend لاگ یا Webhook | بدون فایل سیاست، هیچ رخداد Audit ثبت نمیشود | Falco، SIEM، Audit ابر |
| شبکه، پس از اجرای Pod | Pod به کجا میتواند وصل شود؟ | NetworkPolicy با اجرای CNI | قطع اتصال (Connection) و Timeout | Calico، Cilium، CNI ابری |
RBAC در یک جدول.
| شیء | حوزه (Scope) | محتوا | به زبان ساده |
|---|---|---|---|
Role | یک Namespace | قاعدهها: apiGroups × resources × verbs | «خواندن ConfigMap در shop» |
ClusterRole | Cluster | قاعده، منابع سراسری، nonResourceURLs و aggregationRule اختیاری | مجموعهٔ مجوز قابل استفادهٔ مجدد، یا مجوز nodes، namespaces و /healthz |
RoleBinding | یک Namespace | roleRef به Role یا ClusterRole و Subjects | «این مجموعه را فقط داخل shop بده» |
ClusterRoleBinding | Cluster | roleRef به ClusterRole و Subjects | «این مجموعه را همهجا بده»؛ بهندرت درست است |
| طرف مجوز (Subject) | — | User، Group یا ServiceAccount | User و Group رشتههایی حاصل Authentication هستند؛ شیء User وجود ندارد |
| ClusterRole داخلی | — | view، edit، admin، cluster-admin | view نمیتواند Secret بخواند؛ edit میتواند و Pod را با هر ServiceAccount اجرا میکند |
لایههای سیاست در یک جدول.
| لایه (Layer) | تصمیم | محل اجرا | نحوهٔ شکست | کاربرد |
|---|---|---|---|---|
| Pod Security Admission | سنجش Pod با privileged / baseline / restricted | داخل kube-apiserver | خرابی فراخوانی شبکه ندارد | حداقل حفاظت هر Namespace |
| ValidatingAdmissionPolicy | عبارت CEL روی هر شیء | داخل kube-apiserver | خطای CEL → failurePolicy | قاعدهٔ سادهٔ سازمان بدون مؤلفهٔ اضافه |
| Kyverno | Validate، Mutate، Generate، بررسی Image و گزارش پسزمینه | Deployment مربوط به Webhook | قطعی Webhook → failurePolicy | امضا، Digest، مقدار پیشفرض و گزارش |
| OPA Gatekeeper | Constraint در Rego و Audit اشیای موجود | Deployment مربوط به Webhook | طبق مستندات، Ignore پیشفرض و پذیرش هنگام خرابی (Fail open) | تیمی که از قبل OPA و Rego دارد |
| NetworkPolicy | ارتباط Podها و Egress در L3/L4 | CNI روی هر Node | CNI ناسازگار بیصدا نادیده میگیرد | Default deny و اجازههای صریح |
| سیاست Audit | چه ثبت شود | kube-apiserver | Backend لاگ پیشفرض Blocking است | تشخیص و بررسی رخداد |
چرا وجود دارد (Why it exists)
API در Kubernetes صفحهٔ کنترل (Control plane) تمام اجراهای Cluster است. کسی که Pod میسازد، تصویر (Image)، ServiceAccount و Volume آن را انتخاب میکند؛ اگر چیزی مانع نشود، privileged: true و hostPath: / را هم انتخاب میکند. پس دسترسی نوشتن API، بدون محدودیت دروازهها، معادل root روی Node است. پیش از RBAC، خوشهها از ABAC استفاده میکردند: فایل سیاست JSON روی API server که تغییرش Restart میخواست؛ یا به هر صاحب گواهی اعتماد میکردند. پیش از Bound token، هر ServiceAccount یک Secret با توکن بدون انقضا داشت. کپی پشتیبان etcd یا kubectl get secret -o yaml اعتبارنامهٔ دائمی را افشا میکرد. پیش از PSA نیز PodSecurityPolicy، Authorization و Admission را چنان پیچیده درهم آمیخته بود که حذف شد.
جایگزینها عمداً چندلایهاند. Authentication هویت را تعیین میکند؛ RBAC فعل مجاز روی منبع را؛ Admission داخل شیء را میبیند، چون RBAC نمیتواند «Pod مجاز، اما Pod دارای privileged ممنوع» را بیان کند. Audit همه را ثبت میکند و NetworkPolicy شعاع آسیب (Blast radius) را محدود میکند؛ حتی وقتی برنامهٔ داخل یک Pod پذیرفتهشده تسخیر شده باشد.
| انتخاب سادهتر | انتخاب کاملتر | دستاورد | هزینه |
|---|---|---|---|
| kubeconfig مدیر مشترک برای همه | OIDC، Group و RoleBinding هر Namespace | Audit هر فرد و لغو دسترسی در IdP | نگهداری IdP و نظم گروهها |
cluster-admin برای CI | Role استقرار هر Namespace و TokenRequest کوتاه | توکن لورفته فقط چند دقیقه و در یک Namespace مؤثر است | نگهداری Role هر Namespace برنامه |
ServiceAccount با نام default همهجا | یک ServiceAccount برای هر workload و automount خاموش | Pod تسخیرشده دسترسی API ندارد | چند شیء بیشتر برای هر برنامه |
| کلید ابری ثابت در Secret | Workload identity در IRSA، GKE و Azure | اعتبارنامهٔ ابری بلندمدت در Cluster نیست | تنظیم اعتماد OIDC هر Cluster |
| بدون سیاست Admission | PSA restricted و یک Policy Engine | استقرار Pod دارای privileged و :latest ممنوع | تست سیاست و ادارهٔ Webhook |
| شبکهٔ تخت | NetworkPolicy با Default deny و Allow | RCE در Pod به DB یا Metadata API نمیرسد | هر وابستگی جدید قاعدهٔ Allow میخواهد |
| بدون Audit | Audit در سطح Metadata و هشدار exec و خواندن Secret | پاسخ به «چه کسی این کار را کرد؟» | حجم لاگ و ذخیرهسازی |
تصویر روزمرهٔ فصل: ساختمان اداری. Authentication کارتخوان ورودی است؛ فقط هویت را تشخیص میدهد، حتی پیمانکار با کارت موقت هم هویت دارد. Authorization فهرست مجاز هر اتاق و کمد است: کارت طبقهٔ مالی را باز میکند یا نمیکند. برچسب «منع» نداریم؛ فقط اتاقهایی که مجوزشان داده شده یا نشده است. Admission نگهبانی است که جعبهٔ همراهتان را باز میکند؛ اجازهٔ ورود به اتاق سرور الزاماً اجازهٔ بردن نردبان نیست. Audit دوربین ساختمان و NetworkPolicy درهای داخلی بین بخشهاست که روز سرقت کارت اهمیت پیدا میکنند. توکن ServiceAccount کارت ربات است. Bound token با خروج ربات بیاعتبار میشود و حتی اگر ربات بماند، پایان شیفت منقضی خواهد شد.
سه بدفهمی رایج، از همان اول
۱. «RBAC میتواند منع کند.» خیر: "Permissions are purely additive (there are no "deny" rules)." اگر هر Binding فعلی را مجاز کند، RBAC اجازه میدهد؛ برای توقف باید مجوز را بردارید. قواعدی مانند «Pod دارای privileged ممنوع» یا «بدون :latest» در Admission هستند. اشیای RBAC. ۲. «دسترسی فقطخواندنی امن است.» هر سه فعل get، list و watch روی Secret داده را برمیگردانند: "The get, list and watch verbs can all return the full details of a resource." همچنین create روی Pod امکان اجرای هر ServiceAccount و Mount هر Secret همان Namespace را میدهد. راههای افزایش امتیاز. ۳. «وجود NetworkPolicy یعنی ترافیک مسدود است.» فقط اگر افزونهٔ شبکه آن را اجرا کند: "Creating a NetworkPolicy resource without a controller that implements it will have no effect." NetworkPolicy.
از کجا آمده (Where it comes from)
| زمان | رویداد | منبع |
|---|---|---|
| v1.6 → v1.8 (Oct 2017) | RBAC در 1.6 بتا و در 1.8 عرضهٔ عمومی (GA) با rbac.authorization.k8s.io/v1 و edit، view، admin؛ ABAC بهشکل فایل باقی ماند | وبلاگ Kubernetes، "Using RBAC, Generally Available in Kubernetes v1.8" |
| v1.14 | نقشهای system:basic-user و system:discovery دیگر پیشفرض به system:unauthenticated داده نمیشوند | جدول نقشهای پیشفرض مرجع RBAC |
| v1.21 | منسوخ شدن PodSecurityPolicy | وبلاگ پایداری PSA |
| v1.22 | پایداری Bound ServiceAccount token volume؛ دریافت توکن کوتاه با TokenRequest بهجای Secret | مرجع مدیریت ServiceAccount |
| v1.24 | فعال شدن پیشفرض LegacyServiceAccountTokenNoAutoGeneration؛ توقف ساخت خودکار Secret توکن؛ GA و حذف Gate در v1.27 | مفهوم Service account |
| 25 Aug 2022، v1.25 | پایداری PSA و حذف PodSecurityPolicy | وبلاگ "Pod Security Admission Controller in Stable" |
| v1.29 | بیاعتبار شدن Secret توکن قدیمی خودکار پس از یک سال بیاستفاده ماندن، سپس پاکسازی | مرجع مدیریت ServiceAccount |
| v1.30 (Apr 2024) | GA شدن ValidatingAdmissionPolicy؛ سیاست CEL داخل API server | وبلاگ VAP GA و مرجع VAP |
| v1.33 | GA ساخت توکن ServiceAccount وابسته به Node | مرجع مدیریت ServiceAccount |
| v1.34 | پایداری تنظیم ساختیافتهٔ AuthenticationConfiguration از v1.29 و تنظیم Endpoint ناشناس از v1.31 | مرجع Authentication |
| v1.35 | افزودن kubectl --as-user-extra برای Extra field در Impersonation | مرجع User impersonation |
| v1.36 | پایداری MutatingAdmissionPolicy از v1.30؛ تغییر با CEL بدون Webhook | مرجع MutatingAdmissionPolicy |
| 2025 | آرشیو repo مربوط به Hierarchical Namespace Controller زیر kubernetes-retired | فراداده (Metadata) در GitHub |
| 2026 | Kubernetes 1.37 جاری است؛ 1.37.2 در 2026-10-13؛ مستند Kyverno 1.18، ClusterPolicy را بهنفع ValidatingPolicy و ImageValidatingPolicy منسوخ میداند؛ Gatekeeper v3.23 شامل OPA v1.17 است | kubernetes.io/releases، مستند Kyverno، صفحهٔ نسخههای OPA در Gatekeeper |
دو مسیر به وضعیت امروز رسیدهاند. API server منطق را از Webhook بیرونی به درون خود برده است: PSA جای PSP را گرفت، ValidatingAdmissionPolicy و MutatingAdmissionPolicy بخشی از کار سابق Webhook را انجام میدهند و تنظیم ساختیافتهٔ Authentication جای پرچمهای متعدد --oidc-* را با فایلی قابل بازخوانی گرفته است. مسیر اکوسیستم، یعنی OPA Gatekeeper، Kyverno، Cilium و Calico، قابلیتهای بیرون از هسته را میدهد: امضای Image، گزارش پسزمینه، کتابخانهٔ Mutation و قواعد L7 و آگاه از DNS. خود Kyverno هم به مدل هسته نزدیک میشود؛ سیاستهای جدیدش CEL هستند و شکل ValidatingAdmissionPolicy دارند.
فهرست مفاهیم (The concept catalogue)
هر بخش از زبان ساده و بدفهمی شروع میشود، سپس تعریف، توالی، سناریوی واقعی، رفتار محصولها و راهحل را میآورد.
مسیر درخواست: احراز هویت، مجوز و کنترل پذیرش حیاتی
به زبان ساده: kube-apiserver از هر درخواست میپرسد کیستی و اجازهٔ این کار را داری؟ برای create، update، patch و delete سپس پذیرفتنی بودن شیء را بررسی میکند؛ برای CONNECT روی pods/exec، pods/attach، pods/portforward و proxy میپرسد آیا اتصال (Connection) باز شود؟ CONNECT پذیرفتهشده چیزی ذخیره نمیکند. پاسخ منفی در هر مرحله درخواست را تمام میکند و چیزی به etcd نمیرسد. Admission هرگز خواندن را نمیبیند: "do not (and cannot) block requests to read (get, watch or list) objects, because reads bypass the admission control layer"؛ بنابراین حفاظت Secret در برابر get بر عهدهٔ RBAC است.
بدفهمی رایج: «RBAC خود شیء را بررسی میکند.» فقط ویژگیهای User، Group، Verb، API group، Resource، Subresource، Namespace و Name را میبیند، نه Pod spec را؛ پس Pod دارای privileged را از Pod بیخطر تشخیص نمیدهد. مرجع میگوید: "Access controls and policies that depend on specific fields of specific kinds of objects are handled by admission controllers," و "admission control happens after authorization has completed (and, therefore, only when the authorization decision was to allow the request)."
تعریف: افزونههای احراز هویت (Authentication) شامل Client certificate، Bearer token و Authenticating proxy، مقادیر "Username"، "UID"، "Groups" و "Extra fields" را به درخواست میدهند؛ موفقیت، گروه system:authenticated را اضافه میکند. ماژولهای مجوز (Authorization) بهترتیب بررسی میشوند: "If any authorizer approves or denies a request, that decision is immediately returned and no other authorizer is consulted. If all modules have no opinion on the request, then the request is denied," با HTTP ۴۰۳. کنترل پذیرش (Admission control) دو مرحله دارد: "proceeds in two phases. In the first phase, mutating admission controllers are run. In the second phase, validating admission controllers are run," و "If any of the controllers in either phase reject the request, the entire request is rejected immediately."
kubectl apply -f deployment.yaml as jane (OIDC), namespace shop
1 TLS; Authorization: Bearer <id_token> -> JWT authenticator: user oidc:jane@acme.example,
groups [oidc:shop-oncall, system:authenticated]
2 request attributes: verb=patch group=apps resource=deployments ns=shop name=orders-api
3 Node authorizer: no opinion (not a node) -> RBAC: RoleBinding shop-oncall-edit -> allow
4 mutating admission: ServiceAccount plugin, MutatingAdmissionPolicy, mutating webhooks (Kyverno)
5 schema validation of the merged object
6 validating admission: PodSecurity (warn/audit on the template), ValidatingAdmissionPolicy,
validating webhooks (Kyverno, Gatekeeper), ResourceQuota
7 write to etcd -> audit event at ResponseComplete -> controllers see the change via watchسناریوهای واقعی:
- Pipeline هنگام
patch deploymentsخطای403میگیرد؛ Authentication موفق بوده چون خطا نام کاربر را دارد، اما RBAC، Binding ندارد. - توسعهدهنده مجوز Deployment دارد ولی Pod ساخته نمیشود؛ PSA enforce، Pod ساختهشده توسط ReplicaSet را رد میکند، نه Deployment را.
- پس از ارتقای Policy Engine، هر
kubectlده ثانیه معطل میشود؛ Webhook باfailurePolicy: Failدر دسترس نیست و درخواست منتظر Timeout میماند. - برای بررسی اینکه چه کسی ساعت ۰۳:۱۲ در Pod پرداخت exec کرده، فقط Audit log پاسخ دارد.
| محصول | محل تنظیم دروازهها |
|---|---|
| kubeadm، k3s، مدیریت شخصی | پرچم و فایلهای kube-apiserver که در اختیار شماست: --authentication-config، --authorization-mode، --admission-control-config-file، --audit-policy-file |
| EKS | IAM با Access entry یا ConfigMap قدیمی aws-auth؛ Audit به CloudWatch با فعالکردن Control-plane logging |
| GKE | هویت و گروه Google، Cloud Audit Logs و Admission تحت مدیریت GKE |
| AKS | Microsoft Entra ID و Azure RBAC for Kubernetes بهعنوان Webhook authorizer اختیاری |
| Docker Desktop، kind | یک گواهی مدیر در kubeconfig؛ مناسب لپتاپ، نامناسب بهعنوان الگوی محیط عملیاتی |
راهحل: اول Status code را بخوانید: ۴۰۱ برای Authentication، ۴۰۳ برای Authorization و پیام نامبرندهٔ Webhook یا Policy برای Admission است. فقط همان دروازه را عیبیابی کنید.
احراز هویت: گواهی کلاینت، OIDC، توکن و درخواست ناشناس حیاتی
به زبان ساده: Kubernetes پایگاه دادهٔ User ندارد. احراز هویت (Authentication) یعنی ارائهٔ چیزی که API server به آن اعتماد دارد: گواهی امضاشده با CA خوشه یا توکن صادرکنندهٔ معتبر. نام داخل اعتبارنامه، Username دیدهشده توسط RBAC میشود.
بدفهمی رایج: «کاربر را از Kubernetes حذف میکنم.» مستندات میگوید: "Kubernetes does not have objects which represent normal user accounts. Normal users cannot be added to a cluster through an API call." گواهی کلاینت تا انقضا معتبر میماند؛ حذف RoleBinding تنها ابزار لغو دسترسی آن فرد است. مرجع RBAC هشدار میدهد کاربر جدید با نام کاربر حذفشده "can automatically inherit all the rights of the deleted user".
تعریف: در گواهی کلاینت (Client certificate) با --client-ca-file، "the common name of the subject is used as the user name for the request" و "Client certificates can also indicate a user's group memberships using the certificate's organization fields." در OIDC، id_token (نه access_token) بهعنوان Bearer token فرستاده میشود؛ هشدار مستند: "The id_token can't be revoked, it's like a certificate so it should be short-lived (only a few minutes)." فایل پایدار AuthenticationConfiguration از v1.34 با --authentication-config حداکثر ۶۴ JWT authenticator را با CEL در claimValidationRules، claimMappings و userValidationRules تنظیم میکند و با --oidc-* جمع نمیشود. دربارهٔ درخواست ناشناس (Anonymous request): "requests that are not rejected by other configured authentication methods are treated as anonymous requests, and given a username of system:anonymous and a group of system:unauthenticated"؛ این دسترسی "is enabled by default if an authorization mode other than AlwaysAllow is used". فایل تنظیم میتواند آن را به /livez، /readyz و /healthz محدود کند. فایل توکن ثابت با --token-auth-file وجود دارد، اما تغییرش Restart سرور میخواهد.
OIDC login for a developer (kubelogin-style credential plugin)
1 kubectl needs a token -> exec plugin opens the browser to https://sso.acme.example
2 IdP returns id_token: iss, aud=kubernetes-prod, email=jane@acme.example, groups=[shop-developers], exp=+15m
3 kubectl sends Authorization: Bearer <id_token>
4 API server: issuer + JWKS from discovery, aud matches, exp ok, claimValidationRules (CEL) ok
5 claimMappings: username "oidc:jane@acme.example", groups ["oidc:shop-developers"]
6 RBAC sees those strings; after 15 minutes the plugin refreshes the token silently# kube-apiserver --authentication-config=/etc/kubernetes/authentication-config.yaml
# Structured authentication configuration (stable since v1.34). Replaces the
# --oidc-* flags; cannot be combined with them, nor with --anonymous-auth.
# Self-managed clusters only (kubeadm, k3s); EKS, GKE and AKS configure
# identity through their own APIs (access entries, Google groups, Entra ID).
apiVersion: apiserver.config.k8s.io/v1
kind: AuthenticationConfiguration
# Anonymous requests are allowed only on the health endpoints that load
# balancers probe. Everything else returns 401 to an unauthenticated caller.
anonymous:
enabled: true
conditions:
- path: /livez
- path: /readyz
- path: /healthz
jwt:
- issuer:
url: https://sso.acme.example # the company's OIDC provider
audiences:
- kubernetes-prod # the client ID registered for this cluster
claimValidationRules:
- expression: 'claims.exp - claims.nbf <= 3600'
message: id_token lifetime must not exceed one hour
claimMappings:
username:
claim: email
prefix: "oidc:" # oidc:jane@acme.example can never collide with system:*
groups:
claim: groups
prefix: "oidc:" # RBAC binds Group oidc:shop-developers
userValidationRules:
- expression: "!user.username.startsWith('system:')"
message: 'username cannot use the reserved system: prefix'سناریوهای واقعی:
- پیمانکار میرود ولی گواهی مدیرش ۳۶۴ روز اعتبار دارد؛ باید CA را بچرخانید یا فهرست منع در Authorizer webhook داشته باشید. در OIDC فرد را در IdP غیرفعال میکنید و توکن طی چند دقیقه میمیرد.
- IdP اشتباه، Username برابر
system:adminمیدهد؛ پیشوندoidc:و قاعدهٔ CEL درuserValidationRulesمانع تداخل با هویت داخلی میشوند. - Load balancer برای Probe روی
/readyzاعتبارنامه نمیخواهد؛ فهرست anonymousconditionsباقی مسیرها را از دسترس ناشناس خارج میکند. kubectl auth whoamiبا SelfSubjectReview نام و گروهی را نشان میدهد که API server از kubeconfig شما استخراج کرده است.
| روش | عمر | لغو | کاربرد |
|---|---|---|---|
| گواهی X.509 کلاینت | تا notAfter | فقط با چرخش CA | مدیر اضطراری، هویت Node و مؤلفهها |
| OIDC id_token در Dex، Keycloak، Okta، Entra ID، Google | چند دقیقه | غیرفعالسازی در IdP | انسان |
| توکن ServiceAccount با TokenRequest | 10 دقیقه تا چند ساعت | حذف شیء وابسته: Pod، Secret، Node | Workload و CI |
| Cloud IAM در EKS access entries، GKE، AKS Entra ID | کوتاه، صادرشده توسط ابر | Cloud IAM | Cluster مدیریتشده |
| فایل توکن ثابت | همیشگی | ویرایش فایل و Restart سرور | هرگز در محیط عملیاتی |
راهحل: ورود انسان با OIDC و پیشوند Username و Group؛ گواهی فقط برای مؤلفهها و هویت اضطراری (Break-glass) حفاظتشده؛ ناشناس فقط برای Endpoint سلامت. نظریهٔ جریان OIDC در OAuth 2.0، OIDC و SSO است.
ServiceAccount و توکن آن: Bound، Projected، TokenRequest و automountServiceAccountToken حیاتی
به زبان ساده: ServiceAccount هویت برنامه داخل Cluster است. kubelet توکن امضاشده و کوتاهعمر را بهشکل فایل در Pod میگذارد؛ برنامه آن را به API server میفرستد و با system:serviceaccount:<namespace>:<name> شناخته میشود.
بدفهمی رایج: «برنامه API را صدا نمیزند، پس توکن مهم نیست.» اگر خاموش نکنید، هر Pod توکن ServiceAccount با نام default را در /var/run/secrets/kubernetes.io/serviceaccount/token میگیرد. مهاجم با اجرای کد در PHP آن فایل را میخواند و تمام مجوزهای دادهشده به آن ServiceAccount یا system:serviceaccounts یا system:authenticated را بهدست میآورد.
تعریف: هر Namespace یک ServiceAccount با نام default دارد که به Pod بدون spec.serviceAccountName داده میشود. "In v1.22 and later, Kubernetes gets a short-lived, automatically rotating token using the TokenRequest API and mounts the token as a projected volume." Volume تزریقشدهٔ kube-api-access-* سه منبع دارد: serviceAccountToken که "bound to the specific Pod and has the kube-apiserver as its audience" و عمر پیشفرضش یک ساعت است؛ ConfigMap با نام kube-root-ca.crt؛ و Namespace از Downward API. kubelet وقتی توکن "older than 80% of its total time-to-live (TTL), or if the token is older than 24 hours" باشد آن را تازه میکند. مقدار expirationSeconds، "must be at least 10 minutes (600 seconds)". توکن وابسته (Bound) به Pod، Secret یا Node گره خورده و API server وجود آن شیء را بررسی میکند؛ حذف Pod توکن را بیاعتبار میکند. automountServiceAccountToken: false روی ServiceAccount یا Pod تنظیم میشود و "the Pod spec takes precedence". Secret قدیمی با نوع kubernetes.io/service-account-token، "don't expire and don't rotate"؛ از v1.24 خودکار ساخته نمیشود و از v1.29 نوع خودکار بیاستفاده پس از یک سال بیاعتبار میشود.
Pod orders-api-7d9f starts with its own projected token (expirationSeconds: 600)
1 kubelet -> POST /api/v1/namespaces/shop/serviceaccounts/orders-api/token
{audiences: [api server], expirationSeconds: 600, boundObjectRef: Pod orders-api-7d9f}
2 API server signs a JWT: sub=system:serviceaccount:shop:orders-api, kubernetes.io.pod.uid=...
3 kubelet writes it to the projected volume; app's rest.Config reads the file
4 t=480 s (80 % of 600): kubelet requests a new token, swaps the file atomically
5 Pod deleted -> any copy of the token is rejected: bound object no longer existsسناریوهای واقعی:
- CI برای پانزده دقیقه توکن میخواهد؛
kubectl create token shop-deployer --duration=15mجای Secret بلندمدت را میگیرد. - روش Kubernetes auth در Vault توکن با مخاطب (Audience) برابر
vaultمیخواهد؛ یک منبع Projected ازserviceAccountTokenباaudience: vaultاضافه کنید. - Cluster قدیمی هنوز Secretهای
*-token-*پیش از 1.24 را دارد؛ هرکدام اعتبارنامهٔ بدون انقضاست. - برنامه توکن ابتدای اجرا را Cache کرده و پس از یک ساعت خطا میدهد؛ client-go،
BearerTokenFileرا دوباره میخواند: "If set, the contents are periodically read".
| Workload | ServiceAccount | توکن |
|---|---|---|
| Laravel web، queue، scheduler | shop-web بدون Binding | automountServiceAccountToken: false |
| Go orders-api برای List کردن ConfigMap | orders-api و یک Role | Projected، 600 ثانیه، Audience سرور API |
| Operator / Controller | SA اختصاصی؛ ClusterRole برای Watch سراسری | Projected پیشفرض |
| CI deployer | shop-deployer و Role | kubectl create token --duration=15m یا OIDC ابری |
| ارتباط با Vault یا ابر | SA اختصاصی | توکن Projected اضافه با همان Audience |
#!/bin/sh
# TokenRequest API from the command line (expected, not run: no cluster here).
# A short-lived, audience-bound token for a CI job, instead of a Secret of
# type kubernetes.io/service-account-token that never expires.
set -eu
NS=shop
SA=shop-deployer
# 1. Ask the API server for a 15-minute token for the deployer ServiceAccount.
# Requires "create" on serviceaccounts/token in namespace shop.
# Kept in a shell variable, never written to disk.
TOKEN="$(kubectl create token "$SA" -n "$NS" --duration=15m)"
# 2. Who does the API server think we are with that token?
kubectl --token="$TOKEN" auth whoami
# expected shape:
# ATTRIBUTE VALUE
# Username system:serviceaccount:shop:shop-deployer
# UID <uid>
# Groups [system:serviceaccounts system:serviceaccounts:shop system:authenticated]
# 3. A token for another audience and bound to a Pod: it dies with the Pod.
kubectl create token orders-api -n "$NS" --audience=vault \
--bound-object-kind=Pod --bound-object-name="$(kubectl get pod -n "$NS" \
-l app.kubernetes.io/name=orders-api -o jsonpath='{.items[0].metadata.name}')"
# 4. Find legacy, never-expiring token Secrets that should be deleted.
kubectl get secrets -A --field-selector type=kubernetes.io/service-account-tokenراهحل: برای هر workload یک ServiceAccount، automount خاموش بهصورت پیشفرض، Projected token صریح برای نیاز API و حذف Secret توکن قدیمی. دقت کنید پیشفرض --service-account-extend-token-expiration=true توکن تزریقشده توسط Admission را برای کلاینت قدیمی "up to 1 year" تمدید میکند؛ بایتبهبایت توکن.
اشیای RBAC: Role، ClusterRole، RoleBinding و ClusterRoleBinding حیاتی
به زبان ساده: Role فهرست مجوزهاست؛ Binding آن را به کسی میدهد. Role و RoleBinding در Namespace هستند؛ ClusterRole و ClusterRoleBinding سراسریاند. RoleBinding میتواند به ClusterRole اشاره کند تا تعریف مشترک را فقط در همان Namespace اعطا کند.
بدفهمی رایج: «ClusterRole دسترسی سراسری میدهد.» فقط ClusterRoleBinding چنین میکند. RoleBinding shop/oncall-edit → ClusterRole edit فقط edit در shop میدهد. اشتباه معکوس هم رایج است: ClusterRoleBinding به view اجازهٔ خواندن همهٔ Namespaceها، حتی فراموششدهها، را میدهد.
تعریف: RBAC با --authorization-mode=...,RBAC فعال میشود: "Permissions are purely additive (there are no "deny" rules)." هر Binding شامل subjects از User، Group و ServiceAccount و یک roleRef است. "If you try to change a binding's roleRef, you get a validation error"؛ دلیل: "Making roleRef immutable allows granting someone update permission on an existing binding object, so that they can manage the list of subjects, without being able to change the role that is granted to those subjects." ServiceAccount کاربری با نام system:serviceaccount:<ns>:<name> در گروههای system:serviceaccounts و system:serviceaccounts:<ns> است.
May system:serviceaccount:shop:orders-api "list configmaps" in namespace payments?
1 ClusterRoleBindings: none name this subject or its groups -> continue
2 RoleBindings in payments (only that namespace counts): none match -> continue
3 RoleBinding shop/orders-api-config-reader matches the subject, but it is in shop -> ignored
4 no rule allowed -> RBAC has no opinion -> no other authorizer allows -> 403 Forbiddenسناریوهای واقعی:
- اعطای
adminبه تیم در Namespace خودش با یک RoleBinding به ClusterRole داخلی. - Operator که CRD خود را همهجا Watch میکند: ClusterRole و ClusterRoleBinding محدود به API group خودش.
- تغییر نقش اعطاشده: Binding را حذف و دوباره ایجاد کنید؛
kubectl auth reconcileاین کار را انجام میدهد. - Application controller در Argo CD اغلب دسترسی سراسری دارد؛ برای چندمستأجری، Role استقرار در هر Namespace جایگزین است.
| نیاز | جفت اشیا |
|---|---|
| تعریف و اعطای مجوز در یک Namespace | Role + RoleBinding |
| مجموعهٔ مشترک در چند Namespace | ClusterRole + یک RoleBinding در هر Namespace |
| منابع سراسری مثل Node، Namespace، CRD، PV یا همهٔ Namespaceها | ClusterRole + ClusterRoleBinding |
/healthz، /metrics و سایر nonResourceURLs | ClusterRole + ClusterRoleBinding |
| مدیریت Subjects بدون تغییر Role | update روی Binding؛ roleRef تغییرناپذیر است |
# AFTER, workload side: the Go service orders-api reads its feature-flag
# ConfigMaps from its own namespace and nothing else.
# - its own ServiceAccount (never "default")
# - a namespaced Role (not a ClusterRole) with read verbs on one resource
# - a RoleBinding in the same namespace
# Check it offline with go/rbaccheck, or online with:
# kubectl auth can-i list configmaps -n shop --as=system:serviceaccount:shop:orders-api
apiVersion: v1
kind: ServiceAccount
metadata:
name: orders-api
namespace: shop
labels:
app.kubernetes.io/name: orders-api
# The token is mounted explicitly by the Pod spec (see
# serviceaccount/orders-api-deployment.yaml); the ServiceAccount default is off.
automountServiceAccountToken: false
---
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: orders-api-config-reader
namespace: shop
rules:
- apiGroups: [""] # "" is the core API group
resources: ["configmaps"]
verbs: ["get", "list", "watch"] # watch so an informer can follow changes
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: orders-api-config-reader
namespace: shop
roleRef: # immutable: delete and recreate to change it
apiGroup: rbac.authorization.k8s.io
kind: Role
name: orders-api-config-reader
subjects:
- kind: ServiceAccount
name: orders-api
namespace: shopراهحل: انتخاب پیشفرض Role/ClusterRole همراه RoleBinding است؛ هر ClusterRoleBinding نیازمند بازبینی است. مدل عمومی نقش و مجوز در مجوز: RBAC، ABAC و Zero Trust آمده است.
قاعدهها: Verbs، Resources، Subresources، resourceNames و nonResourceURLs حیاتی
به زبان ساده: قاعده یعنی «این فعلها روی این منابع در این API groupها» و در صورت نیاز «فقط این نامها». فعل از HTTP method میآید. زیرمنبع (Subresource) مثل pods/log، pods/exec و scale جداست و باید نامش را صریح بنویسید.
بدفهمی رایج: «resources: [pods] شامل log و exec هم هست.» خیر؛ درخواست pods/log یا pods/exec با همان نام بررسی میشود. مثال Audit هم میگوید: "Resource "pods" doesn't match requests to any subresource of pods, which is consistent with the RBAC policy."
تعریف: POST به create، GET/HEAD به get یا برای مجموعهها list با "including full object content" یا watch، PUT به update، PATCH به patch و DELETE به delete یا deletecollection نگاشت میشود. فعلهای get list watch create update patch delete و deletecollection منابع را پوشش میدهند؛ فعلهای ویژه impersonate، bind، escalate و approve هستند. برای درخواست غیرمنبعی، HTTP method با حروف کوچک است. apiGroups: [""] گروه هسته است. زیرمنبع را مانند pods/log مینویسید؛ */scale زیرمنبع scale هر منبع را میگیرد. resourceNames نام شیء را محدود میکند، اما "You cannot restrict deletecollection or top-level create requests by resource name." در nonResourceURLs، "you can use the wildcard * as a suffix glob match"؛ مسیرهایی مانند /healthz فقط در ClusterRole معنا دارند.
kubectl logs orders-api-7d9f -n shop -> GET /api/v1/namespaces/shop/pods/orders-api-7d9f/log
attributes: verb=get group="" resource=pods subresource=log name=orders-api-7d9f ns=shop
rule {apiGroups:[""], resources:["pods"], verbs:["get"]} -> no match ("pods" != "pods/log")
rule {apiGroups:[""], resources:["pods","pods/log"], verbs:["get"]} -> match -> allowed
kubectl exec ... -> POST .../pods/orders-api-7d9f/exec -> verb=create resource=pods/exec -> needs its own ruleسناریوهای واقعی:
- نقش خواندن لاگ برای توسعهدهنده:
podsوpods/logباget،listوwatch، بدونpods/exec. - Controller فقط Lease انتخاب رهبر خودش را تغییر میدهد:
resourceNames: [orders-api-leader]رویleases. - ابزار شبیه HorizontalPodAutoscaler فقط
updateرویdeployments/scaleدارد، بدون مجوز رویdeployments. - عامل Monitoring از
/metricsسرور API میخواند:nonResourceURLs: ["/metrics"]وverbs: ["get"].
| فرمان kubectl | فعل | منبع / زیرمنبع |
|---|---|---|
kubectl get pods | list | pods |
kubectl get pod x -w | watch | pods |
kubectl logs x | get | pods/log |
kubectl exec x -- sh | create | pods/exec |
kubectl port-forward x 8080 | create | pods/portforward |
kubectl scale deploy x --replicas=3 | patch | deployments/scale |
kubectl create token sa | create | serviceaccounts/token |
kubectl debug x برای کانتینر موقت | patch | pods/ephemeralcontainers |
راهحل: قاعده را از فرمان واقعی کاربران استخراج کنید. در verbs، resources و apiGroups هرگز * نگذارید: "providing wildcard access gives rights not just to all object types that currently exist in the cluster, but also to all object types which are created in the future".
ClusterRoleهای پیشفرض view، edit، admin، cluster-admin و نقش تجمیعی مهم
به زبان ساده: هر Cluster چهار نقش کاربرمحور دارد: view، edit، admin و ابرکاربر cluster-admin که میتوان آنها را در Namespace اعطا کرد. تجمیع (Aggregation) اجازه میدهد مجوز CRD خودکار به این نقشها افزوده شود.
بدفهمی رایج: «edit نقش امن توسعهدهنده است.» مرجع دربارهٔ edit میگوید: "allows accessing Secrets and running Pods as any ServiceAccount in the namespace, so it can be used to gain the API access levels of any ServiceAccount in the namespace." نقش view عمداً Secret را حذف کرده: "since reading the contents of Secrets enables access to ServiceAccount credentials".
تعریف: cluster-admin پیشفرض به گروه system:masters داده شده و "Allows super-user access to perform any action on any resource"؛ در RoleBinding، "full control over every resource in the role binding's namespace, including the namespace itself" میدهد. admin، "intended to be granted within a namespace using a RoleBinding" و شامل ایجاد Role و RoleBinding است؛ ولی "write access to resource quota or to the namespace itself" ندارد. ClusterRole تجمیعی (Aggregated ClusterRole)، aggregationRule با Label selector دارد؛ Controller manager، rules آن را با قواعد ClusterRoleهای دارای آن Label پر میکند. نقشهای داخلی از rbac.authorization.k8s.io/aggregate-to-view، -edit و -admin استفاده میکنند. هنگام شروع API server نقشهای پیشفرض خودکار هماهنگ میشوند، مگر Annotation برابر rbac.authorization.kubernetes.io/autoupdate: "false" باشد.
A CRD refundrequests.shop.acme.io is installed
1 without aggregation: users with "view" in shop cannot list refundrequests
2 apply ClusterRole shop-orders-crd-view labelled aggregate-to-view/edit/admin = "true"
3 controller manager recomputes view, edit, admin: rules += refundrequests get list watch
4 every existing RoleBinding to view/edit/admin now covers the CRD; no binding changedسناریوهای واقعی:
- Operator نصبشده با Helm معمولاً ClusterRole با
aggregate-to-*دارد تا مدیر Namespace منابع سفارشی را مدیریت کند. - نقش
acme-auditorاز قطعههای Labelدار تحت مالکیت تیمهای مختلف ساخته میشود. - تغییر دستی
editپس از Restart سرور ناپدید میشود؛ نتیجهٔ Auto-reconciliation است. - Chart فروشنده برای Controller یک ClusterRoleBinding به
cluster-adminمیسازد؛ پیش از نصب بازبینی کنید.
| نقش | Secret | اشیای RBAC | شیء Namespace | Binding معمول |
|---|---|---|---|---|
view | خیر | خیر | خیر | RoleBinding برای توسعهدهنده |
edit | خواندن/نوشتن | خیر | خیر | RoleBinding برای مسئول شیفت |
admin | خواندن/نوشتن | Role و RoleBinding در Namespace | بدون نوشتن | RoleBinding برای سرپرست تیم |
cluster-admin | همه | همه | همه | ClusterRoleBinding فقط برای Break-glass |
# AFTER, people and pipelines. Groups come from the OIDC id_token
# (claimMappings.groups in apiserver/authentication-config.yaml, prefix "oidc:").
# Humans are bound to the built-in user-facing ClusterRoles inside one
# namespace with a RoleBinding; nobody but break-glass gets cluster-admin.
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: shop-developers-view
namespace: shop
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: view # no Secrets, no Roles/RoleBindings
subjects:
- kind: Group
name: oidc:shop-developers
apiGroup: rbac.authorization.k8s.io
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: shop-oncall-edit
namespace: shop
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: edit # can read Secrets and run Pods as any SA here
subjects:
- kind: Group
name: oidc:shop-oncall
apiGroup: rbac.authorization.k8s.io
---
# Read logs without exec: pods/log is a subresource and must be named.
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: shop-log-reader
namespace: shop
rules:
- apiGroups: [""]
resources: ["pods", "pods/log"]
verbs: ["get", "list", "watch"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: shop-developers-logs
namespace: shop
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: Role
name: shop-log-reader
subjects:
- kind: Group
name: oidc:shop-developers
apiGroup: rbac.authorization.k8s.io
---
# The deployer used by CI (GitHub Actions / GitLab CI) or by Argo CD for this
# namespace: it applies the kinds the app ships and nothing else. It cannot
# touch RBAC, Secrets, the Namespace object (PSA labels) or webhooks.
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: shop-deployer
namespace: shop
rules:
- apiGroups: ["apps"]
resources: ["deployments", "statefulsets"]
verbs: ["get", "list", "watch", "create", "update", "patch"]
- apiGroups: ["batch"]
resources: ["jobs", "cronjobs"]
verbs: ["get", "list", "watch", "create", "update", "patch", "delete"]
- apiGroups: [""]
resources: ["services", "configmaps"]
verbs: ["get", "list", "watch", "create", "update", "patch"]
- apiGroups: ["networking.k8s.io"]
resources: ["ingresses", "networkpolicies"]
verbs: ["get", "list", "watch", "create", "update", "patch"]
- apiGroups: ["policy"]
resources: ["poddisruptionbudgets"]
verbs: ["get", "list", "watch", "create", "update", "patch"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: shop-deployer
namespace: shop
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: Role
name: shop-deployer
subjects:
- kind: ServiceAccount
name: shop-deployer
namespace: shop
---
apiVersion: v1
kind: ServiceAccount
metadata:
name: shop-deployer
namespace: shop
automountServiceAccountToken: false # CI gets a short TokenRequest token instead
---
# Aggregation: a CRD's permissions join the built-in roles by label.
# The controller manager unions these rules into view/edit/admin.
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: shop-orders-crd-view
labels:
rbac.authorization.k8s.io/aggregate-to-view: "true"
rbac.authorization.k8s.io/aggregate-to-edit: "true"
rbac.authorization.k8s.io/aggregate-to-admin: "true"
rules:
- apiGroups: ["shop.acme.io"]
resources: ["refundrequests"]
verbs: ["get", "list", "watch"]
---
# A custom aggregated ClusterRole of our own: anything labelled
# acme.io/aggregate-to-auditor joins it.
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: acme-auditor
aggregationRule:
clusterRoleSelectors:
- matchLabels:
acme.io/aggregate-to-auditor: "true"
# No rules field: the controller manager owns it and overwrites manual rules;
# even "rules: []" claims the field under server-side apply and causes conflicts.
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: acme-auditor-rbac-read
labels:
acme.io/aggregate-to-auditor: "true"
rules:
- apiGroups: ["rbac.authorization.k8s.io"]
resources: ["roles", "rolebindings", "clusterroles", "clusterrolebindings"]
verbs: ["get", "list", "watch"]
- nonResourceURLs: ["/healthz", "/livez", "/readyz", "/version"]
verbs: ["get"]راهحل: بیشتر افراد view، مسئول شیفت edit، مالک Namespace نقش admin و فقط دسترسی اضطراری cluster-admin بگیرد. نقش داخلی را با Label تجمیع گسترش دهید، نه ویرایش مستقیم.
بررسی دسترسی: kubectl auth can-i، ایفای هویت با --as و SelfSubjectAccessReview حیاتی
به زبان ساده: بدون انجام عمل از API server بپرسید چه تصمیمی میگیرد. kubectl auth can-i برای خودتان است؛ مدیر با --as از طرف دیگری میپرسد.
بدفهمی رایج: «can-i، RoleBindingهایم را میخواند.» کل زنجیرهٔ Authorization را میپرسد: "uses the SelfSubjectAccessReview API to determine if the current user can perform a given action, and works regardless of the authorization mode used". پس yes ممکن است از Webhook authorizer یا Node authorizer بیاید، نه فقط RBAC.
تعریف: kubectl auth can-i <verb> <resource> [-n ns]، yes یا no چاپ میکند؛ --list قواعد Namespace را نشان میدهد. ایفای هویت دیگر (Impersonation)، "is a method of allowing authenticated users to act as another user, group, or service account through HTTP headers": هدرهای Impersonate-User، Impersonate-Group، Impersonate-Uid و Impersonate-Extra-* با --as، --as-group، --as-uid از 1.23 و --as-user-extra از 1.35 تنظیم میشوند. "Impersonation requests first authenticate as the requesting user, then switch to the impersonated user info"؛ فراخواننده فعل impersonate روی users، groups، serviceaccounts یا uids میخواهد. SubjectAccessReview برای هر کاربر و LocalSubjectAccessReview برای یک Namespace، APIهای ابزار و Webhook هستند.
$ kubectl auth can-i list configmaps -n shop --as=system:serviceaccount:shop:orders-api
1 kubectl authenticates as the admin, adds Impersonate-User: system:serviceaccount:shop:orders-api
2 API server checks: admin may "impersonate" serviceaccounts? yes
3 creates a SelfSubjectAccessReview as the impersonated SA: verb=list resource=configmaps ns=shop
4 authorizers evaluate -> status.allowed=true, reason "RBAC: allowed by RoleBinding ..."
5 kubectl prints: yesسناریوهای واقعی:
- پیش از ادغام تغییر RoleBinding:
kubectl auth can-i --list -n shop --as=oidc:jane@acme.example --as-group=oidc:shop-developers. - سرویس Go هنگام شروع با SelfSubjectAccessReview مجوز خود را بررسی و در نبودش فوری با پیام روشن متوقف میشود؛ Go.
- در جریان Break-glass، مسئول شیفت فقط
impersonateروی یک Group ممتاز دارد؛ پس هر عمل ممتاز با هویت جایگزین در Audit مشخص است. kubectl drain mynode --as=superman --as-group=system:mastersمثال خود مستند برای خطر فعلimpersonateاست.
| ابزار | پرسش یا کار |
|---|---|
kubectl auth can-i / --list | من یا هویت X با --as اجازه دارم؟ |
kubectl auth whoami | سرور مرا چه کسی میشناسد؟ |
kubectl auth reconcile -f | اعمال RBAC و ساخت دوبارهٔ Binding با roleRef تغییرکرده |
rakkess و kubectl-who-can، افزونههای krew | چه کسی X را میتواند؟ نمایش ماتریس دسترسی |
rbaccheck در قطعهکدهای فصل | همان تطبیق RBAC بهصورت آفلاین روی YAML در Git |
راهحل: هر تغییر RBAC همراه تست مثبت و منفی can-i باشد؛ در CI آفلاین روی YAML و پس از Apply روی Cluster.
کمترین امتیاز و افزایش امتیاز: escalate، bind، impersonate، create pods و nodes/proxy حیاتی
به زبان ساده: بعضی مجوزها از ظاهرشان قویترند، چون مجوزهای دیگر را بهدست میدهند. کمترین امتیاز (Least privilege) یعنی اینها را بشناسید و تقریباً هرگز اعطا نکنید.
بدفهمی رایج: «سازندهٔ Role میتواند هر مجوزی به خودش بدهد.» خیر: "The RBAC API prevents users from escalating privileges by editing roles or role bindings." برای ساخت Role باید "You already have all the permissions contained in the role" یا فعل escalate را داشته باشید؛ برای Binding نیز باید مجوزهای Role یا فعل bind روی آن را داشته باشید. کلید افزایش امتیاز این دو فعلاند، نه صرفاً create roles.
تعریف: مرجع RBAC خطرهای افزایش امتیاز (Privilege escalation) را فهرست میکند. ساخت Workload: "Permission to create workloads (either Pods, or workload resources that manage Pods) in a namespace implicitly grants access to many other resources in that namespace, such as Secrets, ConfigMaps, and PersistentVolumes" و "since Pods can run as any ServiceAccount, granting permission to create workloads also implicitly grants the API access levels of any service account in that namespace"؛ Pod دارای privileged به Node میرسد. دربارهٔ nodes/proxy: "This access bypasses audit logging and admission control" و "get permission on nodes/proxy is not a read-only permission". escalate و bind کنترل داخلی را دور میزنند؛ impersonate هویت را عوض میکند. تأیید CSR گواهی با "arbitrary names including duplicates of Kubernetes system components" میسازد. create روی serviceaccounts/token توکن SA موجود را میدهد. Webhook configuration تمام اشیای ورودی را میخواند و تغییر میدهد. Patch روی Namespace برچسب PSA را تغییر میدهد. عضویت system:masters، "bypasses all RBAC rights checks ... which cannot be revoked by removing RoleBindings".
"Developers only get create on deployments in shop" (no Secrets access) -> read the payment key anyway
1 kubectl create deploy peek --image=busybox -- sleep 3600, then patch it:
serviceAccountName: payments-worker, volume secret: stripe-key
2 ReplicaSet creates the Pod; kubelet mounts stripe-key (kubelet reads it, not the developer)
3 kubectl logs is denied? the container can still POST the key anywhere egress allows
-> separate namespaces per trust level, PSA restricted, default-deny egress, audit on Pod creationسناریوهای واقعی:
- Binding به
cluster-adminبرای SA مربوط به CI، از رایجترین یافتههای بازبینی؛ before-overgrant.yaml. - ClusterRole پشتیبانی «فقطخواندنی» با
*برای منابع وlist؛ تمام Secretها را میخواند. - ابزار عضوسازی تیم با
bindرویclusterrolesبدونresourceNamesمیتواندcluster-adminبدهد. - سوءاستفاده از عامل Metrics با
get nodes/proxyبرای exec در هر Pod همهٔ Nodeها.
| مجوز | دسترسی ضمنی | جایگزین محدودتر |
|---|---|---|
create pods / deployments / jobs | هر ServiceAccount، Secret و ConfigMap در Namespace | استقرار GitOps با Deployer همان Namespace؛ PSA restricted |
list/watch secrets | تمام مقدارهای Secret | get با resourceNames یا هیچ دسترسی Secret |
create pods/exec | هرچه کانتینر میخواند | pods/log و Debug موقت در Namespace جدا |
escalate / bind | هر مجوز | bind با resourceNames: [view, edit] |
impersonate | هر هویت | فقط یک Group نامبرده |
get nodes/proxy | Exec در هر Pod روی Node، بدون Audit | خواندن از Metrics API |
create serviceaccounts/token | توکن هر SA در حوزهٔ مجوز | فقط SA خود CI |
patch namespaces | تغییر Labelهای PSA و NetworkPolicy | فقط تیم Platform |
گروه system:masters | ابرکاربر با دسترسی لغونشدنی | هرگز در گواهی صادرشده، جز Break-glass |
Pod با hostPath به /run/containerd/containerd.sock | اجرای هر کانتینر مستقیماً با containerd روی Node؛ بدون RBAC، Admission و Audit | PSA baseline یا restricted که hostPath را منع میکند |
راهحل: RBAC در Git را با rbaccheck یا افزونهای مانند kubectl-who-can بررسی کنید، همهٔ ClusterRoleBindingها را بازبینی کنید و RBAC را با PSA و NetworkPolicy همراه کنید؛ RBAC بهتنهایی مسیر create pods را نمیبندد.
هویت بار کاری: IRSA، EKS Pod Identity، GKE Workload Identity و Azure Workload Identity مهم
به زبان ساده: بهجای کلید ابری در Secret، ابر را به توکن ServiceAccount خوشه اعتماد دهید. Pod توکن Projected را به سرویس هویت ابر میدهد و اعتبارنامهٔ موقت یک Role را میگیرد.
بدفهمی رایج: «IAM role خود Node کافی است.» تا وقتی مانعی نباشد، همهٔ Podهای Node اعتبارنامهٔ Instance metadata را میخوانند؛ در نتیجه Role آن Node مجموع نیاز همهٔ workloadهاست. هویت بار کاری (Workload identity) مجوز ابر را برای هر ServiceAccount جدا میکند. بستن Egress به آدرس Metadata به Platform وابسته است؛ خود GKE Workload Identity به آن نیاز دارد.
تعریف: توضیح AWS: "Amazon EKS hosts a public OIDC discovery endpoint for each cluster that contains the signing keys for the ProjectedServiceAccountToken JSON web tokens so external systems, such as IAM, can validate and accept the OIDC tokens". IRSA روی SA، Annotation با نام eks.amazonaws.com/role-arn میگذارد؛ Trust policy نقش، sts:AssumeRoleWithWebIdentity را برای Provider و Subject مجاز میکند. EKS Pod Identity، "is a simpler method than IAM roles for service accounts, as this method doesn't use OIDC identity providers"؛ ارتباط در EKS API تعریف میشود و عامل DaemonSet اعتبارنامه میدهد. GKE Workload Identity Federation به Principal مانند principal://iam.googleapis.com/projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/PROJECT_ID.svc.id.goog/subject/ns/NAMESPACE/sa/KSA_NAME نقش IAM میدهد یا SA در Kubernetes را با iam.gke.io/gcp-service-account به IAM service account مرتبط میکند؛ درخواست Metadata از Pod، "routed to the GKE metadata server" میشود. Azure Workload Identity از Federated identity credential روی Managed identity، Annotation با نام azure.workload.identity/client-id و Label روی Pod با azure.workload.identity/use: "true" استفاده میکند: "Only pods with this label are mutated by the azure-workload-identity mutating admission webhook".
orders-api reads s3://acme-invoices on EKS with IRSA
1 Pod's SA orders-api is annotated eks.amazonaws.com/role-arn=arn:aws:iam::111122223333:role/orders-api-s3-read
2 EKS webhook adds a projected token (audience sts.amazonaws.com) and the AWS SDK environment for it
3 AWS SDK calls sts:AssumeRoleWithWebIdentity with the token
4 STS fetches the cluster's OIDC JWKS, checks iss, aud, sub=system:serviceaccount:shop:orders-api
5 returns credentials for one role; the SDK refreshes them before expiry# Workload identity: the Pod's projected ServiceAccount token (an OIDC JWT
# issued by the cluster) is exchanged for short-lived cloud credentials.
# No cloud access keys in Secrets. One ServiceAccount per workload, so the
# cloud role is as narrow as the Kubernetes one.
#
# AWS EKS, IAM roles for service accounts (IRSA): the IAM role's trust policy
# allows sts:AssumeRoleWithWebIdentity for this cluster's OIDC provider and
# sub = system:serviceaccount:shop:orders-api. (EKS Pod Identity is the newer
# alternative: an association made through the EKS API, no annotation.)
apiVersion: v1
kind: ServiceAccount
metadata:
name: orders-api
namespace: shop
annotations:
eks.amazonaws.com/role-arn: arn:aws:iam::111122223333:role/orders-api-s3-read
automountServiceAccountToken: false
---
# GKE Workload Identity Federation: either grant IAM roles directly to the
# principal principal://iam.googleapis.com/projects/PROJECT_NUMBER/locations/
# global/workloadIdentityPools/PROJECT_ID.svc.id.goog/subject/ns/shop/sa/orders-api
# (no annotation needed), or link to an IAM service account as below.
apiVersion: v1
kind: ServiceAccount
metadata:
name: orders-api-gke
namespace: shop
annotations:
iam.gke.io/gcp-service-account: orders-api@acme-prod.iam.gserviceaccount.com
---
# Azure Workload Identity (AKS): the managed identity has a federated identity
# credential for this subject; the Pod must also carry the label
# azure.workload.identity/use: "true" so the webhook injects the token volume
# and AZURE_FEDERATED_TOKEN_FILE.
apiVersion: v1
kind: ServiceAccount
metadata:
name: orders-api-aks
namespace: shop
annotations:
azure.workload.identity/client-id: 00000000-0000-0000-0000-000000000000سناریوهای واقعی:
- Worker صف Laravel در S3 مینویسد؛ SA با نام
shop-queueو IRSA میگیرد، در حالی که Podهای Web هیچ دسترسی ابری ندارند. - External Secrets Operator با Role اختصاصی IRSA از AWS Secrets Manager میخواند.
- GitHub Actions همین ایده را معکوس استفاده میکند: ابر به OIDC توکن Workflow اعتماد میکند؛ CI/CD.
- چند Cluster در GKE یک Workload identity pool دارند؛ نام Namespace و SA یکسان، Principal یکسان میدهد، پس نامگذاری تصمیم امنیتی است.
| ابر | سازوکار | سمت Kubernetes | سمت ابر |
|---|---|---|---|
| AWS EKS | IRSA | Annotation روی SA با eks.amazonaws.com/role-arn | IAM OIDC provider و Trust policy نقش |
| AWS EKS | Pod Identity | تعریف ارتباط در EKS API، عامل DaemonSet | Role با اعتماد به pods.eks.amazonaws.com |
| Google GKE | Workload Identity Federation | Workload pool خوشه؛ iam.gke.io/gcp-service-account اختیاری | IAM binding به Principal |
| Azure AKS | Azure Workload Identity | Annotation روی SA با azure.workload.identity/client-id و Label روی Pod با azure.workload.identity/use | Managed identity و Federated identity credential |
| مدیریت شخصی | همان الگو | OIDC discovery قابل دسترس با --service-account-issuer | IAM با پشتیبانی OIDC federation، مانند Vault یا ابر |
راهحل: کلید ابری در Secret نگذارید؛ هر workload یک SA و Role ابری داشته باشد. Egress به Metadata را متناسب با Platform تعیین کنید. در EKS با IRSA، اگر Pod به Role خود Node نیاز ندارد، میتوان Egress آن را مسدود کرد تا به 169.254.169.254 دسترسی نداشته باشد. در GKE این آدرس مسیر دریافت اعتبارنامهٔ Workload Identity است و بستن آن قابلیت را خراب میکند: "If you have a strict cluster network policy in place, you must allow egress ... Allow egress to 169.254.169.252/32 on port 988. For clusters running GKE Dataplane V2, ensure that you allowed egress to 169.254.169.254/32 on port 80." Workload بدون نیاز ابری، مانند Web در Laravel این فصل، روی هیچ Platform مجوز خروجی Metadata نمیگیرد.
Pod Security Admission: برچسب Namespace، حالت enforce، audit و warn، نسخه و استثنا حیاتی
به زبان ساده: افزونهٔ داخلی پذیرش (Admission) هر Pod را با یکی از سه سطح Pod Security Standards یعنی privileged، baseline و restricted میسنجد. انتخاب با Label در هر Namespace است. محدودیت هر سطح در امنیت کانتینر آمده؛ اینجا رفتار Labelها را بررسی میکنیم.
بدفهمی رایج: «Label با enforce، Deployment را رد میکند.» مستند میگوید: "audit and warning modes are applied to the workload resources. However, enforce mode is not applied to workload resources, only to the resulting pod objects." Deployment پذیرفته میشود و رد Podهایش را بعداً در Eventهای ReplicaSet میبینید.
تعریف: privileged، baseline و restricted سطوح تجمعی (Cumulative) هستند؛ هر سطح محدودیتهای سطح قبلی را نیز شامل میشود. PSA از v1.25 پایدار است و pod-security.kubernetes.io/<MODE>: <LEVEL> و مقدار اختیاری pod-security.kubernetes.io/<MODE>-version: <VERSION> را میخواند: "VERSION must be a valid Kubernetes minor version, or latest". حالتها: "enforce: Policy violations will cause the pod to be rejected"؛ "audit: Policy violations will trigger the addition of an audit annotation to the event recorded in the audit log, but are otherwise allowed"؛ "warn: Policy violations will trigger a user-facing warning, but are otherwise allowed". استثنا (Exemption) در فایل ثابت PodSecurityConfiguration با --admission-control-config-file، Username، Runtime class و Namespace را مشخص میکند: "Requests meeting exemption criteria are ignored by the Admission Controller (all enforce, audit and warn behaviors are skipped)." همین فایل defaults را برای Namespace بدون Label تعیین میکند؛ پیشفرض اولیه privileged است.
kubectl label ns payments pod-security.kubernetes.io/enforce=restricted --dry-run=server --overwrite
1 API server evaluates existing Pods in payments against restricted:latest
2 prints warnings per Pod that would be rejected; nothing changes (dry run)
3 set warn=restricted + audit=restricted, keep enforce=baseline; fix manifests until warnings stop
4 set enforce=restricted, enforce-version=v1.37 (pinned), commit the Namespace manifest via GitOps
5 only patch-namespaces holders can undo it: keep that verb with the platform team# Pod Security Admission is configured per namespace with labels:
# pod-security.kubernetes.io/<MODE>: <LEVEL> MODE = enforce | audit | warn
# pod-security.kubernetes.io/<MODE>-version: <VERSION> VERSION = v1.NN | latest
# What each LEVEL (privileged, baseline, restricted) forbids is in the
# Container Security chapter; this file is about where the labels go.
apiVersion: v1
kind: Namespace
metadata:
name: shop
labels:
pod-security.kubernetes.io/enforce: restricted
pod-security.kubernetes.io/enforce-version: v1.37 # pinned: upgrades do not change it
pod-security.kubernetes.io/warn: restricted
pod-security.kubernetes.io/warn-version: latest # see what the next version would reject
pod-security.kubernetes.io/audit: restricted
pod-security.kubernetes.io/audit-version: latest
---
# A team namespace on its way to restricted: enforce the floor (baseline),
# warn and audit the target (restricted) until the warnings stop.
apiVersion: v1
kind: Namespace
metadata:
name: payments
labels:
pod-security.kubernetes.io/enforce: baseline
pod-security.kubernetes.io/enforce-version: v1.37
pod-security.kubernetes.io/warn: restricted
pod-security.kubernetes.io/warn-version: latest
pod-security.kubernetes.io/audit: restricted
pod-security.kubernetes.io/audit-version: latest
---
# Node agents (CNI, CSI, log shippers) genuinely need host access. They get
# their own namespace with privileged, and nobody else can create Pods there
# (RBAC), so the exception does not leak to application teams.
apiVersion: v1
kind: Namespace
metadata:
name: node-agents
labels:
pod-security.kubernetes.io/enforce: privileged
pod-security.kubernetes.io/enforce-version: v1.37
pod-security.kubernetes.io/warn: baseline
pod-security.kubernetes.io/warn-version: latest# kube-apiserver --admission-control-config-file=/etc/kubernetes/admission-configuration.yaml
# Cluster-wide PSA defaults for namespaces WITHOUT labels, and the exemptions.
# Managed clusters (EKS, GKE, AKS) do not let you pass this file; use labels.
apiVersion: apiserver.config.k8s.io/v1
kind: AdmissionConfiguration
plugins:
- name: PodSecurity
configuration:
apiVersion: pod-security.admission.config.k8s.io/v1
kind: PodSecurityConfiguration
# The built-in default is privileged everywhere. Raising it to baseline
# means a forgotten namespace label fails safe instead of open.
defaults:
enforce: "baseline"
enforce-version: "latest"
audit: "restricted"
audit-version: "latest"
warn: "restricted"
warn-version: "latest"
exemptions:
# Exempt requests skip enforce, audit and warn entirely. Keep these
# lists short and review them: an exempt namespace is a hole.
usernames: []
runtimeClasses: []
namespaces: ["kube-system"]سناریوهای واقعی:
- پیام
Warning: would violate PodSecurity "restricted:latest": allowPrivilegeEscalation != falseدر هرkubectl applyباwarn=restrictedنشانهٔ درست کارکردن مرحلهٔ مهاجرت است. - CNI DaemonSet در
kube-systemبه شبکهٔ میزبان نیاز دارد؛ Namespace ممتاز یا استثنا بدهید، نه سطح ضعیفتر به Namespace برنامه. - تیم با
editنمیتواند Label Namespace را به privileged تغییر دهد؛editمجوز Patch روی Namespace ندارد.adminنیز "to the namespace itself" دسترسی نوشتن ندارد. - پس از ارتقای Cluster،
enforce-version: latestممکن است Pod قبلاً مجاز را با قواعد restricted جدید رد کند؛ نسخهٔ ثابت تغییر نمیکند.
| حالت | اثر روی Pod | اثر روی Deployment و مشابه آن | محل مشاهده |
|---|---|---|---|
enforce | رد | ارزیابی نمیشود و پذیرفته میشود | Event در ReplicaSet: FailedCreate ... violates PodSecurity |
warn | مجاز | ارزیابی میشود | خط Warning در kubectl |
audit | مجاز | ارزیابی میشود | Annotation رخداد: pod-security.kubernetes.io/audit-violations |
| استثنا | بهکلی نادیده گرفته میشود | بدون بررسی | سنجهٔ pod_security_exemptions_total |
راهحل: همهٔ Namespaceهای برنامه enforce: restricted با نسخهٔ ثابت و warn/audit روی latest داشته باشند. اگر API server دست شماست، Default خوشه را غیر privileged کنید. استثناها را مانند قواعد Firewall بازبینی کنید.
Admission webhook: ValidatingWebhookConfiguration، MutatingWebhookConfiguration و failurePolicy مهم
به زبان ساده: Webhook سرویس HTTPS است که API server در پذیرش (Admission) شیء را برایش میفرستد. پاسخ «مجاز»، «رد» یا «مجاز با این JSON patch» است. Policy Engine و تزریقکنندهٔ Sidecar از این سازوکار استفاده میکنند.
بدفهمی رایج: «failurePolicy: Ignore انتخاب امن است.» این انتخاب دسترسپذیری را حفظ میکند؛ با قطعی Webhook، درخواست انگار سیاستی وجود ندارد ادامه مییابد. برای سیاست امنیتی یعنی Fail open. مقدار Fail امنیت را حفظ میکند ولی دسترسپذیری را تهدید میکند؛ انتخاب به چیزی بستگی دارد که Webhook محافظت میکند.
تعریف: MutatingWebhookConfiguration و ValidatingWebhookConfiguration، Webhook را با rules شامل Operations، API groups، Versions، Resources و Scope، همراه namespaceSelector، objectSelector و حداکثر ۶۴ عبارت CEL در matchConditions ثبت میکنند. در خطای شرط: "for failurePolicy: Fail, reject the request (without calling the webhook)". "The default failurePolicy for an admission webhooks is Fail" و "Ignore means that an error calling the webhook is ignored and the API request is allowed to continue." مهلت پیشفرض: "The timeout for an admission webhook defaults to 10 seconds." فیلد sideEffects امن بودن Dry run را مشخص میکند. Mutating webhook میتواند reinvocationPolicy: IfNeeded داشته باشد؛ "It defaults to Never". رد صریح، "always denies the API request, regardless of the failurePolicy setting." دام قفلکردن خود در مرجع Best practices، Webhookی است که Namespace خودش یا kube-system را هم میگیرد.
The policy webhook's Pods are all evicted during a node upgrade (failurePolicy: Fail, no namespaceSelector)
1 kube-scheduler can still bind Pods, but every Pod CREATE calls the webhook -> connection refused
2 the webhook's own Deployment cannot recreate its Pods (they are Pods too) -> deadlock
3 fix during the incident: kubectl delete validatingwebhookconfiguration <name> (needs that RBAC)
4 fix for good: exclude kube-system and the webhook's namespace, run 3 replicas with a PDB,
set timeoutSeconds 3-5, matchConditions to skip system ServiceAccounts# The two webhook registration kinds, with the settings that decide whether a
# broken webhook takes the cluster down (failurePolicy, timeoutSeconds,
# namespaceSelector, matchConditions). Policy engines install objects like
# these for you; read theirs with:
# kubectl get validatingwebhookconfigurations,mutatingwebhookconfigurations -o yaml
apiVersion: admissionregistration.k8s.io/v1
kind: MutatingWebhookConfiguration
metadata:
name: acme-sidecar-injector
webhooks:
- name: inject.sidecar.acme.io
admissionReviewVersions: ["v1"]
sideEffects: None
reinvocationPolicy: IfNeeded # run again if a later mutation changes the Pod
failurePolicy: Ignore # a missing sidecar is better than no Pods at all
timeoutSeconds: 3 # default 10; admission latency adds up
clientConfig:
service:
name: sidecar-injector
namespace: platform-system
path: /mutate
caBundle: Cg== # placeholder: the injector's serving CA
rules:
- apiGroups: [""]
apiVersions: ["v1"]
operations: ["CREATE"]
resources: ["pods"]
scope: Namespaced
namespaceSelector:
matchLabels:
acme.io/sidecar-injection: enabled
---
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingWebhookConfiguration
metadata:
name: acme-image-policy
webhooks:
- name: images.policy.acme.io
admissionReviewVersions: ["v1"]
sideEffects: None
failurePolicy: Fail # the default: fail closed, a security check must not skip
timeoutSeconds: 5
clientConfig:
service:
name: image-policy
namespace: platform-system
path: /validate
caBundle: Cg==
rules:
- apiGroups: [""]
apiVersions: ["v1"]
operations: ["CREATE", "UPDATE"]
resources: ["pods"]
# Never call ourselves for the namespaces the webhook and the control
# plane run in: otherwise a dead webhook blocks its own restart.
namespaceSelector:
matchExpressions:
- key: kubernetes.io/metadata.name
operator: NotIn
values: ["kube-system", "platform-system"]
# Skip requests from node agents' ServiceAccounts without a network call.
matchConditions:
- name: not-node-agents
expression: "!request.userInfo.username.startsWith('system:serviceaccount:node-agents:')"سناریوهای واقعی:
- تزریق Sidecar در Istio یا Linkerd: Mutation؛
Ignoreپذیرفتنی است، چون Pod بدون Sidecar همچنان Pod است. - Validation در Kyverno و Gatekeeper: برای امنیت
Fail، با استثناهای بالا. - مستند Gatekeeper: "Gatekeeper is defaulting to using failurePolicy: Ignore for admission request webhook errors. The impact of this is that when the webhook is down, or otherwise unreachable, constraints will not be enforced."
- Webhook کند دو ثانیه به هر
kubectl applyو همهٔ نوشتنهای Controller اضافه میکند.
| تنظیم | پیشفرض | Webhook امنیتی | Webhook تسهیلکننده |
|---|---|---|---|
failurePolicy | Fail | Fail | Ignore |
timeoutSeconds | 10 | 3-5 | 1-3 |
namespaceSelector | همه | حذف kube-system و خودش | Label انتخابی |
matchConditions | ندارد | عبور Userهای سیستمی | محدود به شیء مرتبط |
sideEffects | الزامی | None | None یا NoneOnDryRun |
| نمونه (Replica) / PDB | — | ≥ 2 Replica و PDB | ≥ 2 |
راهحل: اگر PSA یا ValidatingAdmissionPolicy قاعده را بیان میکند، سیاست داخل پردازه (Process) را ترجیح دهید. Webhook امنیتی با منع هنگام خرابی (Fail closed)، استثنا و افزونگی اجرا شود؛ تأخیر Admission را با سنجههای Admission webhook سرور پایش کنید.
ValidatingAdmissionPolicy و CEL، همراه MutatingAdmissionPolicy حیاتی
به زبان ساده: قاعده را با عبارت کوتاه CEL یا Common Expression Language مینویسید و خود API server ارزیابی میکند. سرویس اضافه برای استقرار و Timeout شبکه وجود ندارد.
بدفهمی رایج: «ساخت Policy یعنی اعمال آن.» بدون Binding کاری نمیکند: "At least a ValidatingAdmissionPolicy and a corresponding ValidatingAdmissionPolicyBinding must be defined for a policy to have an effect." Binding عمل نهایی را هم انتخاب میکند.
تعریف: ValidatingAdmissionPolicy در admissionregistration.k8s.io/v1، "Stable since Kubernetes v1.30" است. شامل matchConstraints، paramKind اختیاری، matchConditions، variables با ارزیابی تنبل و امکان ارجاع به متغیر قبلی، و validations با expression، message یا messageExpression و reason است. عبارتها object، oldObject، request، params، namespaceObject، authorizer و variables را میبینند. validationActions در Binding: "Deny: Validation failure results in a denied request"، "Warn: Validation failure is reported to the request client" و "Audit: Validation failure is included in the audit event"؛ "Deny and Warn may not be used together". فیلد failurePolicy خطای CEL و پارامتر مفقود را مدیریت میکند. MutatingAdmissionPolicy با "Stable since Kubernetes v1.36" همین مدل را برای تغییر بهکار میبرد: "with an apply configuration that is merged using the server side apply merge strategy, or a JSON patch".
kubectl apply deployment orders-api (image ghcr.io/acme/orders-api:latest) in shop, binding [Warn, Audit]
1 matchConstraints: apps/v1 deployments CREATE -> policy acme-pod-rules applies
2 binding matchResources: namespace shop not excluded -> evaluate
3 variables.podSpec = object.spec.template.spec; variables.containers = containers + initContainers
4 validation 2 (disallow latest tag) -> false -> messageExpression builds the image list
5 Warn: kubectl prints "Warning: Validation failed for ValidatingAdmissionPolicy ..."; Audit: annotation in the audit event
6 request succeeds (no Deny yet); switch the binding to [Deny] once the warnings stop# ValidatingAdmissionPolicy (admissionregistration.k8s.io/v1, stable since
# v1.30): CEL evaluated inside kube-apiserver, no webhook to run or to fail.
# Three rules most clusters want on top of Pod Security Admission:
# require non-root, disallow the latest tag, require resource limits.
# Matches Pods AND the workload kinds, so `kubectl apply` of a bad Deployment
# fails at once instead of a ReplicaSet failing silently later.
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingAdmissionPolicy
metadata:
name: acme-pod-rules.acme.io
spec:
failurePolicy: Fail # a CEL runtime error rejects; there is no network to fail
matchConstraints:
resourceRules:
- apiGroups: [""]
apiVersions: ["v1"]
operations: ["CREATE", "UPDATE"]
resources: ["pods"]
- apiGroups: ["apps"]
apiVersions: ["v1"]
operations: ["CREATE", "UPDATE"]
resources: ["deployments", "statefulsets", "daemonsets"]
- apiGroups: ["batch"]
apiVersions: ["v1"]
operations: ["CREATE", "UPDATE"]
resources: ["jobs"]
variables:
- name: podSpec
expression: "object.kind == 'Pod' ? object.spec : object.spec.template.spec"
- name: containers
expression: "variables.podSpec.containers + variables.podSpec.?initContainers.orValue([])"
- name: podNonRoot
expression: "variables.podSpec.?securityContext.?runAsNonRoot.orValue(false)"
validations:
# require non-root: every container is non-root, by its own setting or the Pod's
- expression: >-
variables.containers.all(c,
c.?securityContext.?runAsNonRoot.orValue(variables.podNonRoot) &&
c.?securityContext.?runAsUser.orValue(variables.podSpec.?securityContext.?runAsUser.orValue(1)) != 0)
message: "containers must set runAsNonRoot: true and must not run as UID 0"
reason: Forbidden
# disallow latest tag: an explicit tag that is not latest, or a digest
- expression: >-
variables.containers.all(c,
c.image.contains('@sha256:') ||
(c.image.substring(c.image.lastIndexOf('/') + 1).contains(':') &&
!c.image.endsWith(':latest')))
messageExpression: >-
'image tag missing or latest: ' + variables.containers.filter(c,
!c.image.contains('@sha256:') &&
(!c.image.substring(c.image.lastIndexOf('/') + 1).contains(':') ||
c.image.endsWith(':latest'))).map(c, c.image).join(', ')
# require limits: memory limit and cpu/memory requests on app containers
- expression: >-
variables.podSpec.containers.all(c,
has(c.resources) && has(c.resources.limits) && 'memory' in c.resources.limits &&
has(c.resources.requests) && 'cpu' in c.resources.requests && 'memory' in c.resources.requests)
message: "every container needs requests.cpu, requests.memory and limits.memory"
---
# The binding decides WHERE and HOW. Roll out as [Warn, Audit] first: users
# see warnings on kubectl apply and the audit log records each failure;
# then switch to [Deny]. (Deny and Warn together are not allowed.)
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingAdmissionPolicyBinding
metadata:
name: acme-pod-rules-app-namespaces.acme.io
spec:
policyName: acme-pod-rules.acme.io
validationActions: [Warn, Audit]
matchResources:
namespaceSelector:
matchExpressions:
- key: kubernetes.io/metadata.name
operator: NotIn
values: ["kube-system", "node-agents"]سناریوهای واقعی:
- جایگزینی Template سادهٔ Gatekeeper برای Label مالک هر Deployment با VAP، و حذف یک Webhook از مسیر حساس.
- Limits هر Namespace با
paramKind، ConfigMap یا CRD هر تیم و یک Binding برای هر تیم. - منع حذف Namespace دارای Label با نام
acme.io/protectedمگرauthorizerعضویت User در گروه Platform را تأیید کند. - Kyverno با
spec.autogenاز سیاست خود VAP میسازد تا قاعده داخل Process اجرا شود.
| موضوع | ValidatingAdmissionPolicy | Policy Engine مبتنی بر Webhook |
|---|---|---|
| دسترسپذیری | داخل Process؛ بدون شبکه | Deployment جدا و Timeout |
| زبان | CEL | Rego در Gatekeeper، CEL/YAML در Kyverno |
| تغییر (Mutation) | MutatingAdmissionPolicy از v1.36 | بله |
| دادهٔ بیرونی، Registry و امضا | خیر | بله |
| گزارش اشیای موجود | خیر؛ فقط هنگام Admission | Background scan، PolicyReport و Audit در Gatekeeper |
| عرضهٔ تدریجی (Rollout) | [Warn, Audit] → [Deny] | Audit/dryrun → Enforce/deny |
راهحل: الزام غیر root، منع Tag برابر latest و الزام Limits در اندازهٔ VAP هستند. فقط برای کاری که CEL داخل API server نمیتواند انجام دهد سراغ Engine بروید. عبارت را در CEL playground تست و با [Warn, Audit] عرضه کنید.
موتورهای سیاست: Kyverno با ClusterPolicy و ValidatingPolicy، و OPA Gatekeeper با ConstraintTemplate مهم
به زبان ساده: موتور سیاست (Policy Engine) یک Webhook بههمراه کتابخانهٔ قواعد در قالب اشیای Kubernetes است. Kyverno از YAML و CEL، Gatekeeper از Rego استفاده میکند. هر دو اشیای در حال اجرا را هم اسکن و تخلف را گزارش میکنند.
بدفهمی رایج: «Policy در Kyverno یعنی kind: ClusterPolicy.» این API قدیمی است؛ مستند Kyverno 1.18 عبارت "ClusterPolicy Deprecated" را دارد و ValidatingPolicy، MutatingPolicy، GeneratingPolicy، DeletingPolicy و ImageValidatingPolicy در policies.kyverno.io/v1 را معرفی میکند. ClusterPolicy موجود کار میکند و بیشتر Chart و مقالهها هنوز آن را دارند، پس هر دو را باید بخوانید. ساختارش rules با match، exclude و یکی از validate، mutate، generate، verifyImages است.
تعریف: در Kyverno، "A ValidatingPolicy is a superset of a ValidatingAdmissionPolicy" و Background scan، Exception و Autogen برای Pod controller اضافه میکند. در ClusterPolicy، "mutation rules are applied before validation rules"؛ failureAction در Validation برابر Enforce یا Audit است و "namespaced policies cannot override or modify behaviors described in a cluster-wide policy". در OPA Gatekeeper v3.23، "Validation uses ConstraintTemplate and Constraint resources" و "Before you can define a constraint, you must first define a ConstraintTemplate, which describes both the Rego that enforces the constraint and the schema of the constraint." مقدار پیشفرض enforcementAction در Constraint، deny است؛ dryrun و warn هم ممکناند. Audit controller منابع موجود را ارزیابی میکند: "By default, all constraints are opted-in audit". مجموعهٔ gatekeeper-library شامل Template آمادهٔ k8sdisallowedtags، k8scontainerlimits و معادلهای PSP است.
Rolling out "disallow latest tag" with Gatekeeper on a live cluster
1 apply ConstraintTemplate k8sdisallowedtags (creates the CRD kind K8sDisallowedTags)
2 apply Constraint no-latest-in-app-namespaces with enforcementAction: dryrun
3 audit controller writes violations to the Constraint's status every audit interval
4 teams fix manifests; kubectl get k8sdisallowedtags -o yaml shows totalViolations: 0
5 switch to enforcementAction: deny; new :latest Pods are rejected at admission# Kyverno ValidatingPolicy (policies.kyverno.io/v1): the same CEL model as the
# built-in ValidatingAdmissionPolicy, plus background scans, PolicyReports and
# exceptions. Adapted from the kyverno/policies library (best-practices-vpol/
# disallow-latest-tag, require-pod-requests-limits; pod-security-vpol/
# require-run-as-nonroot), with the library's exceptions.* terms removed.
# Kyverno autogenerates the Deployment/StatefulSet/Job variants from a Pod rule.
apiVersion: policies.kyverno.io/v1
kind: ValidatingPolicy
metadata:
name: acme-pod-rules
spec:
validationActions: [Audit] # step 1: report only; step 2: [Deny]
evaluation:
background:
enabled: true # also scan what is already running
matchConstraints:
resourceRules:
- apiGroups: [""]
apiVersions: [v1]
operations: [CREATE, UPDATE]
resources: [pods]
namespaceSelector:
matchExpressions:
- key: kubernetes.io/metadata.name
operator: NotIn
values: [kube-system, kyverno, node-agents]
variables:
- name: allContainers
expression: >-
object.spec.containers + object.spec.?initContainers.orValue([])
validations:
- expression: >-
variables.allContainers.all(c,
c.?securityContext.?runAsNonRoot.orValue(
object.spec.?securityContext.?runAsNonRoot.orValue(false)) == true)
message: "Running as root is not allowed: set securityContext.runAsNonRoot to true."
- expression: >-
variables.allContainers.all(c,
c.image.substring(c.image.lastIndexOf('/') + 1).contains(':') ||
c.image.contains('@'))
message: "An image tag is required."
- expression: >-
variables.allContainers.all(c, !c.image.endsWith(':latest'))
message: "Using a mutable image tag e.g. 'latest' is not allowed."
- expression: >-
object.spec.containers.all(c,
has(c.resources) && has(c.resources.requests) &&
has(c.resources.requests.memory) && has(c.resources.requests.cpu) &&
has(c.resources.limits) && has(c.resources.limits.memory))
message: "CPU and memory resource requests and memory limits are required for containers."# OPA Gatekeeper: a ConstraintTemplate (Rego + the parameter schema) and a
# Constraint that applies it. The template is copied unchanged from the
# gatekeeper-library (library/general/disallowedtags/template.yaml, v1.0.2);
# The library publishes it in Rego v0 syntax (Gatekeeper v3.23 bundles OPA v1.17).
# Roll out with enforcementAction: dryrun (audit only), then deny.
apiVersion: templates.gatekeeper.sh/v1
kind: ConstraintTemplate
metadata:
name: k8sdisallowedtags
annotations:
metadata.gatekeeper.sh/title: "Disallow tags"
metadata.gatekeeper.sh/version: 1.0.2
description: >-
Requires container images to have an image tag different from the ones in
the specified list.
https://kubernetes.io/docs/concepts/containers/images/#image-names
spec:
crd:
spec:
names:
kind: K8sDisallowedTags
validation:
# Schema for the `parameters` field
openAPIV3Schema:
type: object
properties:
exemptImages:
description: >-
Any container that uses an image that matches an entry in this list will be excluded
from enforcement. Prefix-matching can be signified with `*`. For example: `my-image-*`.
It is recommended that users use the fully-qualified Docker image name (e.g. start with a domain name)
in order to avoid unexpectedly exempting images from an untrusted repository.
type: array
items:
type: string
tags:
type: array
description: Disallowed container image tags.
items:
type: string
targets:
- target: admission.k8s.gatekeeper.sh
rego: |
package k8sdisallowedtags
import data.lib.exempt_container.is_exempt
violation[{"msg": msg}] {
container := input_containers[_]
not is_exempt(container)
tags := [tag_with_prefix | tag := input.parameters.tags[_]; tag_with_prefix := concat(":", ["", tag])]
strings.any_suffix_match(container.image, tags)
msg := sprintf("container <%v> uses a disallowed tag <%v>; disallowed tags are %v", [container.name, container.image, input.parameters.tags])
}
violation[{"msg": msg}] {
container := input_containers[_]
not is_exempt(container)
parts := split(container.image, "/")
not contains(parts[count(parts) - 1], ":")
msg := sprintf("container <%v> didn't specify an image tag <%v>", [container.name, container.image])
}
input_containers[c] {
c := input.review.object.spec.containers[_]
}
input_containers[c] {
c := input.review.object.spec.initContainers[_]
}
input_containers[c] {
c := input.review.object.spec.ephemeralContainers[_]
}
libs:
- |
package lib.exempt_container
is_exempt(container) {
exempt_images := object.get(object.get(input, "parameters", {}), "exemptImages", [])
img := container.image
exemption := exempt_images[_]
_matches_exemption(img, exemption)
}
_matches_exemption(img, exemption) {
not endswith(exemption, "*")
exemption == img
}
_matches_exemption(img, exemption) {
endswith(exemption, "*")
prefix := trim_suffix(exemption, "*")
startswith(img, prefix)
}
---
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sDisallowedTags
metadata:
name: no-latest-in-app-namespaces
spec:
enforcementAction: dryrun # then: deny (the default)
match:
kinds:
- apiGroups: [""]
kinds: ["Pod"]
excludedNamespaces: ["kube-system", "gatekeeper-system", "node-agents"]
parameters:
tags: ["latest"]
exemptImages: []سناریوهای واقعی:
- تیم Platform با Helm، Kyverno را نصب میکند؛ Policyها در Git هستند و Argo CD آنها را Sync میکند. تخلف بهشکل شکست Sync دیده میشود.
- تیم امنیت از قبل برای Terraform plan با
conftestو CI، Rego مینویسد؛ Gatekeeper انتخاب مناسبی است. generateدر Kyverno، اکنون GeneratingPolicy، برای هر Namespace جدید Default-deny NetworkPolicy میسازد.kyverno testوgator verifyدر CI سیاست را پیش از Merge روی Fixture تست میکنند.
| موضوع | Kyverno | OPA Gatekeeper | ValidatingAdmissionPolicy |
|---|---|---|---|
| زبان | CEL جاری؛ الگوی JMESPath در ClusterPolicy قدیمی | Rego | CEL |
| Mutation / Generation | بله / بله | Mutation با Assign؛ بدون Generation | MutatingAdmissionPolicy |
| امضای Image | ImageValidatingPolicy، verifyImages | External data provider | خیر |
| گزارش شیء موجود | PolicyReport | Audit status در Constraint | خیر |
| رفتار پیشفرض خرابی | قابل تنظیم در Policy | Ignore طبق مستند | داخل Process |
| CLI برای CI | kyverno test | gator | kubectl --dry-run=server |
راهحل: یک Engine برای هر Cluster انتخاب کنید؛ PSA حداقل حفاظت، VAP قواعد ساده، و Engine امضا، Mutation و گزارش را پوشش دهد. هر Policy با برنامهٔ زماندار از Audit به Enforce برسد.
پذیرش زنجیرهٔ تأمین: بررسی امضای Image با cosign و Kyverno verifyImages مهم
به زبان ساده: CI هر تصویر (Image) ساختهشده را امضا میکند و Cluster، Image بدون امضای CI شما را اجرا نمیکند. پس رمز دزدیدهشدهٔ مخزن تصویر (Registry) بهتنهایی برای ورود کد به محیط عملیاتی کافی نیست.
بدفهمی رایج: «امضا را در CI بررسی میکنیم، پس Cluster پوشش دارد.» CI تنها مسیر ورود نیست؛ انسان با edit میتواند kubectl set image را به هر Image اشاره دهد. بررسی باید در Admission و با چکیدهٔ محتوا (Digest) باشد؛ امضا روی Digest است و برچسب (Tag) پس از بررسی جابهجا میشود.
تعریف: امضای بدون کلید (Keyless signing) در cosign و Sigstore، امضا (Signature) را با گواهی کوتاه Fulcio و ورودی Transparency log در Rekor به هویت OIDC نسبت میدهد. در GitHub Actions صادرکننده https://token.actions.githubusercontent.com و Subject مسیر Workflow است. ImageValidatingPolicy در Kyverno، matchImageReferences، attestors شامل هویت Keyless، کلید و گواهی Notary و CEL validations با verifyImageSignatures(image, [attestors.cosign]) دارد. validationConfigurations.mutateDigest، "Mutates image tags to digests (recommended to avoid mutable tags)" و verifyDigest، "Ensures that images are verified with a digest instead of tags". در ClusterPolicy قدیمی این کار با verifyImages، imageReferences و attestors.entries.keyless شامل subject، issuer و rekor.url انجام میشود: "The rule mutates matching images to add the image digest, when mutateDigest is set to true (which is the default)".
Pod with ghcr.io/acme/orders-api:1.4.2 created in shop
1 Kyverno ImageValidatingPolicy matches ghcr.io/acme/*
2 resolve tag -> digest sha256:D; fetch cosign signature for D from the registry
3 verify Fulcio cert chain, identity = https://github.com/acme/orders-api/.github/workflows/release.yml@refs/tags/v1.4.2
4 check Rekor inclusion; validation expression true
5 mutate image to ghcr.io/acme/orders-api:1.4.2@sha256:D -> Pod admitted with a pinned digest# Image signature verification at admission: only images from ghcr.io/acme
# signed keyless (cosign + Sigstore Fulcio/Rekor) by this organisation's
# GitHub Actions release workflow may run. Shape taken from the Kyverno
# ImageValidatingPolicy docs (Cosign Keyless Verification sample).
apiVersion: policies.kyverno.io/v1
kind: ImageValidatingPolicy
metadata:
name: verify-acme-images
spec:
validationActions: [Deny]
failurePolicy: Fail # registry or Rekor unreachable -> reject (fail closed)
webhookConfiguration:
timeoutSeconds: 15 # signature lookups are network calls
matchConstraints:
resourceRules:
- apiGroups: [""]
apiVersions: ["v1"]
operations: ["CREATE", "UPDATE"]
resources: ["pods"]
matchImageReferences:
- glob: "ghcr.io/acme/*"
# lab only: lets unsigned-test-pod.yaml prove the rejection with a public,
# existing, unsigned image; remove in production
- glob: "ghcr.io/kyverno/test-verify-image:unsigned"
validationConfigurations:
mutateDigest: true # rewrite :1.4.2 to @sha256:... after verifying
verifyDigest: true
required: true
attestors:
- name: cosign
cosign:
keyless:
identities:
- subject: "https://github.com/acme/*/.github/workflows/release.yml@refs/tags/*"
issuer: "https://token.actions.githubusercontent.com"
ctlog:
url: "https://rekor.sigstore.dev"
validations:
- expression: >-
images.containers.map(image, verifyImageSignatures(image, [attestors.cosign])).all(e, e > 0)
message: "image is not signed by an acme release workflow"# The older Kyverno policy kind, still found in most clusters: ClusterPolicy
# (kyverno.io/v1), marked Deprecated in the Kyverno 1.18 docs in favour of
# ValidatingPolicy / ImageValidatingPolicy. Same intent as the two files next
# to this one: verifyImages with cosign keyless, and a pattern-style validate rule.
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
name: acme-legacy-images
spec:
webhookConfiguration:
timeoutSeconds: 30
rules:
- name: verify-acme-signature
match:
any:
- resources:
kinds: [Pod]
verifyImages:
- imageReferences:
- "ghcr.io/acme/*"
failureAction: Enforce
mutateDigest: true
attestors:
- entries:
- keyless:
subject: "https://github.com/acme/*/.github/workflows/release.yml@refs/tags/*"
issuer: "https://token.actions.githubusercontent.com"
rekor:
url: https://rekor.sigstore.dev
- name: disallow-latest-tag
match:
any:
- resources:
kinds: [Pod]
validate:
failureAction: Audit
message: "Using a mutable image tag e.g. 'latest' is not allowed."
pattern:
spec:
containers:
- image: "!*:latest"سناریوهای واقعی:
- Hotfix دستی Pushشده از لپتاپ رد میشود؛ باید از Release workflow بگذرد.
- Rekor یا Registry در دسترس نیست؛
failurePolicy: Failساخت Pod جدید را میبندد. امضاها را با ارجاعدهنده (Referrer) در OCI همراه Image Mirror و Webhook را پایش کنید. - Image شخص ثالث مانند ingress-nginx با هویت منتشرشدهٔ فروشنده در Attestor دوم بررسی میشود.
- علاوه بر امضا، گواهی فهرست مواد نرمافزاری (SBOM) یا اسکن آسیبپذیری با
verifyAttestationSignaturesلازم است.
| بررسیکننده | محل | نکته |
|---|---|---|
| Kyverno ImageValidatingPolicy / verifyImages | Admission webhook | cosign و Notary؛ Mutation به Digest |
| Sigstore policy-controller | Admission webhook | CRD با نام ClusterImagePolicy |
| Gatekeeper و External data provider | Admission webhook | مثلاً Ratify |
cosign verify در CI/CD | Pipeline | لازم است، کافی نیست |
| امضا با cosign sign در GitHub Actions یا GitLab CI | Build | مسئولیت امنیت کانتینر |
راهحل: در CI با Digest امضا کنید، در Admission با هویت مشخص بررسی کنید، Image را به Digest تغییر دهید. قطعی بررسی یعنی توقف استقرار، نه دلیلی برای Fail open.
ثبت ممیزی: سطح سیاست، مرحله، Backend و هشدارها حیاتی
به زبان ساده: API server میتواند برای هر درخواست ثبت کند چه کسی، چه کاری، چه وقت، از کجا و با چه نتیجهای انجام داده است. سیاست ممیزی (Audit policy) درخواست و میزان جزئیات ثبتشده را انتخاب میکند.
بدفهمی رایج: «Audit پیشفرض فعال است.» در API server خودمدیریتشده: "You can pass a file with the policy to kube-apiserver using the --audit-policy-file flag. If the flag is omitted, no events are logged." در Cluster مدیریتشده نیز تنظیم جداست: EKS control-plane logging، GKE Cloud Audit Logs و AKS diagnostic settings؛ اغلب خاموش یا ناقص است.
تعریف: مرحلههای رخداد RequestReceived، ResponseStarted که "only generated for long-running requests (e.g. watch)"، ResponseComplete و Panic هستند. "The first matching rule sets the audit level of the event". سطح None: "don't log events that match this rule"؛ Metadata: "log events with metadata (requesting user, timestamp, resource, verb, etc.) but not request or response body"؛ Request: "request metadata and body but not response body"؛ سپس RequestResponse. این سطحها جزئیات، حجم و خطر افشا را موازنه میکنند؛ Request روی Secret مقدارش را در لاگ مینویسد. دو Backend داریم: Log که "writes events into the filesystem" با --audit-log-path، -maxage، -maxbackup و -maxsize و حالت پیشفرض blocking؛ و Webhook که "sends events to an external HTTP API" و پیشفرض Batch است. هشدار مرجع: Audit، "increases the memory consumption of the API server".
An attacker with a stolen token tries to read Secrets and exec into a Pod
1 GET /api/v1/namespaces/payments/secrets -> 403; audit: Metadata, user=system:serviceaccount:shop:orders-api, code 403
2 POST .../pods/payments-worker-1/exec -> 403; audit: Metadata, verb=create, resource=pods/exec
3 SIEM rule: >5 403s on secrets or pods/exec from one SA in 5 min -> page on-call
4 on-call: kubectl delete pod orders-api-7d9f (bound token dies), review RBAC, rotate what it touched# kube-apiserver --audit-policy-file=/etc/kubernetes/audit-policy.yaml
# --audit-log-path=/var/log/kubernetes/audit/audit.log
# --audit-log-maxage=30 --audit-log-maxbackup=10 --audit-log-maxsize=100
# Rules are evaluated in order; the FIRST match sets the level.
# Levels: None < Metadata < Request < RequestResponse.
apiVersion: audit.k8s.io/v1
kind: Policy
omitStages:
- "RequestReceived" # one event per request at ResponseComplete is enough
rules:
# 1. Noise that would dominate the log: health checks and the API discovery.
- level: None
nonResourceURLs: ["/healthz*", "/livez*", "/readyz*", "/version", "/openapi*"]
- level: None
users: ["system:kube-proxy"]
verbs: ["watch"]
resources:
- group: ""
resources: ["endpoints", "services"]
# 2. Secrets, ConfigMaps and TokenRequests: who touched them, NEVER the body
# (a Request or RequestResponse level would copy secret values into the log).
- level: Metadata
resources:
- group: ""
resources: ["secrets", "configmaps", "serviceaccounts/token"]
# 3. Interactive access to running containers: always worth an alert.
- level: Metadata
resources:
- group: ""
resources: ["pods/exec", "pods/attach", "pods/portforward", "pods/ephemeralcontainers"]
# 4. Changes to who-can-do-what: keep the full request and response.
- level: RequestResponse
resources:
- group: "rbac.authorization.k8s.io"
resources: ["roles", "rolebindings", "clusterroles", "clusterrolebindings"]
- group: "admissionregistration.k8s.io"
resources: ["validatingwebhookconfigurations", "mutatingwebhookconfigurations",
"validatingadmissionpolicies", "validatingadmissionpolicybindings"]
# 5. Writes to workloads and namespaces (PSA labels live on Namespace objects).
- level: Request
verbs: ["create", "update", "patch", "delete", "deletecollection"]
resources:
- group: ""
resources: ["pods", "services", "namespaces", "serviceaccounts"]
- group: "apps"
- group: "batch"
- group: "networking.k8s.io"
# 6. Reads of everything else: metadata only, and skip the watch stream noise.
- level: Metadata
omitStages:
- "RequestReceived"سناریوهای واقعی:
- هشدار روی
pods/exec،pods/attach،pods/portforward،pods/ephemeralcontainersوget/listرویsecretsتوسط انسان؛ همچنین Binding بهcluster-admin، تغییر Webhook configuration و موجForbiddenاز یک SA. - پس از رخداد، هویت سازندهٔ Deployment استخراج رمزارز،
userAgentو IP مبدأ را پیدا کنید. - حالت
auditدر PSA و عملAuditدر VAP، Annotation به رخداد میافزایند؛ تخلف بدون مسدودکردن دیده میشود. - برای شروع
Metadataهمهجا مناسب است؛RequestResponseفقط برای تغییر RBAC و تنظیم Admission.
| Backend / Platform | فعالسازی | مقصد رخداد |
|---|---|---|
| Log در مدیریت شخصی | --audit-policy-file و --audit-log-path | فایل Node؛ ارسال با Fluent Bit یا Vector |
| Webhook | --audit-webhook-config-file | Falco با Plugin k8saudit یا SIEM collector |
| EKS | نوع audit در Control-plane logging | CloudWatch Logs |
| GKE | Cloud Audit Logs؛ Admin Activity فعال، Data Access قابل تنظیم | Cloud Logging |
| AKS | Diagnostic settings با kube-audit / kube-audit-admin | Log Analytics |
راهحل: سیاستی مانند بالا، سطح Metadata برای Secret؛ هرگز Body را ثبت نکنید. هشدارهای فهرست بالا و نگهداری کافی برای فرایند رخداد. Query لاگ در عیبیابی در مشاهدهپذیری و عیبیابی Kubernetes است.
NetworkPolicy: Default deny، Ingress و Egress، Selector، ipBlock، DNS و CNI حیاتی
به زبان ساده: قواعد Firewall بین Podها با Label نوشته میشوند. پیشفرض هر Pod با Pod دیگر و اینترنت حرف میزند. NetworkPolicy که Pod را انتخاب کند، برای جهتهای مشخصشده آن را به حالت «فقط موارد مجاز» میبرد.
بدفهمی رایج: «Policyها مرتب ارزیابی میشوند و خاصترین برنده است.» ترتیب و Deny نداریم: "Network policies do not conflict; they are additive. If any policy or policies apply to a given pod for a given direction, the connections allowed in that direction from that pod is the union of what the applicable policies allow." اتصال (Connection) مجوز هر دو طرف را میخواهد: "both the egress policy on the source pod and the ingress policy on the destination pod need to allow the connection."
تعریف: "By default, a pod is non-isolated for egress; all outbound connections are allowed" و برای Ingress هم همین است. وقتی Policy انتخابکنندهٔ Pod جهتی را در policyTypes داشته باشد، Pod در آن جهت جدا میشود. قواعد Ingress و Egress همتاها را با podSelector برای Podهای همان Namespace، namespaceSelector، هر دو در یک ورودی برای Podهای با Label مشخص در Namespaceهای مشخص، یا ipBlock تعیین میکنند. دربارهٔ IP: "These should be cluster-external IPs, since Pod IPs are ephemeral and unpredictable". فیلد ports و endPort بازهٔ Port را میدهند. سهگانهٔ podSelector namespaceSelector ipBlock کل واژگان انتخاب همتاست. هر Namespace، Label تغییرناپذیر kubernetes.io/metadata.name دارد. "A default deny-all egress policy also blocks DNS traffic," پس خروجی kube-dns باید صریح مجاز شود. ترافیک "to and from the node where a Pod is running is always allowed". در نهایت: "Network policies are implemented by the network plugin."
The one-entry vs two-entry trap (from the docs)
from:
- namespaceSelector: {matchLabels: {user: alice}}
podSelector: {matchLabels: {role: client}} -> ONE peer: role=client Pods IN alice's namespaces
from:
- namespaceSelector: {matchLabels: {user: alice}}
- podSelector: {matchLabels: {role: client}} -> TWO peers: ANY Pod in alice's namespaces, OR role=client here
-> one dash too many opens the namespace; check with kubectl describe networkpolicy# Namespace-wide default deny, both directions, then DNS for everyone.
# Requires a network plugin that implements NetworkPolicy (Calico, Cilium,
# AWS VPC CNI with network policy enabled, Azure CNI with Cilium, GKE
# Dataplane V2...). Without one these objects are accepted and do nothing.
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: default-deny-all
namespace: shop
spec:
podSelector: {} # every Pod in the namespace
policyTypes: [Ingress, Egress] # isolated in both directions, no rules = nothing allowed
---
# Default-deny egress also blocks DNS. Every Pod may query kube-dns/CoreDNS
# and nothing else on port 53.
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: allow-dns-egress
namespace: shop
spec:
podSelector: {}
policyTypes: [Egress]
egress:
- to:
- namespaceSelector:
matchLabels:
kubernetes.io/metadata.name: kube-system
podSelector: # same list item: kube-dns Pods IN kube-system
matchLabels:
k8s-app: kube-dns
ports:
- {protocol: UDP, port: 53}
- {protocol: TCP, port: 53}سناریوهای واقعی:
- RCE در Laravel،
curl http://169.254.169.254/برای اعتبارنامهٔ ابر وcurl https://kubernetes.default.svcرا امتحان میکند؛ Default-deny egress هر دو را قطع میکند. - پس از Default deny همهجا "could not resolve host" دیده میشود؛ قاعدهٔ Egress برای DNS جا افتاده است.
- API server، Pod نیست؛ تطبیق
ipBlockبعد از Service NAT به پیادهسازی بستگی دارد: "connections from pods to Service IPs that get rewritten to cluster-external IPs may or may not be subject to ipBlock-based policies". - بین Apply سیاست و برنامهریزی CNI فاصله هست: "that pod may be started unprotected, and isolation rules will be applied when the NetworkPolicy handling is completed."
| CNI / Platform | NetworkPolicy استاندارد | قابلیت اضافه |
|---|---|---|
| Calico | بله | NetworkPolicy/GlobalNetworkPolicy در projectcalico.org/v3: ترتیب، Deny، Tier، Host endpoint |
| Cilium | بله | CiliumNetworkPolicy: HTTP در L7، DNS با toFQDNs، Entity مانند kube-apiserver، Deny |
| AWS VPC CNI در EKS | با فعال بودن Network policy agent | Security group برای Pod |
| GKE Dataplane V2 | بله؛ مبتنی بر Cilium | سیاست FQDN در GKE |
| Azure CNI powered by Cilium در AKS | بله | قابلیت Cilium بسته به Tier |
| Flannel تنها، kindnet در kind قدیمی | خیر؛ شیء پذیرفته و نادیده گرفته میشود | — |
راهحل: در هر Namespace برنامه، هر دو جهت Default deny باشد؛ DNS یکبار مجاز شود و هر workload سیاست Allow ورودی و خروجی داشته باشد. بعد از هر تغییر CNI تست سلامت اولیه (Smoke test) اجرا کنید. Firewall میزبان و ابر در دیوارههای آتش است.
گسترش سیاست CNI: Cilium و Calico، قواعد L7 و خروجی آگاه از DNS تکمیلی
به زبان ساده: API استاندارد NetworkPolicy به IP و Port محدود است. Cilium و Calico اشیای سیاست خود را برای HTTP path، نام DNS، Deny صریح و پیشفرض سراسری اضافه میکنند.
بدفهمی رایج: «قواعد L7 هزینه ندارد.» در Cilium این قواعد "will proxy traffic through a node-local" Envoy instance؛ یک Hop، CPU و وابستگی دسترسپذیری Proxy اضافه میشود. وقتی Envoy داخلی است: "Layer 7 traffic targeted by policies will therefore depend on the availability of the Cilium agent pod".
تعریف: در CiliumNetworkPolicy، "Layer 7 policy rules are embedded into Layer 4 rules". مسیر toPorts[].rules.http شامل method و path است؛ Path، "an extended POSIX regex matched against the path of a request". قواعد rules.dns با matchName/matchPattern، دادهٔ toFQDNs را هم فراهم میکنند: "The separate L3 toFQDNs egress rule allows connections to any IPs returned". Entity با نام kube-apiserver، "represents both deployments of the kube-apiserver: within the cluster and outside of the cluster". Calico، "provides a richer set of policy capabilities than Kubernetes including: policy ordering/priority, deny rules, and more flexible match rules" و Policy محلی و سراسری دارد. API استاندارد تا 1.37، "Anything TLS related" و "Targeting of services by name" را پشتیبانی نمیکند.
ingress-nginx forwards to orders-api: GET /orders/42 allowed, DELETE /orders/42 refused
1 CiliumNetworkPolicy orders-api-l7 selects orders-api, ingress from the ingress-nginx Pods on 8080 with http rules
2 Cilium redirects that port to the node-local Envoy
3 GET /orders/42 matches method GET, path /orders/.* -> forwarded
4 DELETE /orders/42 -> Envoy returns an HTTP 403 access denied; the app never sees it# Cilium extensions over the plain NetworkPolicy API (cilium.io/v2):
# 1. L7 HTTP rules: the ingress controller may call orders-api only with GET /orders/...
# (enforced by the node-local Envoy proxy Cilium inserts for L7 rules).
# 2. kube-apiserver as an entity instead of an IP for orders-api.
# 3. DNS-aware egress: DNS visibility plus toFQDNs for one external API.
apiVersion: cilium.io/v2
kind: CiliumNetworkPolicy
metadata:
name: orders-api-l7
namespace: shop
spec:
description: "ingress-nginx may only GET /orders/* on orders-api"
endpointSelector:
matchLabels:
app.kubernetes.io/name: orders-api
ingress:
- fromEndpoints:
- matchLabels:
"k8s:io.kubernetes.pod.namespace": ingress-nginx
app.kubernetes.io/name: ingress-nginx
toPorts:
- ports:
- port: "8080"
protocol: TCP
rules:
http:
- method: "GET"
path: "/orders/.*"
egress:
- toEntities:
- kube-apiserver
toPorts:
- ports:
- port: "443"
protocol: TCP
- port: "6443"
protocol: TCP
---
apiVersion: cilium.io/v2
kind: CiliumNetworkPolicy
metadata:
name: shop-web-payments-fqdn
namespace: shop
spec:
endpointSelector:
matchLabels:
app.kubernetes.io/name: shop-web
egress:
- toEndpoints:
- matchLabels:
"k8s:io.kubernetes.pod.namespace": kube-system
"k8s:k8s-app": kube-dns
toPorts:
- ports:
- port: "53"
protocol: ANY
rules:
dns:
- matchPattern: "*"
- toFQDNs:
- matchName: "api.stripe.com"
toPorts:
- ports:
- port: "443"
protocol: TCPسناریوهای واقعی:
- Laravel به Stripe میرود؛
toFQDNs: api.stripe.comجای فهرست CIDR دائماً متغیر را میگیرد. - GlobalNetworkPolicy در Calico برای Metadata که تیم برنامه نتواند دور بزند: در EKS با IRSA منع
169.254.169.254برای همهٔ Podها؛ در GKE اجازه فقط برای Workload Identity به169.254.169.252:988یا169.254.169.254:80در Dataplane V2 و منع برای بقیه. - ابتدا دیدپذیری: قاعدهٔ DNS با
matchPattern: "*"Lookupهای Namespace را ثبت میکند تا Allow list بنویسید. - Authorization در Service mesh مانند Istio و Linkerd جایگزین L7 بر پایهٔ Workload identity و mTLS است؛ mTLS و امنیت سرویس.
| نیاز | Kubernetes NetworkPolicy | Cilium | Calico |
|---|---|---|---|
| Deny صریح و ترتیب | خیر | Deny policy | بله، Order و Tier |
| سیاست سراسری | خیر | CiliumClusterwideNetworkPolicy | GlobalNetworkPolicy |
| HTTP method/path | خیر | بله با Envoy | یکپارچگی Istio یا Application layer policy |
| نام DNS | خیر | toFQDNs | قواعد Domain؛ Edition را بررسی کنید |
| API server بهعنوان همتا | فقط ipBlock | toEntities: [kube-apiserver] | قواعد Service/Host endpoint |
راهحل: ابتدا NetworkPolicy قابل حمل بنویسید؛ برای FQDN egress و چند قاعدهٔ مهم L7 از Kind اختصاصی CNI استفاده کنید، با آگاهی از وابستگی ایجادشده به همان CNI.
کنترل دسترسی Secret: RBAC و رمزنگاری در حالت سکون مهم
به زبان ساده: API server مقدار Secret را به هر هویتی که RBAC مجاز کند میدهد؛ etcd هم بدون تنظیم، آن را رمزنگارینشده ذخیره میکند. این دو تصمیم مستقلاند.
بدفهمی رایج: «Secret چون base64 است رمز شده.» base64 کدگذاری است. رمزنگاری در حالت سکون (At rest) با --encryption-provider-config و ترجیحاً KMS provider انجام میشود. جزئیات، انواع Secret و دام «List هم خواندن است» در پیکربندی، Secret و ذخیرهسازی است؛ این بخش مرور میکند.
تعریف: دربارهٔ RBAC برای Secret: "list and watch access also effectively allow for users to reveal the Secret contents"؛ ساخت workload نیز با Mount دسترسی میدهد. resourceNames، get را به نام محدود میکند؛ list محدودشده با نام نیاز به Field selector روی metadata.name دارد. برنامه معمولاً هیچ RBAC برای Secret نمیخواهد؛ kubelet با هویت خودش و Node authorizer، Secret را Mount میکند. Node authorizer فقط Secret ارجاعشده در Podهای واگذارشده به همان Node را اجازه میدهد و NodeRestriction تغییرهای مجاز kubelet را محدود میکند.
Who can read the Secret shop/orders-db?
1 RBAC: subjects with get on secrets (by name or all) or list/watch on secrets in shop, or cluster-wide
2 anyone who can create Pods in shop (mount it), or exec into a Pod that mounts it
3 the kubelet of a node running a Pod that references it (Node authorizer)
4 anyone with etcd or backup access, unless encryption at rest is on (then: KMS key holders)سناریوهای واقعی:
- External Secrets Operator در Namespace مقصد
create/updateروی Secret میخواهد؛ دیگران نباید آن را داشته باشند. - نقش پشتیبانی با
kubectl get secrets -Aتمام رمزهای Cluster را افشا میکند. - Snapshot از etcd روی لپتاپ کپی شده؛ بدون Encryption at rest همهٔ Secretها متن آشکارند.
- Vault agent یا Secrets Store CSI driver میتواند اصلاً شیء Secret نسازد.
| هویت (Principal) | دسترسی مناسب Secret |
|---|---|
| Pod برنامه | هیچکدام از راه RBAC؛ Mount با kubelet |
| Controller مثل ESO و cert-manager | نوشتن در Namespace مقصد |
| توسعهدهنده | هیچ در محیط عملیاتی |
| مسئول شیفت | edit در Namespace خودش، شامل Secret، با Audit |
| Break-glass تیم Platform | همه، با Audit و هشدار |
راهحل: Role برنامه و توسعهدهنده فعل Secret نداشته باشد. خواندن Secret را در Metadata ممیزی کنید و Encryption at rest با KMS داشته باشید؛ پیکربندی، Secret و ذخیرهسازی.
مقاومسازی API server و kubelet؛ CIS Kubernetes Benchmark و kube-bench مهم
به زبان ساده: چند پرچم تعیین میکنند اصلاً دروازههای بالا وجود دارند یا نه. CIS Kubernetes Benchmark آنها را فهرست و kube-bench روی Node بررسی میکند.
بدفهمی رایج: «پیشفرضها امناند.» بعضی پیشفرضهای خط فرمان چنین نیستند: --authorization-mode در kube-apiserver، "Defaults to AlwaysAllow if --authorization-config is not used"؛ --anonymous-auth و --profiling هر دو "Default: true". پرچم --authorization-mode در kubelet برابر "AlwaysAllow" و --read-only-port برابر ۱۰۲۵۵ است. kubeadm و سرویس مدیریتشده مقدار امن میگذارند؛ پیشفرض فایل KubeletConfiguration هم امن است: anonymous.enabled: false، webhook.enabled: true، mode: Webhook و readOnlyPort با "Default: 0 (disabled)". خطر دقیقاً Node دستی است که فقط با Flag و راهنمای قدیمی اجرا شده.
تعریف: --anonymous-auth درخواست ناشناس را فعال میکند؛ --authorization-mode=Node,RBAC ترتیب استاندارد است. "Enabling the AlwaysAllow mode bypasses authorization" و --authorization-mode=AlwaysAllow,RBAC، "has the same effect as --authorization-mode=AlwaysAllow". در احراز هویت (Authentication) Webhook برای kubelet، "the kubelet calls the TokenReview API on the configured API server to determine user information from bearer tokens"؛ X.509 با --client-ca-file تماس خود API server را پوشش میدهد و anonymous خاموش است. مجوز (Authorization) در حالت Webhook، "uses the SubjectAccessReview API". پرچمهای دیگر: --kubelet-certificate-authority برای بررسی گواهی سرویس kubelet، --encryption-provider-config، --audit-policy-file، --service-account-extend-token-expiration و --enable-admission-plugins=NodeRestriction. ابزار kube-bench، "checks whether Kubernetes is deployed securely by running the checks documented in the CIS Kubernetes Benchmark"؛ با Job و kubectl apply -f job.yaml اجرا میشود. روی EKS فقط بررسی Node ممکن است چون "it's not possible to schedule jobs onto the master node". نسخهٔ Benchmark عمومی 2.1.0 و نسخههای اختصاصی EKS 2.1.0، AKS 2.1.0 و GKE 2.0.0 در زمان نگارش هستند.
Hardening review of a self-managed kubeadm cluster
1 kubectl apply -f job.yaml (kube-bench as a Job; control-plane checks need it scheduled on a control-plane node)
2 read the [FAIL] and [WARN] lines: e.g. profiling still on, audit-log flags missing, kubelet read-only port open
3 apply apiserver/kube-apiserver-flags.yaml values; static Pod restarts by itself
4 nodes: KubeletConfiguration with anonymous off, Webhook authz, readOnlyPort 0
5 re-run kube-bench; store the report as the evidence for the audit# Excerpt of a kubeadm-style static Pod manifest for kube-apiserver
# (/etc/kubernetes/manifests/kube-apiserver.yaml), security flags only.
# Self-managed clusters only: on EKS, GKE and AKS the provider owns these.
apiVersion: v1
kind: Pod
metadata:
name: kube-apiserver
namespace: kube-system
spec:
containers:
- name: kube-apiserver
image: registry.k8s.io/kube-apiserver:v1.37.0
command:
- kube-apiserver
# Authorization: Node first (kubelets), then RBAC. Never AlwaysAllow,
# which is the default when neither this flag nor --authorization-config is set.
- --authorization-mode=Node,RBAC
# Authentication: OIDC + anonymous-only-on-health live in this file;
# it replaces --oidc-* and --anonymous-auth (default true).
- --authentication-config=/etc/kubernetes/authentication-config.yaml
- --client-ca-file=/etc/kubernetes/pki/ca.crt
# ServiceAccount tokens: who issues them and with which keys.
- --service-account-issuer=https://kubernetes.default.svc.cluster.local
- --service-account-key-file=/etc/kubernetes/pki/sa.pub
- --service-account-signing-key-file=/etc/kubernetes/pki/sa.key
# Default true: admission-injected tokens are silently extended to one
# year (with a warnafter claim) for old clients. Turn off once nothing
# reads the token only at start-up.
- --service-account-extend-token-expiration=false
# Admission: PSA defaults and exemptions live in this file.
- --admission-control-config-file=/etc/kubernetes/admission-configuration.yaml
- --enable-admission-plugins=NodeRestriction
# Talk to kubelets over verified TLS, as a client the kubelet can authorise.
- --kubelet-certificate-authority=/etc/kubernetes/pki/ca.crt
- --kubelet-client-certificate=/etc/kubernetes/pki/apiserver-kubelet-client.crt
- --kubelet-client-key=/etc/kubernetes/pki/apiserver-kubelet-client.key
# Secrets encrypted in etcd (see the Config, Secrets & Storage chapter).
- --encryption-provider-config=/etc/kubernetes/encryption-config.yaml
# Audit: no policy file = no audit events at all.
- --audit-policy-file=/etc/kubernetes/audit-policy.yaml
- --audit-log-path=/var/log/kubernetes/audit/audit.log
- --audit-log-maxage=30
- --audit-log-maxbackup=10
- --audit-log-maxsize=100
# Default true; the CIS Kubernetes Benchmark asks for false.
- --profiling=false# /var/lib/kubelet/config.yaml (KubeletConfiguration). The config-file
# defaults are already safe; the deprecated command-line FLAGS are not
# (--anonymous-auth=true, --authorization-mode=AlwaysAllow,
# --read-only-port=10255), so state the values explicitly and let
# kube-bench check them.
apiVersion: kubelet.config.k8s.io/v1beta1
kind: KubeletConfiguration
authentication:
anonymous:
enabled: false # 401 for unauthenticated calls to :10250
webhook:
enabled: true # bearer tokens checked with TokenReview
cacheTTL: 2m0s
x509:
clientCAFile: /etc/kubernetes/pki/ca.crt # the API server's client cert
authorization:
mode: Webhook # SubjectAccessReview against RBAC (nodes/proxy, nodes/log, ...)
webhook:
cacheAuthorizedTTL: 5m0s
cacheUnauthorizedTTL: 30s
readOnlyPort: 0 # no unauthenticated :10255
rotateCertificates: true
serverTLSBootstrap: trueسناریوهای واقعی:
- اسکن Port ۱۰۲۵۵ را روی Node ساختهشده با راهنمای قدیمی باز مییابد؛ فهرست Pod بدون Authentication در دسترس است.
- API server اینترنتی با Binding سفارشی برای
system:unauthenticatedبه هرکس پاسخ میدهد: "Review bindings for the system:unauthenticated group and remove them where possible". - ممیز شواهد رعایت CIS میخواهد؛ خروجی زمانبندیشدهٔ kube-bench یا اسکن CIS در Trivy Operator ارائه کنید.
- در EKS/GKE/AKS موارد Control plane بر عهدهٔ Provider است؛ Node و RBAC همچنان مسئولیت شماست.
| بررسی | مدیریت شخصی | مدیریتشده: EKS / GKE / AKS |
|---|---|---|
| Flagهای API server | شما | Provider |
| تنظیم kubelet | شما | شما؛ Imageهای Node عموماً درستاند |
| RBAC، PSA، NetworkPolicy، Audit policy | شما | شما |
| رمزنگاری etcd | شما | گزینهٔ Provider برای KMS |
| اسکن CIS | job.yaml در kube-bench | job-eks.yaml و مشابه؛ فقط Node |
راهحل: Flagها در کد ثابت باشند: تنظیم kubeadm یا Terraform برای سرویس مدیریتشده. kube-bench را روی Image جدید Node در CI و دورهای روی Cluster اجرا کنید.
چندمستأجری: مرز Namespace، Namespace سلسلهمراتبی و vCluster تکمیلی
به زبان ساده: چند تیم یا مشتری یک Cluster را شریکاند. Namespace واحد (Unit) تعیین حوزهٔ RBAC، PSA، NetworkPolicy و Quota است؛ پس مرز مستأجر محسوب میشود. اگر کافی نیست، به هر مستأجر Control plane خودش را بدهید.
بدفهمی رایج: «Namespace مستأجرها را جدا میکند.» فقط اشیای API را و فقط بهاندازهٔ سیاست تنظیمشده جدا میکند. مرجع میگوید: "boundaries within a namespace should be considered weak"؛ همچنین "the kubelet and (unless using virtual control planes) the API service are still shared". CRD، Webhook و اشیای سراسری بین همه مشترکاند.
تعریف: چندمستأجری (Multi-tenancy) با مرز Namespace یعنی Namespace هر مستأجر همراه RoleBinding، PSA label، Default-deny NetworkPolicy، ResourceQuota و LimitRange؛ برای مستأجر غیرقابل اعتماد Node pool جدا هم لازم است. Namespace سلسلهمراتبی (Hierarchical namespaces) با HNC اجازهٔ ساخت زیرNamespace و انتشار RBAC و Policy در درخت را میدهد: "you can create additional namespaces under your team's namespace, even if you don't have cluster-level permission to create namespaces". repo آن زیر kubernetes-retired آرشیو شده؛ الگو محسوبش کنید، نه وابستگی تازه. Control plane مجازی هر مستأجر (Virtual control plane per tenant)، "extends namespace-based multi-tenancy" و API server، Controller manager و Datastore اختصاصی میدهد. vCluster این مدل را پیاده میکند: "Each cluster is backed by a dedicated virtualized control plane" که "as a pod in a dedicated namespace" از Cluster میزبان، با Node مشترک یا خصوصی، اجرا میشود.
Onboarding tenant "payments" on a shared cluster
1 platform GitOps repo: Namespace payments with PSA restricted labels, quota, limit range
2 RoleBinding admin -> group oidc:payments-leads; view -> oidc:payments-devs
3 NetworkPolicy default deny + DNS (generated by a Kyverno GeneratingPolicy for every new namespace)
4 payments wants its own CRDs and webhooks -> not on the shared API server: give it a vCluster
5 regulated card data -> separate node pool or separate cluster (vCluster private nodes or a real cluster)سناریوهای واقعی:
- تیمهای داخلی با Namespace و سیاستهای فصل میتوانند یک Cluster داشته باشند.
- محیط Preview هر Pull request، Namespace یا vCluster ساخته و حذفشده توسط CI است.
- SaaS اجراکنندهٔ کد مشتری به Cluster جدا یا Virtual cluster روی Node خصوصی نیاز دارد؛ هرگز Namespace مشترک.
- تیم برای Operator خود cluster-admin میخواهد؛ Virtual cluster آن را میدهد بدون دسترسی به Cluster میزبان.
| مدل | جداسازی | هزینه | کاربرد |
|---|---|---|---|
| Namespace هر تیم | اشیای API؛ شبکه با NetworkPolicy | کمترین | تیم داخلی قابل اعتماد |
| درخت Namespace با الگوی HNC | همان، با واگذاری زیرNamespace | کم | سازمان بزرگ؛ Controller آرشیو شده |
| vCluster روی Node مشترک | API server، CRD و RBAC جدا | متوسط | تیم نیازمند اختیار شبیه cluster-admin |
| vCluster روی Node خصوصی | علاوه بر بالا، Compute و شبکه | بیشتر | مشتری یا مستأجر با الزامات نظارتی |
| Cluster هر مستأجر | همهچیز | بیشترین | جداسازی سخت و Compliance |
راهحل: مدل مستأجر را صریح و برای هر کلاس مستند کنید. بستهٔ Namespace را خودکار بسازید تا هیچ مستأجری بدون RBAC، PSA و NetworkPolicy ایجاد نشود.
سازوکار (Mechanics)
تصمیم مجوز چگونه گرفته میشود
با --authorization-mode=Node,RBAC، مجوزدهندهٔ Node یا Node authorizer فقط برای kubeletها، یعنی Userهای system:node:<name> در گروه system:nodes، تصمیم میگیرد و آنها را به اشیای مرتبط با Podهای خودشان محدود میکند. برای دیگران نظری ندارد و RBAC تصمیم میگیرد. RBAC ابتدا ClusterRoleBindingها و سپس RoleBindingهای Namespace درخواست را میگردد؛ برای Subject مطابق، تمام قواعد Role ارجاعشده را میسنجد و با اولین Allow متوقف میشود. آزمون قاعده چهار بررسی با AND است؛ از plugin/pkg/auth/authorizer/rbac/rbac.go و Evaluation helperهای Kubernetes v1.34.1 به بررسیکنندهٔ آفلاین فصل منتقل شده است:
package rbaccheck
// The RBAC rule matching of kube-apiserver, ported from Kubernetes v1.34.1:
// plugin/pkg/auth/authorizer/rbac/rbac.go (RuleAllows) and
// pkg/apis/rbac/v1/evaluation_helpers.go (the *Matches helpers).
// A rule allows a request only if verb, API group, resource (with
// subresource) and name all match; there is no code path that denies.
import (
"strings"
rbacv1 "k8s.io/api/rbac/v1"
)
// RuleAllows is rbac.go's RuleAllows over the evaluation helpers.
func RuleAllows(r Request, rule rbacv1.PolicyRule) bool {
if r.Path == "" {
combined := r.Resource
if r.Subresource != "" {
combined += "/" + r.Subresource
}
return verbMatches(rule, r.Verb) && apiGroupMatches(rule, r.APIGroup) &&
resourceMatches(rule, combined, r.Subresource) && resourceNameMatches(rule, r.Name)
}
return verbMatches(rule, r.Verb) && nonResourceURLMatches(rule, r.Path)
}
func verbMatches(rule rbacv1.PolicyRule, verb string) bool {
for _, v := range rule.Verbs {
if v == rbacv1.VerbAll || v == verb {
return true
}
}
return false
}
func apiGroupMatches(rule rbacv1.PolicyRule, group string) bool {
for _, g := range rule.APIGroups {
if g == rbacv1.APIGroupAll || g == group {
return true
}
}
return false
}
func resourceMatches(rule rbacv1.PolicyRule, combined, sub string) bool {
for _, res := range rule.Resources {
if res == rbacv1.ResourceAll || res == combined {
return true
}
// "*/scale" matches the scale subresource of every resource
if sub != "" && len(res) == len(sub)+2 && strings.HasPrefix(res, "*/") && strings.HasSuffix(res, sub) {
return true
}
}
return false
}
func resourceNameMatches(rule rbacv1.PolicyRule, name string) bool {
if len(rule.ResourceNames) == 0 {
return true // an empty list means every name
}
for _, n := range rule.ResourceNames {
if n == name {
return true
}
}
return false
}
func nonResourceURLMatches(rule rbacv1.PolicyRule, path string) bool {
for _, u := range rule.NonResourceURLs {
if u == rbacv1.NonResourceAll || u == path ||
(strings.HasSuffix(u, "*") && strings.HasPrefix(path, strings.TrimRight(u, "*"))) {
return true
}
}
return false
}سه نتیجه دارد: * در فیلد خودش همهچیز را میگیرد، یعنی ResourceAll، VerbAll و APIGroupAll؛ فهرست خالی resourceNames هر نام را مجاز میکند: "For resourceNames, an empty set means that everything is allowed"؛ و */scale زیرمنبع scale هر منبع را میگیرد، نه خود منبع را. هیچ شاخهای از کد Deny برنمیگرداند؛ این همان قاعدهٔ افزایشی بودن مجوزهاست.
Authorizer chain for: user system:node:worker-3 GET secret shop/orders-db
1 Node authorizer: is a Pod bound to worker-3 referencing secret orders-db? yes -> ALLOW (stop)
Authorizer chain for: user oidc:jane GET secret shop/orders-db
1 Node authorizer: not a node -> no opinion
2 RBAC: bindings for oidc:jane / oidc:shop-developers in shop -> view has no secrets -> no opinion
3 no more authorizers -> 403: User "oidc:jane@acme.example" cannot get resource "secrets" ... in the namespace "shop"توکن ServiceAccount، بایتبهبایت
Payload مستند توکن وابسته به Pod، از راهنمای "Configure Service Accounts for Pods":
{
"aud": ["https://kubernetes.default.svc"],
"exp": 1731613413,
"iat": 1700077413,
"iss": "https://kubernetes.default.svc",
"jti": "ea28ed49-2e11-4280-9ec5-bc3d1d84661a",
"kubernetes.io": {
"namespace": "kube-system",
"node": {"name": "127.0.0.1", "uid": "58456cb0-dd00-45ed-b797-5578fdceaced"},
"pod": {"name": "coredns-69cbfb9798-jv9gn", "uid": "778a530c-b3f4-47c0-9cd5-ab018fb64f33"},
"serviceaccount": {"name": "coredns", "uid": "a087d5a0-e1dd-43ec-93ac-f13d89cd13af"},
"warnafter": 1700081020
},
"nbf": 1700077413,
"sub": "system:serviceaccount:kube-system:coredns"
}حساب کنید: exp − iat برابر ۳۱٬۵۳۶٬۰۰۰ ثانیه، یعنی ۳۶۵ روز، ولی warnafter − iat برابر ۳٬۶۰۷ ثانیه است. مرجع مدیریت، درخواست Volume تزریقشده را با expirationSeconds: 3607 نشان میدهد؛ پرچم --service-account-extend-token-expiration با پیشفرض true دلیل یک سال را توضیح میدهد: "admission injected tokens would be extended up to 1 year to prevent unexpected failure during transition". توکن یک سال معتبر است، اما کلاینتی که بعد از warnafter همچنان همان توکن را میدهد فایل را دوباره نمیخواند. این تمدید برای حفاظت از همین کلاینت است و پیش از خاموشکردن Flag باید آن را اصلاح کرد. Volume ترکیبی (Projected volume) که خودتان تعریف میکنید، مانند orders-api-deployment.yaml، تزریق Admission نیست؛ پس ۶۰۰ ثانیهاش واقعی است. با false شدن Flag، انقضای پیشفرض هم واقعی میشود. jti شناسهٔ توکن در Audit است؛ kubernetes.io.pod.uid معنای Bound را میدهد، چون پس از حذف Pod سرور توکن را رد میکند؛ aud هم علت بیفایده بودن توکن vault برای API server است.
Admission بهترتیب اجرا
افزونههای پیشفرض v1.37 در راهنمای --enable-admission-plugins عبارتاند از: NamespaceLifecycle، LimitRanger، ServiceAccount، TaintNodesByCondition، PodSecurity، Priority، DefaultTolerationSeconds، DefaultStorageClass، StorageObjectInUseProtection، PodGroupProtection، PersistentVolumeClaimResize، RuntimeClass، CertificateApproval، CertificateSigning، ClusterTrustBundleAttest، CertificateSubjectRestriction، DefaultIngressClass، PodTopologyLabels، NodeDeclaredFeatureValidator، PodResizeValidator، MutatingAdmissionPolicy، MutatingAdmissionWebhook، ValidatingAdmissionPolicy، ValidatingAdmissionWebhook و ResourceQuota. افزونهٔ NodeRestriction در فهرست نیست و باید اضافه شود؛ kubeadm آن را اضافه میکند.
1 mutating phase: built-in mutators (ServiceAccount injects kube-api-access-*, DefaultTolerationSeconds,
LimitRanger defaults), then MutatingAdmissionPolicy, then MutatingAdmissionWebhook (reinvoked if IfNeeded)
2 object schema validation (types, required fields, immutable fields)
3 validating phase: PodSecurity, ValidatingAdmissionPolicy, ValidatingAdmissionWebhook,
ResourceQuota last in the plugin list (it increments usage)
4 any rejection anywhere -> whole request rejected; quota usage is reconciled laterفایلهای سیاست و تنظیم این فصل
| فایل | محتوا | اعمالکننده |
|---|---|---|
k8s/rbac/before-overgrant.yaml | ضدالگو برای Linter | هیچکس؛ آموزشی است |
k8s/rbac/orders-api-rbac.yaml | ServiceAccount، Role، RoleBinding | repo مربوط به GitOps برنامه |
k8s/rbac/people-and-ci.yaml | RoleBinding گروه، Deployer Role، ClusterRole تجمیعی | repo تیم Platform |
k8s/serviceaccount/orders-api-deployment.yaml | Deployment با Projected token | repo برنامه |
k8s/psa/namespaces.yaml | Namespace با PSA label | repo تیم Platform |
k8s/admission/*.yaml | VAP و Binding، Webhook configuration | repo تیم Platform |
k8s/kyverno/*.yaml، k8s/gatekeeper/*.yaml | سیاست Policy Engine | repo تیم Platform؛ یک Engine |
k8s/netpol/*.yaml | NetworkPolicy، CiliumNetworkPolicy | repo برنامه برای Allow، Platform برای Default deny |
apiserver/*.yaml | Authentication، Admission، Audit، تنظیم kubelet و Flagهای API server | آمادهسازی Node با kubeadm، Ansible، Terraform |
تنظیمها
| تنظیم | محل | پیشفرض | نکته |
|---|---|---|---|
--authorization-mode | kube-apiserver | AlwaysAllow در نبود --authorization-config | Node,RBAC بگذارید |
--anonymous-auth | Flag در kube-apiserver / kubelet | true | یا anonymous.conditions در AuthenticationConfiguration |
--authentication-config | kube-apiserver | تنظیم نشده | پایدار v1.34؛ ناسازگار با --oidc-* |
Authenticatorهای jwt | AuthenticationConfiguration | — | حداکثر 64 |
--service-account-extend-token-expiration | kube-apiserver | true | اعتبار توکن تزریقشده 1 سال |
--service-account-max-token-expiration | kube-apiserver | تنظیم نشده | سقف مدت TokenRequest |
expirationSeconds | Projected token | 3600 | حداقل 600 |
| تازهسازی توکن توسط kubelet | kubelet | 80 % از TTL یا 24 ساعت | قابل تنظیم نیست |
| بیاعتبارسازی توکن قدیمی | kube-controller-manager | 1 سال بیاستفاده | از v1.29 |
timeoutSeconds در Webhook | Webhook configuration | 10 | حداکثر 30 |
failurePolicy در Webhook | Webhook configuration | Fail | Gatekeeper با Ignore نصب میشود |
matchConditions | Webhook / VAP | ندارد | حداکثر 64 برای هر Webhook |
validationActions | VAP binding | الزامی | Deny، Warn، Audit؛ Deny+Warn ممنوع |
defaults در PSA | PodSecurityConfiguration | privileged / latest | برای هر Mode |
--audit-log-mode | kube-apiserver | blocking | پیشفرض Webhook برابر batch |
--audit-webhook-batch-max-size / -max-wait | kube-apiserver | 400 / 30 ثانیه | فقط حالت Batch |
authentication.anonymous.enabled در kubelet | KubeletConfiguration | false | پیشفرض Flag برابر true |
authorization.mode در kubelet | KubeletConfiguration | Webhook | پیشفرض Flag برابر AlwaysAllow |
readOnlyPort در kubelet | KubeletConfiguration | 0 | پیشفرض Flag برابر 10255 |
| Cache مربوط به Webhook در kubelet | KubeletConfiguration | authn: 2 دقیقه، authz: 5 دقیقه / 30 ثانیه | مجوز لغوشده ممکن است همینقدر باقی بماند |
پیام خطاهایی که واقعاً میبینید
| پیام | دروازه | معنا | راهحل |
|---|---|---|---|
error: You must be logged in to the server (Unauthorized) | Authentication | اعتبارنامهٔ منقضی یا نامعتبر، 401 | تازهسازی OIDC؛ بررسی Issuer/Audience |
pods is forbidden: User "system:serviceaccount:shop:orders-api" cannot list resource "pods" in API group "" in the namespace "shop" | Authorization | هیچ Binding مجاز نمیکند، 403 | محدودترین Rule؛ بررسی با auth can-i |
User "system:anonymous" cannot get path "/" | Authorization | درخواست بدون اعتبارنامه رسیده | اصلاح kubeconfig یا Mount توکن |
unable to load in-cluster configuration, KUBERNETES_SERVICE_HOST and KUBERNETES_SERVICE_PORT must be defined | client-go | خارج Pod؛ rest.ErrNotInCluster | محلی از kubeconfig؛ داخل Pod بررسی Env |
open /var/run/secrets/kubernetes.io/serviceaccount/token: no such file or directory | client-go | Automount خاموش و Projected token وجود ندارد | توکن Project کنید یا برنامه را بدون API نگه دارید |
Error from server (Forbidden): pods "x" is forbidden: violates PodSecurity "restricted:v1.37": ... | Admission در PSA | Pod سطح را نقض میکند | اصلاح securityContext؛ امنیت کانتینر |
Warning: would violate PodSecurity "restricted:latest": ... | PSA warn | با Enforce رد میشد | پیش از افزایش Enforce اصلاح کنید |
... is forbidden: ValidatingAdmissionPolicy '...' with binding '...' denied request: ... | VAP | عبارت CEL نادرست و عمل Deny | اصلاح شیء یا Policy |
Internal error occurred: failed calling webhook "...": ... context deadline exceeded | Admission webhook | Webhook کند یا قطع با failurePolicy: Fail | بازیابی Webhook؛ بررسی استثناها |
admission webhook "..." denied the request: ... | Admission webhook | رد صریح Kyverno یا Gatekeeper | پیام Policy را بخوانید |
خطای Validation روی roleRef هنگام Update کردن Binding | API validation | roleRef تغییرناپذیر است | حذف و ایجاد یا kubectl auth reconcile |
Forbidden هنگام ایجاد Role یا Binding، با فهرست مجوزهای نداشته | کنترل افزایش امتیاز RBAC | اعطای بیش از مجوز خود | گرفتن مجوز یا بهندرت escalate/bind |
dial tcp 10.96.0.10:53: i/o timeout پس از Default deny | NetworkPolicy | خروجی DNS مجاز نیست | افزودن DNS egress policy |
Go
orders-api سرویس Go فروشگاه این پایگاه دانش است. علاوه بر HTTP، هنگام شروع ConfigMapهای Feature flag با Label برابر acme.io/flags=true را از API میخواند. تمام نیاز RBAC همین است: List و Watch روی ConfigMap، فقط در Namespace خودش.
قبل
پیادهسازی اولیهٔ رایج: ServiceAccount با نام default، ClusterRoleBinding بهدلیل «Forbidden میداد»، List سراسری و Namespace ثابت در کد:
// Package before is the first version of orders-api's flag loader that many
// services start with. It compiles and works on day one; each comment says
// what is wrong. The fixed version is the lister package.
package before
import (
"context"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
)
// LoadFlags returns the names of the shop ConfigMaps.
func LoadFlags(ctx context.Context) ([]string, error) {
cfg, err := rest.InClusterConfig() // token of the "default" SA, bound to cluster-admin "to make it work"
if err != nil {
return nil, err
}
cs := kubernetes.NewForConfigOrDie(cfg) // panics instead of returning an error
// metav1.NamespaceAll: needs a ClusterRoleBinding, reads every team's ConfigMaps
list, err := cs.CoreV1().ConfigMaps(metav1.NamespaceAll).List(ctx, metav1.ListOptions{})
if err != nil {
return nil, err // a 403 looks like any other error
}
var names []string
for _, cm := range list.Items {
if cm.Namespace == "shop" { // hard-coded: breaks in shop-staging
names = append(names, cm.Name)
}
}
return names, nil
}اشیای RBAC معمول همراهش هم اینها هستند؛ هرکدام توضیح خطا دارد. rbaccheck هر نه یافته را گزارش میکند؛ آزمایشگاه:
# BEFORE: what many clusters look like after a year. Every object below is
# accepted by the API server; each comment says why it is still wrong.
# (rbaccheck in go/ flags every one of these; see the chapter's Lab.)
apiVersion: v1
kind: ServiceAccount
metadata:
name: ci-deployer
namespace: ci
---
# 1. The CI pipeline is cluster-admin: one leaked runner token = the whole
# cluster, every namespace, every Secret, every node via privileged Pods.
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: ci-deployer-cluster-admin
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: cluster-admin
subjects:
- kind: ServiceAccount
name: ci-deployer
namespace: ci
---
# 2. A "read-only" role that is not read-only: list/watch on secrets returns
# the data of every Secret; wildcards also cover resources added later.
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: support-readonly
rules:
- apiGroups: ["*"]
resources: ["*"]
verbs: ["get", "list", "watch"]
---
# 3. "Developers need to debug": exec into any Pod in shop, plus create pods,
# which lets them run as any ServiceAccount and mount any Secret there.
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: shop-debug
namespace: shop
rules:
- apiGroups: [""]
resources: ["pods", "pods/exec", "pods/log"]
verbs: ["get", "list", "create"]
---
# 4. A helper that manages RBAC for teams: escalate and bind defeat the
# API server's built-in escalation check; impersonate turns this
# identity into anyone, including members of system:masters.
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: team-onboarding
rules:
- apiGroups: ["rbac.authorization.k8s.io"]
resources: ["clusterroles", "clusterrolebindings"]
verbs: ["create", "update", "escalate", "bind"]
- apiGroups: [""]
resources: ["users", "groups", "serviceaccounts"]
verbs: ["impersonate"]
---
# 5. The default ServiceAccount of shop gets edit: every Pod that does not
# name a ServiceAccount (and automounts its token) inherits it.
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: default-sa-edit
namespace: shop
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: edit
subjects:
- kind: ServiceAccount
name: default
namespace: shopبعد
بستهٔ lister: استفاده از rest.InClusterConfig و kubernetes.NewForConfig با User agent و QPS کم؛ خواندن Namespace از فایل Projected؛ پرسش «اجازه دارم؟» با SelfSubjectAccessReview پیش از عمل؛ و Wrap کردن ErrForbidden برای تفکیک خطای RBAC از شبکه:
// Package lister is the Kubernetes-facing part of orders-api: it reads the
// ConfigMaps of its OWN namespace with the Pod's ServiceAccount token, and
// nothing else. The RBAC that makes this work (and nothing more) is
// k8s/rbac/orders-api-rbac.yaml.
package lister
import (
"context"
"errors"
"fmt"
"os"
"sort"
"strings"
authorizationv1 "k8s.io/api/authorization/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
)
// NamespaceFile is where the projected volume puts the Pod's namespace
// (the downwardAPI source of kube-api-access-*, or our own projection).
const NamespaceFile = "/var/run/secrets/kubernetes.io/serviceaccount/namespace"
// ErrForbidden is returned when RBAC denies the call. It wraps the API
// error, so apierrors.IsForbidden still works on it.
var ErrForbidden = errors.New("forbidden by RBAC")
// NamespaceFromFile reads the namespace the Pod runs in. Using it instead
// of a hard-coded "shop" keeps the code correct when the same image is
// deployed to shop-staging.
func NamespaceFromFile(path string) (string, error) {
b, err := os.ReadFile(path)
if err != nil {
return "", fmt.Errorf("read namespace: %w", err)
}
ns := strings.TrimSpace(string(b))
if ns == "" {
return "", fmt.Errorf("read namespace: %s is empty", path)
}
return ns, nil
}
// InClusterClient builds a clientset from the Pod's environment:
// KUBERNETES_SERVICE_HOST/PORT, the token file and ca.crt. rest.Config
// re-reads BearerTokenFile periodically, so the kubelet's token rotation
// needs no code here. Outside a Pod it returns rest.ErrNotInCluster.
func InClusterClient(userAgent string) (kubernetes.Interface, error) {
cfg, err := rest.InClusterConfig()
if err != nil {
return nil, err
}
cfg.UserAgent = userAgent // shows up in audit events as userAgent
cfg.QPS, cfg.Burst = 5, 10 // a config reader needs little; protect the API server
return kubernetes.NewForConfig(cfg)
}
// Lister lists ConfigMaps in exactly one namespace.
type Lister struct {
client kubernetes.Interface
namespace string
}
// New returns a Lister for namespace ns.
func New(client kubernetes.Interface, ns string) *Lister {
return &Lister{client: client, namespace: ns}
}
// CanList asks the API server "may I list configmaps here?" with a
// SelfSubjectAccessReview (what kubectl auth can-i does). Every
// authenticated identity may create one about itself. It returns the
// decision and the authorizer's reason.
func (l *Lister) CanList(ctx context.Context) (bool, string, error) {
review := &authorizationv1.SelfSubjectAccessReview{
Spec: authorizationv1.SelfSubjectAccessReviewSpec{
ResourceAttributes: &authorizationv1.ResourceAttributes{
Namespace: l.namespace,
Verb: "list",
Resource: "configmaps",
},
},
}
res, err := l.client.AuthorizationV1().SelfSubjectAccessReviews().Create(ctx, review, metav1.CreateOptions{})
if err != nil {
return false, "", fmt.Errorf("self subject access review: %w", err)
}
return res.Status.Allowed, res.Status.Reason, nil
}
// ConfigMapNames returns the sorted names of the ConfigMaps in the namespace,
// optionally filtered by a label selector such as "acme.io/flags=true".
func (l *Lister) ConfigMapNames(ctx context.Context, labelSelector string) ([]string, error) {
list, err := l.client.CoreV1().ConfigMaps(l.namespace).List(ctx, metav1.ListOptions{LabelSelector: labelSelector})
if apierrors.IsForbidden(err) {
return nil, fmt.Errorf("%w: list configmaps in %q: %w", ErrForbidden, l.namespace, err)
}
if err != nil {
return nil, fmt.Errorf("list configmaps in %q: %w", l.namespace, err)
}
names := make([]string, 0, len(list.Items))
for _, cm := range list.Items {
names = append(names, cm.Name)
}
sort.Strings(names)
return names, nil
}تستها از Fake clientset در client-go استفاده میکنند. این Client، RBAC اجرا نمیکند؛ بنابراین آنچه کد درخواست میکند، یعنی فقط Namespace خودش و ویژگیهای درست SelfSubjectAccessReview، بررسی میشود. رفتار ۴۰۳ با PrependReactor و apierrors.NewForbidden، و خطای rest.ErrNotInCluster خارج Pod نیز تست میشوند:
package lister
import (
"context"
"errors"
"os"
"path/filepath"
"reflect"
"testing"
authorizationv1 "k8s.io/api/authorization/v1"
corev1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/client-go/kubernetes/fake"
"k8s.io/client-go/rest"
k8stesting "k8s.io/client-go/testing"
)
func cm(ns, name string, labels map[string]string) *corev1.ConfigMap {
return &corev1.ConfigMap{ObjectMeta: metav1.ObjectMeta{Namespace: ns, Name: name, Labels: labels}}
}
// The fake clientset does NOT run RBAC; this test only shows that the code
// asks for its own namespace and never for another one.
func TestConfigMapNamesOnlyOwnNamespace(t *testing.T) {
client := fake.NewClientset(
cm("shop", "orders-flags", map[string]string{"acme.io/flags": "true"}),
cm("shop", "kube-root-ca.crt", nil),
cm("payments", "payments-flags", map[string]string{"acme.io/flags": "true"}),
)
l := New(client, "shop")
got, err := l.ConfigMapNames(context.Background(), "")
if err != nil {
t.Fatal(err)
}
if want := []string{"kube-root-ca.crt", "orders-flags"}; !reflect.DeepEqual(got, want) {
t.Fatalf("names = %v, want %v", got, want)
}
got, err = l.ConfigMapNames(context.Background(), "acme.io/flags=true")
if err != nil {
t.Fatal(err)
}
if want := []string{"orders-flags"}; !reflect.DeepEqual(got, want) {
t.Fatalf("filtered names = %v, want %v", got, want)
}
for _, a := range client.Actions() {
if a.GetNamespace() != "shop" {
t.Fatalf("request outside own namespace: %s %s in %q", a.GetVerb(), a.GetResource().Resource, a.GetNamespace())
}
}
}
// A 403 from the API server (what RBAC returns) becomes ErrForbidden and
// still satisfies apierrors.IsForbidden.
func TestConfigMapNamesForbidden(t *testing.T) {
client := fake.NewClientset()
client.PrependReactor("list", "configmaps", func(k8stesting.Action) (bool, runtime.Object, error) {
return true, nil, apierrors.NewForbidden(schema.GroupResource{Resource: "configmaps"}, "",
errors.New(`User "system:serviceaccount:shop:orders-api" cannot list resource "configmaps" in API group "" in the namespace "payments"`))
})
_, err := New(client, "payments").ConfigMapNames(context.Background(), "")
if !errors.Is(err, ErrForbidden) {
t.Fatalf("err = %v, want ErrForbidden", err)
}
if !apierrors.IsForbidden(err) {
t.Fatalf("apierrors.IsForbidden(%v) = false", err)
}
}
func TestCanList(t *testing.T) {
for _, tc := range []struct {
name string
allowed bool
reason string
}{
{"allowed", true, `RBAC: allowed by RoleBinding "orders-api-config-reader/shop"`},
{"denied", false, ""},
} {
t.Run(tc.name, func(t *testing.T) {
client := fake.NewClientset()
var seen *authorizationv1.SelfSubjectAccessReview
client.PrependReactor("create", "selfsubjectaccessreviews", func(a k8stesting.Action) (bool, runtime.Object, error) {
seen = a.(k8stesting.CreateAction).GetObject().(*authorizationv1.SelfSubjectAccessReview).DeepCopy()
seen.Status = authorizationv1.SubjectAccessReviewStatus{Allowed: tc.allowed, Reason: tc.reason}
return true, seen, nil
})
ok, reason, err := New(client, "shop").CanList(context.Background())
if err != nil {
t.Fatal(err)
}
if ok != tc.allowed || reason != tc.reason {
t.Fatalf("CanList = %v %q, want %v %q", ok, reason, tc.allowed, tc.reason)
}
ra := seen.Spec.ResourceAttributes
if ra.Namespace != "shop" || ra.Verb != "list" || ra.Resource != "configmaps" {
t.Fatalf("review asked for %+v", *ra)
}
})
}
}
func TestNamespaceFromFile(t *testing.T) {
dir := t.TempDir()
p := filepath.Join(dir, "namespace")
if err := os.WriteFile(p, []byte("shop\n"), 0o600); err != nil {
t.Fatal(err)
}
ns, err := NamespaceFromFile(p)
if err != nil || ns != "shop" {
t.Fatalf("NamespaceFromFile = %q, %v", ns, err)
}
empty := filepath.Join(dir, "empty")
if err := os.WriteFile(empty, nil, 0o600); err != nil {
t.Fatal(err)
}
if _, err := NamespaceFromFile(empty); err == nil {
t.Fatal("empty file: want error")
}
if _, err := NamespaceFromFile(filepath.Join(dir, "missing")); err == nil {
t.Fatal("missing file: want error")
}
}
// Outside a Pod (no KUBERNETES_SERVICE_HOST/PORT) rest.InClusterConfig fails
// with rest.ErrNotInCluster before it touches the token file.
func TestInClusterClientOutsideCluster(t *testing.T) {
t.Setenv("KUBERNETES_SERVICE_HOST", "")
t.Setenv("KUBERNETES_SERVICE_PORT", "")
_, err := InClusterClient("orders-api/test")
if !errors.Is(err, rest.ErrNotInCluster) {
t.Fatalf("err = %v, want rest.ErrNotInCluster", err)
}
}فرمان داخل Pod:
// config-lister is the in-cluster entry point of orders-api's config
// reader: check the permission once, list the flag ConfigMaps, exit
// non-zero with a clear message if RBAC or the environment is wrong.
// Run it in a Pod whose ServiceAccount is bound by k8s/rbac/orders-api-rbac.yaml.
package main
import (
"context"
"errors"
"fmt"
"log/slog"
"os"
"time"
"academy/kubernetes-security-rbac/lister"
"k8s.io/client-go/rest"
)
func main() {
if err := run(); err != nil {
slog.Error("config-lister failed", "err", err)
os.Exit(1)
}
}
func run() error {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
client, err := lister.InClusterClient("orders-api/config-lister")
if errors.Is(err, rest.ErrNotInCluster) {
return fmt.Errorf("not running in a Pod (or automountServiceAccountToken is false and no token is projected): %w", err)
}
if err != nil {
return err
}
ns, err := lister.NamespaceFromFile(lister.NamespaceFile)
if err != nil {
return err
}
l := lister.New(client, ns)
ok, reason, err := l.CanList(ctx)
if err != nil {
return err
}
slog.Info("access review", "namespace", ns, "verb", "list", "resource", "configmaps", "allowed", ok, "reason", reason)
if !ok {
return fmt.Errorf("ServiceAccount may not list configmaps in %q: check the RoleBinding", ns)
}
names, err := l.ConfigMapNames(ctx, "acme.io/flags=true")
if err != nil {
return err
}
for _, n := range names {
fmt.Println(n)
}
return nil
}module academy/kubernetes-security-rbac
go 1.24.0
require (
k8s.io/api v0.34.1
k8s.io/apimachinery v0.34.1
k8s.io/client-go v0.34.1
sigs.k8s.io/yaml v1.6.0
)
require (
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/emicklei/go-restful/v3 v3.12.2 // indirect
github.com/fxamacker/cbor/v2 v2.9.0 // indirect
github.com/go-logr/logr v1.4.2 // indirect
github.com/go-openapi/jsonpointer v0.21.0 // indirect
github.com/go-openapi/jsonreference v0.20.2 // indirect
github.com/go-openapi/swag v0.23.0 // indirect
github.com/gogo/protobuf v1.3.2 // indirect
github.com/google/gnostic-models v0.7.0 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/josharian/intern v1.0.0 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/mailru/easyjson v0.7.7 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/x448/float16 v0.8.4 // indirect
go.yaml.in/yaml/v2 v2.4.2 // indirect
go.yaml.in/yaml/v3 v3.0.4 // indirect
golang.org/x/net v0.38.0 // indirect
golang.org/x/oauth2 v0.27.0 // indirect
golang.org/x/sys v0.31.0 // indirect
golang.org/x/term v0.30.0 // indirect
golang.org/x/text v0.23.0 // indirect
golang.org/x/time v0.9.0 // indirect
google.golang.org/protobuf v1.36.5 // indirect
gopkg.in/evanphx/json-patch.v4 v4.12.0 // indirect
gopkg.in/inf.v0 v0.9.1 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
k8s.io/klog/v2 v2.130.1 // indirect
k8s.io/kube-openapi v0.0.0-20250710124328-f3f2b991d03b // indirect
k8s.io/utils v0.0.0-20250604170112-4c0f3b243397 // indirect
sigs.k8s.io/json v0.0.0-20241014173422-cfa47c3a1cc8 // indirect
sigs.k8s.io/randfill v1.0.0 // indirect
sigs.k8s.io/structured-merge-diff/v6 v6.3.0 // indirect
)همین منطق بهشکل Job یکباره در آزمایشگاه:
# The one-shot form of the same logic (go/cmd/config-lister): check the
# permission, list the flag ConfigMaps, exit 0, or exit 1 with a message that
# names the missing RoleBinding. Same ServiceAccount, token projection and
# label as the orders-api Deployment, so orders-api-netpol.yaml applies to it.
apiVersion: batch/v1
kind: Job
metadata:
name: orders-api-config-check
namespace: shop
spec:
backoffLimit: 0 # a 403 will not fix itself by retrying
ttlSecondsAfterFinished: 3600
template:
metadata:
labels:
app.kubernetes.io/name: orders-api
spec:
restartPolicy: Never
serviceAccountName: orders-api
automountServiceAccountToken: false
securityContext:
runAsNonRoot: true
runAsUser: 65532
seccompProfile:
type: RuntimeDefault
containers:
- name: config-lister
# built from go/Dockerfile (ENTRYPOINT /config-lister); the lab replaces the
# placeholder digest with the one the push printed
image: ghcr.io/acme/config-lister:1.4.2@sha256:0000000000000000000000000000000000000000000000000000000000000000
resources:
requests: {cpu: 10m, memory: 16Mi}
limits: {memory: 32Mi}
securityContext:
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
capabilities:
drop: ["ALL"]
volumeMounts:
- name: kube-api-token
mountPath: /var/run/secrets/kubernetes.io/serviceaccount
readOnly: true
volumes:
- name: kube-api-token
projected:
sources:
- serviceAccountToken:
path: token
expirationSeconds: 600
- configMap:
name: kube-root-ca.crt
items:
- key: ca.crt
path: ca.crt
- downwardAPI:
items:
- path: namespace
fieldRef:
fieldPath: metadata.namespaceDeployment خود سرور، با توکن Projected ششصدثانیهای در مسیر مورد استفادهٔ rest.InClusterConfig و توکن دوم برای Vault:
# orders-api with an explicit, short-lived, audience-bound token.
# The ServiceAccount has automountServiceAccountToken: false; instead of the
# default kube-api-access-* volume we project the same three files ourselves
# at the path rest.InClusterConfig() reads, with a 10-minute lifetime, plus a
# second token whose audience is Vault (useless against the API server).
apiVersion: apps/v1
kind: Deployment
metadata:
name: orders-api
namespace: shop
labels:
app.kubernetes.io/name: orders-api
spec:
replicas: 2
selector:
matchLabels:
app.kubernetes.io/name: orders-api
template:
metadata:
labels:
app.kubernetes.io/name: orders-api
spec:
serviceAccountName: orders-api
automountServiceAccountToken: false # we mount our own projected volume below
securityContext: # restricted PSS level (see container-security)
runAsNonRoot: true
runAsUser: 65532
seccompProfile:
type: RuntimeDefault
containers:
- name: orders-api
image: ghcr.io/acme/orders-api:1.4.2@sha256:0000000000000000000000000000000000000000000000000000000000000000
# the HTTP server; it reads its flag ConfigMaps at start-up with the
# lister package (cmd/config-lister is the same logic as a one-shot Job)
ports:
- name: http
containerPort: 8080
resources:
requests: {cpu: 100m, memory: 64Mi}
limits: {memory: 128Mi}
securityContext:
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
capabilities:
drop: ["ALL"]
volumeMounts:
- name: kube-api-token
mountPath: /var/run/secrets/kubernetes.io/serviceaccount
readOnly: true
- name: vault-token
mountPath: /var/run/secrets/tokens
readOnly: true
volumes:
- name: kube-api-token
projected:
sources:
- serviceAccountToken:
path: token
expirationSeconds: 600 # minimum allowed; kubelet refreshes at 80% of TTL
- configMap:
name: kube-root-ca.crt
items:
- key: ca.crt
path: ca.crt
- downwardAPI:
items:
- path: namespace
fieldRef:
fieldPath: metadata.namespace
- name: vault-token
projected:
sources:
- serviceAccountToken:
path: vault-token
audience: vault # Vault's Kubernetes auth checks this "aud"
expirationSeconds: 3600NetworkPolicy شامل Egress مورد نیاز API است. در GKE با Workload Identity، workload دارای دسترسی ابر به قاعدهٔ Metadata server هم نیاز دارد؛ در EKS با IRSA نباید آن را بگیرد:
# The Go service orders-api: ingress only from the ingress-nginx controller,
# egress to the Kubernetes API server (it lists ConfigMaps) on 443/6443.
# The API server is not a Pod you can select. NetworkPolicy can only name it
# by IP (ipBlock); what IP the plugin sees after the Service VIP is rewritten
# is implementation-defined, so check with your CNI. Cilium has a dedicated
# kube-apiserver entity (see cilium-l7.yaml).
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: orders-api
namespace: shop
spec:
podSelector:
matchLabels:
app.kubernetes.io/name: orders-api
policyTypes: [Ingress, Egress]
ingress:
- from:
- namespaceSelector:
matchLabels:
kubernetes.io/metadata.name: ingress-nginx
podSelector:
matchLabels:
app.kubernetes.io/name: ingress-nginx
ports:
- {protocol: TCP, port: 8080}
egress:
- to:
- ipBlock:
cidr: 10.0.0.1/32 # control-plane endpoint (kubectl get endpointslices -n default kubernetes)
ports:
- {protocol: TCP, port: 443}
- {protocol: TCP, port: 6443}# VARIANT for GKE only, for the workloads that use GKE Workload Identity
# (orders-api, the queue worker if it writes to Cloud Storage). Under
# default deny these Pods must still reach the GKE metadata server, which is
# where Workload Identity hands out credentials. From the GKE docs: "Allow
# egress to 169.254.169.252/32 on port 988. For clusters running GKE Dataplane
# V2, ensure that you allowed egress to 169.254.169.254/32 on port 80."
# Keep only the rule for your dataplane. Workloads without cloud access
# (shop-web) never get this policy. On EKS with IRSA do not apply it: there the
# metadata address serves the NODE's role and stays denied.
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: gke-metadata-egress
namespace: shop
spec:
podSelector:
matchExpressions:
- key: app.kubernetes.io/name
operator: In
values: [orders-api, shop-queue]
policyTypes: [Egress]
egress:
- to:
- ipBlock:
cidr: 169.254.169.252/32 # GKE metadata server (legacy dataplane)
ports:
- {protocol: TCP, port: 988}
- to:
- ipBlock:
cidr: 169.254.169.254/32 # GKE Dataplane V2
ports:
- {protocol: TCP, port: 80}تصویر (Image) برای Job مربوط به config-lister از Dockerfile خود فصل ساخته میشود:
# syntax=docker/dockerfile:1
# Image for the config-lister Job (k8s/serviceaccount/config-lister-job.yaml).
# Build context: this go/ directory. Same pattern as the Images & Dockerfiles
# chapter: cached module download, static binary, distroless, numeric non-root.
FROM --platform=$BUILDPLATFORM golang:1.27-trixie AS build
WORKDIR /src
COPY go.mod go.sum ./
RUN --mount=type=cache,target=/go/pkg/mod go mod download
COPY . .
ARG TARGETOS TARGETARCH
RUN --mount=type=cache,target=/go/pkg/mod --mount=type=cache,target=/root/.cache/go-build \
CGO_ENABLED=0 GOOS=$TARGETOS GOARCH=$TARGETARCH \
go build -trimpath -ldflags "-s -w" -o /out/config-lister ./cmd/config-lister
FROM gcr.io/distroless/static-debian13:nonroot
COPY --from=build /out/config-lister /config-lister
USER 65532:65532
ENTRYPOINT ["/config-lister"]بررسیکنندهٔ آفلاین RBAC برای Lab و CI، همان تطبیق Rule در API server را روی YAML در Git اجرا میکند و Linter برای راههای افزایش امتیاز دارد:
// Package rbaccheck answers "can this subject do this?" for RBAC objects
// read from YAML files, offline, the way the API server's RBAC authorizer
// would. The matching rules are ported from Kubernetes v1.34
// (plugin/pkg/auth/authorizer/rbac/rbac.go RuleAllows and
// pkg/apis/rbac/v1/evaluation_helpers.go). It also lints the objects for the
// over-grants the RBAC good-practices page lists.
//
// It only knows the objects in the files: built-in ClusterRoles such as
// view, edit or cluster-admin have no rules here, so a binding to them
// grants nothing in Allowed (Lint still flags the risky ones by name).
package rbaccheck
import (
"bytes"
"fmt"
"os"
rbacv1 "k8s.io/api/rbac/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"sigs.k8s.io/yaml"
)
// Request is the subset of authorizer attributes RBAC looks at.
type Request struct {
User string
Groups []string
Verb string // get, list, watch, create, update, patch, delete, deletecollection, ...
APIGroup string // "" for the core group
Resource string // configmaps, pods, ...
Subresource string // exec, log, token, ...
Name string // object name, "" for collections
Namespace string // "" for cluster-scoped requests
Path string // set instead of Resource for non-resource URLs (/healthz)
}
// ServiceAccount returns the username and groups the API server gives a
// ServiceAccount token: system:serviceaccount:<ns>:<name> and the groups
// system:serviceaccounts, system:serviceaccounts:<ns>, system:authenticated.
func ServiceAccount(ns, name string) (string, []string) {
return "system:serviceaccount:" + ns + ":" + name,
[]string{"system:serviceaccounts", "system:serviceaccounts:" + ns, "system:authenticated"}
}
// Store holds the RBAC objects found in some YAML files.
type Store struct {
Roles map[string]rbacv1.Role // key "namespace/name"
ClusterRoles map[string]rbacv1.ClusterRole
RoleBindings []rbacv1.RoleBinding
ClusterRoleBindings []rbacv1.ClusterRoleBinding
}
// SplitDocuments splits a multi-document YAML stream on "---" lines.
func SplitDocuments(data []byte) [][]byte {
var docs [][]byte
for _, d := range bytes.Split(append([]byte("\n"), data...), []byte("\n---")) {
if len(bytes.TrimSpace(stripComments(d))) > 0 {
docs = append(docs, d)
}
}
return docs
}
func stripComments(d []byte) []byte {
var out [][]byte
for _, l := range bytes.Split(d, []byte("\n")) {
if t := bytes.TrimSpace(l); len(t) > 0 && t[0] != '#' {
out = append(out, l)
}
}
return bytes.Join(out, []byte("\n"))
}
// Load reads the files and keeps the four RBAC kinds, decoded strictly
// (an unknown or misspelled field is an error). Other kinds are skipped.
func Load(paths ...string) (*Store, error) {
s := &Store{Roles: map[string]rbacv1.Role{}, ClusterRoles: map[string]rbacv1.ClusterRole{}}
for _, p := range paths {
data, err := os.ReadFile(p)
if err != nil {
return nil, err
}
for i, doc := range SplitDocuments(data) {
var meta struct {
Kind string `json:"kind"`
}
if err := yaml.Unmarshal(doc, &meta); err != nil {
return nil, fmt.Errorf("%s doc %d: %w", p, i, err)
}
var derr error
switch meta.Kind {
case "Role":
var r rbacv1.Role
if derr = yaml.UnmarshalStrict(doc, &r); derr == nil {
s.Roles[r.Namespace+"/"+r.Name] = r
}
case "ClusterRole":
var r rbacv1.ClusterRole
if derr = yaml.UnmarshalStrict(doc, &r); derr == nil {
s.ClusterRoles[r.Name] = r
}
case "RoleBinding":
var b rbacv1.RoleBinding
if derr = yaml.UnmarshalStrict(doc, &b); derr == nil {
s.RoleBindings = append(s.RoleBindings, b)
}
case "ClusterRoleBinding":
var b rbacv1.ClusterRoleBinding
if derr = yaml.UnmarshalStrict(doc, &b); derr == nil {
s.ClusterRoleBindings = append(s.ClusterRoleBindings, b)
}
}
if derr != nil {
return nil, fmt.Errorf("%s doc %d (%s): %w", p, i, meta.Kind, derr)
}
}
}
return s, nil
}
// clusterRoleRules returns a ClusterRole's effective rules. For an aggregated
// ClusterRole the controller manager OVERWRITES the rules field with the
// union of the rules of every ClusterRole its aggregationRule selects
// ("The control plane overwrites any values that you manually specify in the
// rules field of an aggregate ClusterRole"), so manual rules are ignored here
// too. Selectors use the apimachinery label-selector semantics
// (matchLabels and matchExpressions).
func (s *Store) clusterRoleRules(name string) []rbacv1.PolicyRule {
cr, ok := s.ClusterRoles[name]
if !ok {
return nil
}
if cr.AggregationRule == nil {
return append([]rbacv1.PolicyRule(nil), cr.Rules...)
}
var rules []rbacv1.PolicyRule
for i := range cr.AggregationRule.ClusterRoleSelectors {
sel, err := metav1.LabelSelectorAsSelector(&cr.AggregationRule.ClusterRoleSelectors[i])
if err != nil {
continue // an invalid selector selects nothing
}
for _, other := range s.ClusterRoles {
if other.Name != name && sel.Matches(labels.Set(other.Labels)) {
rules = append(rules, other.Rules...)
}
}
}
return rules
}
func subjectMatches(sub rbacv1.Subject, bindingNS, user string, groups []string) bool {
switch sub.Kind {
case rbacv1.UserKind:
return sub.Name == user
case rbacv1.GroupKind:
for _, g := range groups {
if g == sub.Name {
return true
}
}
case rbacv1.ServiceAccountKind:
ns := sub.Namespace
if ns == "" {
ns = bindingNS
}
return user == "system:serviceaccount:"+ns+":"+sub.Name
}
return false
}
// Allowed reports whether any binding grants the request, and which one.
// RBAC is purely additive: there is no deny rule, so the first allow wins
// and "no rule matched" means denied.
func (s *Store) Allowed(r Request) (bool, string) {
for _, b := range s.ClusterRoleBindings {
for _, sub := range b.Subjects {
if subjectMatches(sub, "", r.User, r.Groups) {
for _, rule := range s.clusterRoleRules(b.RoleRef.Name) {
if RuleAllows(r, rule) {
return true, "ClusterRoleBinding " + b.Name
}
}
}
}
}
if r.Namespace == "" {
return false, "no rule matched"
}
for _, b := range s.RoleBindings {
if b.Namespace != r.Namespace {
continue // a RoleBinding only ever grants inside its own namespace
}
for _, sub := range b.Subjects {
if !subjectMatches(sub, b.Namespace, r.User, r.Groups) {
continue
}
var rules []rbacv1.PolicyRule
if b.RoleRef.Kind == "Role" {
rules = s.Roles[b.Namespace+"/"+b.RoleRef.Name].Rules
} else {
rules = s.clusterRoleRules(b.RoleRef.Name)
}
for _, rule := range rules {
if RuleAllows(r, rule) {
return true, "RoleBinding " + b.Namespace + "/" + b.Name
}
}
}
}
return false, "no rule matched"
}package rbaccheck
import (
"fmt"
"sort"
rbacv1 "k8s.io/api/rbac/v1"
)
// Severity of a lint finding.
type Severity string
const (
High Severity = "HIGH" // grants that amount to cluster or namespace takeover
Note Severity = "NOTE" // intended but worth knowing (workload creation)
)
// Finding is one lint result.
type Finding struct {
Severity Severity
Object string
Message string
}
func (f Finding) String() string { return fmt.Sprintf("%-4s %s: %s", f.Severity, f.Object, f.Message) }
func has(list []string, v string) bool {
for _, x := range list {
if x == v {
return true
}
}
return false
}
func lintRules(obj string, rules []rbacv1.PolicyRule) []Finding {
var out []Finding
add := func(s Severity, format string, a ...any) {
out = append(out, Finding{s, obj, fmt.Sprintf(format, a...)})
}
for _, r := range rules {
if has(r.Verbs, "*") || has(r.Resources, "*") || has(r.APIGroups, "*") {
add(High, "wildcard in verbs/resources/apiGroups also covers resources added later")
}
for _, v := range []string{"escalate", "bind", "impersonate"} {
if has(r.Verbs, v) {
add(High, "verb %q bypasses RBAC's privilege-escalation checks", v)
}
}
readsAll := has(r.Resources, "*") || has(r.Resources, "secrets")
if readsAll && (has(r.Verbs, "list") || has(r.Verbs, "watch") || has(r.Verbs, "*")) {
add(High, "list/watch on secrets returns the data of every Secret")
}
if has(r.Resources, "secrets") && has(r.Verbs, "get") && len(r.ResourceNames) == 0 {
add(High, "get on secrets without resourceNames reads any Secret by name")
}
for _, sub := range []string{"pods/exec", "pods/attach", "nodes/proxy", "serviceaccounts/token"} {
if has(r.Resources, sub) {
add(High, "%s gives code execution or credentials beyond this role", sub)
}
}
if has(r.Resources, "pods") && has(r.Verbs, "create") {
add(High, "create pods = run as any ServiceAccount and mount any Secret in the namespace")
}
for _, w := range []string{"deployments", "statefulsets", "daemonsets", "jobs", "cronjobs"} {
if has(r.Resources, w) && has(r.Verbs, "create") {
add(Note, "create %s implies running Pods as any ServiceAccount in the namespace", w)
}
}
}
return out
}
func lintSubjects(obj, roleName string, subjects []rbacv1.Subject) []Finding {
var out []Finding
if roleName == "cluster-admin" {
out = append(out, Finding{High, obj, "binds cluster-admin"})
}
for _, s := range subjects {
if s.Kind == rbacv1.ServiceAccountKind && s.Name == "default" {
out = append(out, Finding{High, obj, "grants to the default ServiceAccount, inherited by every Pod that names none"})
}
if s.Kind == rbacv1.GroupKind && (s.Name == "system:unauthenticated" || s.Name == "system:authenticated" || s.Name == "system:serviceaccounts") {
out = append(out, Finding{High, obj, "grants to the broad group " + s.Name})
}
if s.Kind == rbacv1.UserKind && s.Name == "system:anonymous" {
out = append(out, Finding{High, obj, "grants to system:anonymous"})
}
}
return out
}
// Lint returns findings sorted by object name.
func Lint(s *Store) []Finding {
var out []Finding
for k, r := range s.Roles {
out = append(out, lintRules("Role "+k, r.Rules)...)
}
for k, r := range s.ClusterRoles {
out = append(out, lintRules("ClusterRole "+k, r.Rules)...)
}
for _, b := range s.RoleBindings {
out = append(out, lintSubjects("RoleBinding "+b.Namespace+"/"+b.Name, b.RoleRef.Name, b.Subjects)...)
}
for _, b := range s.ClusterRoleBindings {
out = append(out, lintSubjects("ClusterRoleBinding "+b.Name, b.RoleRef.Name, b.Subjects)...)
}
sort.SliceStable(out, func(i, j int) bool {
if out[i].Object != out[j].Object {
return out[i].Object < out[j].Object
}
return out[i].Message < out[j].Message
})
return out
}
// HighCount counts HIGH findings.
func HighCount(fs []Finding) int {
n := 0
for _, f := range fs {
if f.Severity == High {
n++
}
}
return n
}package rbaccheck
import (
"path/filepath"
"strings"
"testing"
rbacv1 "k8s.io/api/rbac/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
const rbacDir = "../../k8s/rbac"
func load(t *testing.T, files ...string) *Store {
t.Helper()
var paths []string
for _, f := range files {
paths = append(paths, filepath.Join(rbacDir, f))
}
s, err := Load(paths...)
if err != nil {
t.Fatal(err)
}
return s
}
// The offline equivalent of
//
// kubectl auth can-i <verb> <resource> -n <ns> --as=system:serviceaccount:shop:orders-api
func TestOrdersAPIServiceAccount(t *testing.T) {
s := load(t, "orders-api-rbac.yaml", "people-and-ci.yaml")
user, groups := ServiceAccount("shop", "orders-api")
for _, tc := range []struct {
req Request
want bool
}{
{Request{Verb: "list", Resource: "configmaps", Namespace: "shop"}, true},
{Request{Verb: "watch", Resource: "configmaps", Namespace: "shop"}, true},
{Request{Verb: "get", Resource: "configmaps", Name: "orders-flags", Namespace: "shop"}, true},
{Request{Verb: "update", Resource: "configmaps", Name: "orders-flags", Namespace: "shop"}, false},
{Request{Verb: "list", Resource: "configmaps", Namespace: "payments"}, false}, // RoleBinding is namespaced
{Request{Verb: "list", Resource: "configmaps"}, false}, // nor cluster-wide
{Request{Verb: "get", Resource: "secrets", Name: "orders-db", Namespace: "shop"}, false},
{Request{Verb: "create", Resource: "pods", Subresource: "exec", Name: "x", Namespace: "shop"}, false},
{Request{Verb: "list", APIGroup: "apps", Resource: "configmaps", Namespace: "shop"}, false}, // wrong API group
} {
tc.req.User, tc.req.Groups = user, groups
got, why := s.Allowed(tc.req)
if got != tc.want {
t.Errorf("%+v: allowed=%v (%s), want %v", tc.req, got, why, tc.want)
}
}
}
func TestPeopleAndCI(t *testing.T) {
s := load(t, "people-and-ci.yaml")
dev := Request{User: "oidc:jane@acme.example", Groups: []string{"oidc:shop-developers", "system:authenticated"}, Namespace: "shop"}
logs := dev
logs.Verb, logs.Resource, logs.Subresource, logs.Name = "get", "pods", "log", "shop-web-1"
if ok, why := s.Allowed(logs); !ok {
t.Errorf("developer cannot read pods/log: %s", why)
}
exec := logs
exec.Verb, exec.Subresource = "create", "exec"
if ok, _ := s.Allowed(exec); ok {
t.Error("developer can exec: pods/log must not imply pods/exec")
}
deployer, groups := ServiceAccount("shop", "shop-deployer")
for _, tc := range []struct {
verb, group, res string
want bool
}{
{"patch", "apps", "deployments", true},
{"create", "batch", "jobs", true},
{"create", "rbac.authorization.k8s.io", "rolebindings", false},
{"get", "", "secrets", false},
{"patch", "", "namespaces", false}, // would let it relabel PSA
{"delete", "apps", "deployments", false},
} {
r := Request{User: deployer, Groups: groups, Verb: tc.verb, APIGroup: tc.group, Resource: tc.res, Namespace: "shop"}
if ok, why := s.Allowed(r); ok != tc.want {
t.Errorf("deployer %s %s/%s: allowed=%v (%s), want %v", tc.verb, tc.group, tc.res, ok, why, tc.want)
}
}
// Aggregation: acme-auditor has no rules of its own, but inherits the
// rules of every ClusterRole labelled acme.io/aggregate-to-auditor.
s.ClusterRoleBindings = append(s.ClusterRoleBindings, auditorBinding())
audit := Request{User: "oidc:auditor@acme.example", Verb: "list", APIGroup: "rbac.authorization.k8s.io", Resource: "clusterrolebindings"}
if ok, why := s.Allowed(audit); !ok {
t.Errorf("aggregated ClusterRole did not grant: %s", why)
}
health := Request{User: "oidc:auditor@acme.example", Verb: "get", Path: "/healthz"}
if ok, _ := s.Allowed(health); !ok {
t.Error("nonResourceURLs /healthz not granted")
}
if ok, _ := s.Allowed(Request{User: "oidc:auditor@acme.example", Verb: "get", Path: "/metrics"}); ok {
t.Error("/metrics granted but not listed")
}
}
// Manual rules in an aggregated ClusterRole are overwritten by the control
// plane, so they must grant nothing here either.
func TestAggregatedClusterRoleIgnoresManualRules(t *testing.T) {
s := load(t, "people-and-ci.yaml")
agg := s.ClusterRoles["acme-auditor"]
agg.Rules = []rbacv1.PolicyRule{ruleOf([]string{"get", "list"}, []string{""}, []string{"secrets"})}
s.ClusterRoles["acme-auditor"] = agg
s.ClusterRoleBindings = append(s.ClusterRoleBindings, auditorBinding())
user := "oidc:auditor@acme.example"
if ok, why := s.Allowed(Request{User: user, Verb: "list", Resource: "secrets", Namespace: "shop"}); ok {
t.Errorf("manual rule in aggregated ClusterRole granted secrets: %s", why)
}
if ok, why := s.Allowed(Request{User: user, Verb: "list", APIGroup: "rbac.authorization.k8s.io", Resource: "roles", Namespace: "shop"}); !ok {
t.Errorf("selected contributor rules not granted: %s", why)
}
}
// An aggregationRule that selects no ClusterRole yields no rules at all,
// even if the manifest (wrongly) carries rules of its own; and a selector
// key that is absent from a role's labels must not match.
func TestAggregatedClusterRoleWithNoMatches(t *testing.T) {
s := load(t, "people-and-ci.yaml")
empty := rbacv1.ClusterRole{
AggregationRule: &rbacv1.AggregationRule{ClusterRoleSelectors: []metav1.LabelSelector{
{MatchLabels: map[string]string{"acme.io/aggregate-to-nobody": "true"}},
{MatchExpressions: []metav1.LabelSelectorRequirement{{Key: "acme.io/missing", Operator: metav1.LabelSelectorOpIn, Values: []string{""}}}},
}},
Rules: []rbacv1.PolicyRule{ruleOf([]string{"*"}, []string{"*"}, []string{"*"})},
}
empty.Name = "acme-empty"
s.ClusterRoles[empty.Name] = empty
if got := s.clusterRoleRules("acme-empty"); len(got) != 0 {
t.Fatalf("aggregated role with no matching contributors has %d rules, want 0", len(got))
}
}
func TestLintBefore(t *testing.T) {
fs := Lint(load(t, "before-overgrant.yaml"))
text := make([]string, len(fs))
for i, f := range fs {
text[i] = f.String()
}
all := strings.Join(text, "\n")
for _, want := range []string{
"ClusterRoleBinding ci-deployer-cluster-admin: binds cluster-admin",
"ClusterRole support-readonly: wildcard",
"ClusterRole support-readonly: list/watch on secrets",
"Role shop/shop-debug: pods/exec",
"Role shop/shop-debug: create pods",
`ClusterRole team-onboarding: verb "escalate"`,
`ClusterRole team-onboarding: verb "bind"`,
`ClusterRole team-onboarding: verb "impersonate"`,
"RoleBinding shop/default-sa-edit: grants to the default ServiceAccount",
} {
if !strings.Contains(all, want) {
t.Errorf("missing finding %q in:\n%s", want, all)
}
}
if HighCount(fs) < 9 {
t.Errorf("HIGH findings = %d, want >= 9", HighCount(fs))
}
}
func TestLintAfterHasNoHigh(t *testing.T) {
fs := Lint(load(t, "orders-api-rbac.yaml", "people-and-ci.yaml"))
for _, f := range fs {
if f.Severity == High {
t.Errorf("unexpected %s", f)
}
}
notes := 0
for _, f := range fs {
if f.Severity == Note {
notes++
}
}
if notes == 0 {
t.Error("expected NOTE findings for the deployer's workload creation")
}
}
func TestRuleAllowsSubresourceWildcard(t *testing.T) {
r := Request{Verb: "update", APIGroup: "apps", Resource: "deployments", Subresource: "scale"}
rule := ruleOf([]string{"update"}, []string{"apps"}, []string{"*/scale"})
if !RuleAllows(r, rule) {
t.Error("*/scale should match deployments/scale")
}
r.Subresource = ""
if RuleAllows(r, rule) {
t.Error("*/scale must not match deployments itself")
}
}
func ruleOf(verbs, groups, resources []string) rbacv1.PolicyRule {
return rbacv1.PolicyRule{Verbs: verbs, APIGroups: groups, Resources: resources}
}
func auditorBinding() rbacv1.ClusterRoleBinding {
b := rbacv1.ClusterRoleBinding{
RoleRef: rbacv1.RoleRef{APIGroup: "rbac.authorization.k8s.io", Kind: "ClusterRole", Name: "acme-auditor"},
Subjects: []rbacv1.Subject{{Kind: rbacv1.UserKind, Name: "oidc:auditor@acme.example"}},
}
b.Name = "acme-auditor"
return b
}تست زیر همهٔ Manifestها را با Decode سختگیرانه به Typeهای k8s.io/api تبدیل میکند. هنگام تألیف، یک خطای واقعی YAML را گرفت: system: prefix بدون Quote در پیام CEL:
// Package manifests checks the chapter's YAML offline: every document of a
// built-in kind is decoded STRICTLY into the k8s.io/api Go types (v0.34),
// so a misspelled or misplaced field fails here the way
// `kubectl apply --dry-run=server` would fail on a cluster. CRDs (Kyverno,
// Gatekeeper, Cilium) and the API server's own config files have no types
// in k8s.io/api and are only parsed as YAML.
package manifests
import (
"os"
"path/filepath"
"strings"
"testing"
admissionregistrationv1 "k8s.io/api/admissionregistration/v1"
appsv1 "k8s.io/api/apps/v1"
batchv1 "k8s.io/api/batch/v1"
corev1 "k8s.io/api/core/v1"
networkingv1 "k8s.io/api/networking/v1"
rbacv1 "k8s.io/api/rbac/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"sigs.k8s.io/yaml"
"academy/kubernetes-security-rbac/rbaccheck"
)
func typed(kind string) any {
switch kind {
case "Namespace":
return &corev1.Namespace{}
case "ServiceAccount":
return &corev1.ServiceAccount{}
case "Pod":
return &corev1.Pod{}
case "Deployment":
return &appsv1.Deployment{}
case "Job":
return &batchv1.Job{}
case "Role":
return &rbacv1.Role{}
case "ClusterRole":
return &rbacv1.ClusterRole{}
case "RoleBinding":
return &rbacv1.RoleBinding{}
case "ClusterRoleBinding":
return &rbacv1.ClusterRoleBinding{}
case "NetworkPolicy":
return &networkingv1.NetworkPolicy{}
case "ValidatingAdmissionPolicy":
return &admissionregistrationv1.ValidatingAdmissionPolicy{}
case "ValidatingAdmissionPolicyBinding":
return &admissionregistrationv1.ValidatingAdmissionPolicyBinding{}
case "ValidatingWebhookConfiguration":
return &admissionregistrationv1.ValidatingWebhookConfiguration{}
case "MutatingWebhookConfiguration":
return &admissionregistrationv1.MutatingWebhookConfiguration{}
}
return nil
}
type doc struct {
file string
kind string
raw []byte
obj any
}
func loadAll(t *testing.T) []doc {
t.Helper()
var files []string
for _, dir := range []string{"../../k8s", "../../apiserver"} {
err := filepath.WalkDir(dir, func(p string, d os.DirEntry, err error) error {
if err == nil && !d.IsDir() && strings.HasSuffix(p, ".yaml") {
files = append(files, p)
}
return err
})
if err != nil {
t.Fatal(err)
}
}
var out []doc
for _, f := range files {
data, err := os.ReadFile(f)
if err != nil {
t.Fatal(err)
}
for i, raw := range rbaccheck.SplitDocuments(data) {
var meta struct {
APIVersion string `json:"apiVersion"`
Kind string `json:"kind"`
}
if err := yaml.Unmarshal(raw, &meta); err != nil {
t.Fatalf("%s doc %d: not YAML: %v", f, i, err)
}
if meta.APIVersion == "" || meta.Kind == "" {
t.Fatalf("%s doc %d: missing apiVersion/kind", f, i)
}
d := doc{file: f, kind: meta.Kind, raw: raw}
if obj := typed(meta.Kind); obj != nil {
if err := yaml.UnmarshalStrict(raw, obj); err != nil {
t.Errorf("%s doc %d (%s): %v", f, i, meta.Kind, err)
}
d.obj = obj
} else {
var anyDoc map[string]any
if err := yaml.UnmarshalStrict(raw, &anyDoc); err != nil {
t.Errorf("%s doc %d (%s): %v", f, i, meta.Kind, err)
}
}
out = append(out, d)
}
}
return out
}
func TestStrictDecode(t *testing.T) {
docs := loadAll(t)
n := 0
for _, d := range docs {
if d.obj != nil {
n++
}
}
t.Logf("%d documents, %d decoded into k8s.io/api types", len(docs), n)
if n < 30 {
t.Fatalf("only %d typed documents; did a file move?", n)
}
}
// Rules the API server or the docs state, checked by hand.
func TestSecurityInvariants(t *testing.T) {
for _, d := range loadAll(t) {
switch o := d.obj.(type) {
case *corev1.Namespace:
for k, v := range o.Labels {
if !strings.HasPrefix(k, "pod-security.kubernetes.io/") {
continue
}
mode := strings.TrimSuffix(strings.TrimPrefix(k, "pod-security.kubernetes.io/"), "-version")
if mode != "enforce" && mode != "audit" && mode != "warn" {
t.Errorf("%s: unknown PSA mode label %s", d.file, k)
}
if strings.HasSuffix(k, "-version") {
if v != "latest" && !strings.HasPrefix(v, "v1.") {
t.Errorf("%s: %s=%s is not latest or v1.NN", d.file, k, v)
}
} else if v != "privileged" && v != "baseline" && v != "restricted" {
t.Errorf("%s: %s=%s is not a PSS level", d.file, k, v)
}
}
case *admissionregistrationv1.ValidatingAdmissionPolicyBinding:
deny, warn := false, false
for _, a := range o.Spec.ValidationActions {
deny = deny || a == admissionregistrationv1.Deny
warn = warn || a == admissionregistrationv1.Warn
}
if deny && warn {
t.Errorf("%s: Deny and Warn may not be used together", d.file)
}
case *admissionregistrationv1.ValidatingWebhookConfiguration:
for _, w := range o.Webhooks {
if w.TimeoutSeconds == nil || *w.TimeoutSeconds > 10 {
t.Errorf("%s: webhook %s needs timeoutSeconds <= 10", d.file, w.Name)
}
if w.NamespaceSelector == nil {
t.Errorf("%s: webhook %s should exclude its own namespace", d.file, w.Name)
}
}
case *rbacv1.RoleBinding:
if o.Namespace == "" {
t.Errorf("%s: RoleBinding %s has no namespace", d.file, o.Name)
}
case *appsv1.Deployment:
checkPodSpec(t, d.file, o.Name, o.Spec.Template.Spec)
case *batchv1.Job:
checkPodSpec(t, d.file, o.Name, o.Spec.Template.Spec)
}
}
}
func checkPodSpec(t *testing.T, file, name string, ps corev1.PodSpec) {
t.Helper()
if ps.AutomountServiceAccountToken == nil || *ps.AutomountServiceAccountToken {
t.Errorf("%s: %s must set automountServiceAccountToken: false", file, name)
}
if ps.ServiceAccountName == "" || ps.ServiceAccountName == "default" {
t.Errorf("%s: %s must use its own ServiceAccount", file, name)
}
for _, v := range ps.Volumes {
if v.Projected == nil {
continue
}
for _, src := range v.Projected.Sources {
if st := src.ServiceAccountToken; st != nil && st.ExpirationSeconds != nil && *st.ExpirationSeconds < 600 {
t.Errorf("%s: projected token shorter than the 600 s minimum", file)
}
}
}
}
// Every NetworkPolicy podSelector in shop must select a label some
// Deployment or policy target in this chapter (or the Workloads chapter)
// really carries; a typo here silently selects nothing.
func TestNetworkPolicySelectorsUseKnownApps(t *testing.T) {
known := map[string]bool{
"shop-web": true, "orders-api": true, "shop-mysql": true, "shop-redis": true,
"shop-queue": true, "shop-scheduler": true, "ingress-nginx": true,
}
for _, d := range loadAll(t) {
np, ok := d.obj.(*networkingv1.NetworkPolicy)
if !ok {
continue
}
check := func(where string, ml map[string]string) {
if v, ok := ml["app.kubernetes.io/name"]; ok && !known[v] {
t.Errorf("%s %s: %s selects unknown app %q", d.file, np.Name, where, v)
}
}
check("spec.podSelector", np.Spec.PodSelector.MatchLabels)
for _, r := range np.Spec.Ingress {
for _, p := range r.From {
if p.PodSelector != nil {
check("ingress.from", p.PodSelector.MatchLabels)
}
}
}
for _, r := range np.Spec.Egress {
for _, p := range r.To {
if p.PodSelector != nil {
check("egress.to", p.PodSelector.MatchLabels)
}
}
}
}
}
// The strict decoder is what makes TestStrictDecode meaningful: a field in
// the wrong place (here automountServiceAccountToken under metadata) fails.
func TestStrictDecodeCatchesMisplacedField(t *testing.T) {
bad := []byte("apiVersion: v1\nkind: ServiceAccount\nmetadata:\n name: x\n automountServiceAccountToken: false\n")
if err := yaml.UnmarshalStrict(bad, &corev1.ServiceAccount{}); err == nil {
t.Fatal("misplaced field accepted")
}
good := []byte("apiVersion: v1\nkind: ServiceAccount\nmetadata:\n name: x\nautomountServiceAccountToken: false\n")
if err := yaml.UnmarshalStrict(good, &corev1.ServiceAccount{}); err != nil {
t.Fatal(err)
}
}
// NetworkPolicy needs BOTH sides: for every in-namespace egress rule
// "app A -> app B on port P", some policy selecting B must allow ingress
// from A on P, otherwise the connection is dropped under default deny.
func TestNetworkPolicyBothSidesAllow(t *testing.T) {
type edge struct {
from, to string
port int32
}
appsOf := func(sel *metav1.LabelSelector) []string {
if sel == nil {
return nil
}
if v, ok := sel.MatchLabels["app.kubernetes.io/name"]; ok {
return []string{v}
}
for _, e := range sel.MatchExpressions {
if e.Key == "app.kubernetes.io/name" && e.Operator == metav1.LabelSelectorOpIn {
return e.Values
}
}
return nil
}
var egress, ingress []edge
for _, d := range loadAll(t) {
np, ok := d.obj.(*networkingv1.NetworkPolicy)
if !ok || np.Namespace != "shop" {
continue
}
selected := appsOf(&np.Spec.PodSelector)
for _, r := range np.Spec.Egress {
for _, peer := range r.To {
if peer.NamespaceSelector != nil || peer.IPBlock != nil {
continue // other namespaces and external IPs are checked elsewhere
}
for _, src := range selected {
for _, dst := range appsOf(peer.PodSelector) {
for _, p := range r.Ports {
egress = append(egress, edge{src, dst, p.Port.IntVal})
}
}
}
}
}
for _, r := range np.Spec.Ingress {
for _, peer := range r.From {
if peer.NamespaceSelector != nil || peer.IPBlock != nil {
continue
}
for _, src := range appsOf(peer.PodSelector) {
for _, dst := range selected {
for _, p := range r.Ports {
ingress = append(ingress, edge{src, dst, p.Port.IntVal})
}
}
}
}
}
}
if len(egress) == 0 {
t.Fatal("no in-namespace egress edges found")
}
for _, e := range egress {
found := false
for _, i := range ingress {
if i == e {
found = true
}
}
if !found {
t.Errorf("egress %s -> %s:%d has no matching ingress allow on %s", e.from, e.to, e.port, e.to)
}
}
}نگاه Go
- تنظیم داخل Cluster سه فایل و دو متغیر است.
rest.InClusterConfig()،KUBERNETES_SERVICE_HOST/KUBERNETES_SERVICE_PORTو/var/run/secrets/kubernetes.io/serviceaccount/{token,ca.crt}را میخواند. در نبود متغیرهاrest.ErrNotInClusterمیدهد: "unable to load in-cluster configuration, KUBERNETES_SERVICE_HOST and KUBERNETES_SERVICE_PORT must be defined". فیلدBearerTokenFileرا تنظیم میکند و "If set, the contents are periodically read"؛ پس چرخش توکن دهدقیقهای توسط kubelet کد اضافه نمیخواهد. توکن ابتدای اجرا را در String کپی نکنید. - Namespace را از فایل بگیرید. فایل
namespaceاز Downward API در Projected volume میآید؛ همان Image درshop،shop-stagingو Preview هر PR، بدون RBAC تازه کار میکند. - Client را از ابتدا به Namespace محدود کنید.
CoreV1().ConfigMaps(ns)با Namespace مشخص فقط Role میخواهد؛metav1.NamespaceAllبه ClusterRole و ClusterRoleBinding نیاز دارد. Informer هم همین است:informers.NewSharedInformerFactoryWithOptions(cs, resync, informers.WithNamespace(ns))فقطlistوwatchهمان Namespace را میخواهد. - شکست RBAC فوری و روشن باشد. SelfSubjectAccessReview هنگام شروع، خطاهای پراکندهٔ بعدی ۴۰۳ را به یک لاگ با Namespace، Verb و Resource تبدیل میکند. هر هویت احرازشده میتواند دربارهٔ خودش SelfSubjectAccessReview بسازد؛ مجوز اضافی لازم نیست.
- ۴۰۳ را از بقیه جدا کنید.
apierrors.IsForbidden(err)وIsUnauthorizedبرای ۴۰۱ اجازه میدهند «تنظیم اشتباه» اعلام شود، نه Retry بیپایان. Wrap با%w، همerrors.Is(err, ErrForbidden)و همIsForbiddenرا حفظ میکند. - Client کمفشار بسازید.
UserAgentدر Audit باuserAgentدیده میشود؛QPS/Burstرا کم نگه دارید. API Priority and Fairness در هر صورت Client پرسروصدا را محدود میکند. - نسخهها. client-go v0.34.1 همراه
k8s.io/apiوk8s.io/apimachineryv0.34.1،go 1.24.0اعلام میکند؛ به همین دلیل خطgoماژول1.24.0است. v0.35 به Go 1.25 نیاز دارد. client-go اختلاف نسخهٔ متعارف API server را پشتیبانی میکند؛ APIهای ConfigMap و SelfSubjectAccessReview v1 استفادهشده در Kubernetes 1.37 پایدارند. - خارج Cluster همین کد با kubeconfig و
clientcmd.BuildConfigFromFlagsو هویت OIDC توسعهدهنده کار میکند. kubeconfig دارای توکن ServiceAccount را داخل Image نفرستید. بررسی JWT در سرویس خودتان، مثلاً توکن Kubernetes با Audience برابرorders-apiاز workload دیگر، با TokenReview یا JWKS خوشه در احراز هویت در Go است.
Laravel
فروشگاه Laravel شامل Nginx و php-fpm در shop-web و همچنین shop-queue و shop-scheduler از بارهای کاری Kubernetes، اصلاً Kubernetes API را صدا نمیزند. RBAC درست برای آن هیچ مجوزی و توکن درست، نبود توکن است. هدف این بخش Pod برنامهٔ Laravel بدون دسترسی API است.
قبل
# Before: what Helm charts and quick starts produce.
apiVersion: apps/v1
kind: Deployment
metadata:
name: shop-web
spec:
template:
spec:
# no serviceAccountName -> "default"; no automount setting -> token mounted
containers:
- name: php-fpm
image: ghcr.io/acme/shop-app:latest # mutable tag, runs as root by default
---
# "The queue worker needed to list pods once" -> edit for the default SA
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: default-edit
roleRef: {apiGroup: rbac.authorization.k8s.io, kind: ClusterRole, name: edit}
subjects: [{kind: ServiceAccount, name: default, namespace: shop}]
# ...and no NetworkPolicy: the web Pod can reach the API server, the metadata
# endpoint, every other namespace and the internet.اکنون RCE در هر وابستگی Composer، فایل /var/run/secrets/kubernetes.io/serviceaccount/token را میخواند و با edit همهٔ Secretهای shop را میگیرد و Pod را با هر ServiceAccount آن اجرا میکند.
بعد
ServiceAccount اختصاصی بدون Binding و توکن، و Pod template استفادهکنندهٔ آن. Nginx روی پورت ۸۰۸۰ گوش میدهد، چون غیر root تحت PSA restricted اجرا میشود و بدون NET_BIND_SERVICE نمیتواند پورت ۸۰ را بگیرد؛ بارهای کاری Kubernetes برای سادگی از ۸۰ استفاده میکند:
# The Laravel app never talks to the Kubernetes API, so its Pods get:
# - a dedicated ServiceAccount with no RoleBindings at all
# - no token in the filesystem (automountServiceAccountToken: false on both
# the ServiceAccount and the Pod template; the Pod setting wins if they differ)
# A remote-code-execution bug in a Composer package then finds no
# /var/run/secrets/kubernetes.io/serviceaccount/token to steal, and
# shop-web-netpol.yaml gives it no route to the API server either.
apiVersion: v1
kind: ServiceAccount
metadata:
name: shop-web
namespace: shop
automountServiceAccountToken: false
---
# Excerpt of the shop-web Deployment from the Kubernetes Workloads chapter:
# only the fields this chapter adds are shown with their surroundings.
apiVersion: apps/v1
kind: Deployment
metadata:
name: shop-web
namespace: shop
labels:
app.kubernetes.io/name: shop-web
spec:
selector:
matchLabels:
app.kubernetes.io/name: shop-web
template:
metadata:
labels:
app.kubernetes.io/name: shop-web
spec:
serviceAccountName: shop-web
automountServiceAccountToken: false
securityContext:
runAsNonRoot: true
runAsUser: 33 # www-data in the Debian-based php:8.4-fpm images
seccompProfile:
type: RuntimeDefault
containers:
- name: php-fpm
image: ghcr.io/acme/shop-app:1.8.0
resources:
requests: {cpu: 250m, memory: 256Mi}
limits: {memory: 512Mi}
securityContext:
allowPrivilegeEscalation: false
capabilities:
drop: ["ALL"]
- name: nginx
image: ghcr.io/acme/shop-web:1.8.0
ports:
- name: http
containerPort: 8080
resources:
requests: {cpu: 50m, memory: 32Mi}
limits: {memory: 64Mi}
securityContext:
allowPrivilegeEscalation: false
capabilities:
drop: ["ALL"]Ingress فقط از Controller مربوط به ingress-nginx؛ Egress فقط به MySQL و Redis و قاعدهٔ DNS کل Namespace؛ قواعد Ingress متناظر روی MySQL و Redis چون هر دو سمت باید مجاز کنند؛ و Egress برای queue و scheduler. تست manifests وجود همتای Ingress برای هر قاعدهٔ Egress داخل Namespace را بررسی میکند:
# The Laravel web Pods (Nginx + php-fpm, label app.kubernetes.io/name: shop-web):
# ingress only from the ingress-nginx controller, on the Nginx port (8080: the
# non-root Nginx of this chapter cannot bind 80 without NET_BIND_SERVICE)
# egress only to MySQL and Redis in this namespace (DNS comes from
# shop-default-deny.yaml). No route to the Kubernetes API, the cloud
# metadata endpoint or the internet.
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: shop-web
namespace: shop
spec:
podSelector:
matchLabels:
app.kubernetes.io/name: shop-web
policyTypes: [Ingress, Egress]
ingress:
- from:
# ONE list item with both selectors = controller Pods in ingress-nginx.
# Two separate items ("- namespaceSelector" and "- podSelector") would
# mean "anything in ingress-nginx OR those labels in shop".
- namespaceSelector:
matchLabels:
kubernetes.io/metadata.name: ingress-nginx
podSelector:
matchLabels:
app.kubernetes.io/name: ingress-nginx
ports:
- {protocol: TCP, port: 8080}
egress:
- to:
- podSelector:
matchLabels:
app.kubernetes.io/name: shop-mysql
ports:
- {protocol: TCP, port: 3306}
- to:
- podSelector:
matchLabels:
app.kubernetes.io/name: shop-redis
ports:
- {protocol: TCP, port: 6379}
---
# The other side: MySQL accepts connections from the web, queue and scheduler
# Pods only. Both the egress rule above AND this ingress rule must allow it.
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: shop-mysql
namespace: shop
spec:
podSelector:
matchLabels:
app.kubernetes.io/name: shop-mysql
policyTypes: [Ingress]
ingress:
- from:
- podSelector:
matchExpressions:
- key: app.kubernetes.io/name
operator: In
values: [shop-web, shop-queue, shop-scheduler]
ports:
- {protocol: TCP, port: 3306}
---
# Redis accepts the same three Laravel roles.
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: shop-redis
namespace: shop
spec:
podSelector:
matchLabels:
app.kubernetes.io/name: shop-redis
policyTypes: [Ingress]
ingress:
- from:
- podSelector:
matchExpressions:
- key: app.kubernetes.io/name
operator: In
values: [shop-web, shop-queue, shop-scheduler]
ports:
- {protocol: TCP, port: 6379}
---
# The queue worker and the scheduler: no ingress at all, egress to MySQL and
# Redis only (same image as shop-web, different command).
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: shop-workers
namespace: shop
spec:
podSelector:
matchExpressions:
- key: app.kubernetes.io/name
operator: In
values: [shop-queue, shop-scheduler]
policyTypes: [Ingress, Egress]
egress:
- to:
- podSelector:
matchLabels:
app.kubernetes.io/name: shop-mysql
ports:
- {protocol: TCP, port: 3306}
- to:
- podSelector:
matchLabels:
app.kubernetes.io/name: shop-redis
ports:
- {protocol: TCP, port: 6379}اگر MySQL سرویس مدیریتشدهٔ بیرون Cluster است، این فایل را بهجای قواعد shop-mysql اعمال کنید. جایگزین است؛ اضافه نیست، چون Policyها افزایشیاند و اعمال هر دو، هر دو مسیر را باز میکند:
# ALTERNATIVE to the in-cluster shop-mysql rules in shop-web-netpol.yaml, applied
# INSTEAD of them (policies are additive, so applying both allows both paths).
# Managed MySQL (RDS, Cloud SQL, Azure Database) lives outside the cluster:
# use ipBlock with the database subnet instead of a podSelector. Whether
# ipBlock sees the real destination depends on the plugin and on NAT.
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: shop-web-managed-db
namespace: shop
spec:
podSelector:
matchLabels:
app.kubernetes.io/name: shop-web
policyTypes: [Egress]
egress:
- to:
- ipBlock:
cidr: 10.20.0.0/24 # the private database subnet
except: [10.20.0.1/32]
ports:
- {protocol: TCP, port: 3306}نگاه Laravel
- بدون توکن، بدون API. با
automountServiceAccountToken: falseروی ServiceAccount و Pod، چیزی زیر/var/run/secrets/kubernetes.io/serviceaccountقرار نمیگیرد. Pod همچنان باspec.serviceAccountNameبه SA با نامshop-webنسبت داده شده، ولی اعتبارنامهای برای ارائه ندارد. - تستی برای حفظ این وضعیت. آن را در Smoke test کانتینر داخل Cluster، مثلاً Job پس از استقرار، اجرا کنید تا تغییر Chart و فعالشدن دوبارهٔ Automount، Pipeline را شکست دهد:
<?php
// tests/Feature/NoKubernetesApiAccessTest.php — runs inside the deployed image (post-deploy smoke test)
namespace Tests\Feature;
use Tests\TestCase;
final class NoKubernetesApiAccessTest extends TestCase
{
public function test_no_service_account_token_is_mounted(): void
{
$this->assertFileDoesNotExist('/var/run/secrets/kubernetes.io/serviceaccount/token');
}
public function test_api_server_is_not_reachable(): void
{
// KUBERNETES_SERVICE_HOST is still injected; NetworkPolicy must drop the connection.
$host = getenv('KUBERNETES_SERVICE_HOST') ?: 'kubernetes.default.svc';
$socket = @fsockopen($host, 443, $errno, $errstr, 2.0);
$this->assertFalse($socket, 'shop-web can open a TCP connection to the Kubernetes API');
}
}- دسترسی ابر فقط در محل نیاز. اگر Job صف فاکتور را به S3 میفرستد، به
shop-queue، SA اختصاصی با IRSA یا GKE/Azure Workload identity بدهید وshop-webبدون آن بماند. AWS SDK for PHP و Driver با نامs3در Laravel اعتبارنامهٔ Web identity را از محیط میگیرند؛ کلیدی در.envلازم نیست. - Proxy مورد اعتماد. وقتی ingress-nginx تنها همتای Ingress مجاز است، میانافزار (Middleware) با نام
TrustProxiesرا با$middleware->trustProxies(at: [...])درbootstrap/app.phpبرای Pod CIDR کنترلر تنظیم کنید تا$request->ip()آدرس کلاینت را بدهد. NetworkPolicy تضمین میکند دیگران آن Forwarded headerها را نفرستند. - Secret بهشکل فایل یا Env، نه API.
DB_PASSWORDاز Secret نصبشده توسط kubelet میآید؛ پیکربندی، Secret و ذخیرهسازی. برنامه هرگزget secretsنمیخواهد. - مسیر سلامت. Probe از kubelet و با Pod IP به
/upمیرسد؛ ترافیک Node به Pod همیشه در NetworkPolicy مجاز است، پس با Default deny هم Probe کار میکند.
حل مسئلههای کلاسیک (Solving the classic problems)
| مسئله | راهحل | روش | مزیت | هزینه / محدودیت |
|---|---|---|---|---|
| CI دارای cluster-admin | Role استقرار Namespace و توکن کوتاه | Role با نام shop-deployer، kubectl create token --duration=15m یا OIDC ابری؛ مجوز پروژهای Argo CD | افشا محدود به یک Namespace و چند دقیقه | Role هر Namespace |
| Debug عملیاتی برای توسعهدهنده | لاگ، بدون exec معمول | Role برای pods/log؛ kubectl debug فقط در Break-glass | بدون Shell در Pod عملیاتی | بعضی خطاها بازتولید میخواهند |
| PSA restricted بدون قطعی | ابتدا warn/audit | Label با --dry-run=server، warn+audit restricted، enforce baseline، سپس restricted با نسخهٔ ثابت | شکست پیش از وقوع دیده میشود | چند هفته پیگیری |
| قطعی Webhook مانع Cluster | استثنا، افزونگی، قواعد داخل Process | حذف kube-system و خودش با namespaceSelector، ≥ 2 Replica و PDB، VAP ساده | Control plane از Webhook قطعشده جان سالم میبرد | منطق در دو محل |
| توکن ServiceAccount بلندمدت | حذف Secret توکن قدیمی | kubectl get secrets -A --field-selector type=kubernetes.io/service-account-token؛ Projected token | بدون اعتبارنامهٔ بیانقضا | کلاینت قدیمی باید فایل را بازخوانی کند |
| کلید ابر در Secret | Workload identity | IRSA / Pod Identity / GKE / Azure WI هر SA | بدون اعتبارنامهٔ ثابت ابر | تنظیم OIDC هر Cluster |
| Default deny، Namespace را خراب میکند | DNS و Allow هر workload | allow-dns-egress سپس Policy برنامه، تست در Staging | حداقل دسترسپذیری شبکه | هر وابستگی تازه یک PR |
| «چه کسی Deployment پرداخت را حذف کرد؟» | Audit و Retention | Metadata همهجا، RequestResponse برای RBAC، ارسال به SIEM | پاسخ در چند دقیقه | فضا و حافظهٔ API server |
CI دارای cluster-admin است
ClusterRoleBinding را با Role در هر Namespace مقصد عوض کنید؛ فقط Kindهای برنامه مانند Deployment، Service، ConfigMap، Ingress، NetworkPolicy و Job را بدهید، بدون RBAC، Secret یا شیء Namespace. GitHub Actions و GitLab CI با OIDC در ابر احراز هویت و اعتبارنامهٔ کوتاه Cluster میگیرند؛ در مدیریت شخصی، Runner معتبر از kubectl create token shop-deployer --duration=15m استفاده کند. در GitOps اصلاً Pipeline با Cluster حرف نمیزند؛ Digest را در Git مینویسد و Argo CD با AppProject محدود به shop اعمال میکند؛ GitOps. خطر باقیمانده همان NOTE در Linter است: ساخت Deployment یعنی اجرای Pod با هر SA در shop. به همین دلیل فقط SAهای فروشگاه در shop هستند و PSA restricted اعمال میشود.
توسعهدهنده به Debug عملیاتی نیاز دارد
برای همه view و Role با نام shop-log-reader برای pods و pods/log بدهید. pods/exec و pods/ephemeralcontainers فقط از گروه Break-glass قابل استفاده با Impersonation مسئول شیفت باشد؛ مجوز impersonate فقط روی همان گروه. هر exec با هویت آن گروه در Audit دیده میشود و هشدار میدهد. Metrics و Trace باید بیشتر پرسشها را بدون Shell پاسخ دهند؛ مشاهدهپذیری و عیبیابی Kubernetes.
عرضهٔ PSA restricted بدون قطعی
با kubectl label --dry-run=server --overwrite ns <ns> pod-security.kubernetes.io/enforce=restricted موارد متخلف را ببینید. سپس warn و audit را restricted کنید، در حالی که enforce روی baseline است. Manifest را اصلاح کنید؛ چهار مورد معمول allowPrivilegeEscalation: false، حذف ALL capabilities، runAsNonRoot: true و seccompProfile: RuntimeDefault هستند. بعد enforce را با enforce-version ثابت بالا ببرید. فصل امنیت کانتینر همین Rollout را از دید کانتینر توضیح میدهد.
قطعی Policy webhook، Cluster را مسدود میکند
رویهٔ اضطراری مکتوب باشد: چه کسی اجازهٔ kubectl delete validatingwebhookconfiguration دارد و پس از آن GitOps باید دوباره آن را اعمال کند. برای پیشگیری kube-system و Namespace موتور را کنار بگذارید، برای User سیستمی matchConditions داشته باشید، حداقل دو Replica روی Nodeهای مختلف با PodDisruptionBudget، و timeoutSeconds چندثانیهای تنظیم کنید. هر قاعدهٔ قابل بیان با CEL را به ValidatingAdmissionPolicy ببرید که قطعی شبکه ندارد.
Default deny، Namespace را خراب کرده است
ابتدا در Staging همراه قاعدهٔ DNS از روز اول اعمال کنید. Flow log در Cilium Hubble یا Calico، اتصالهای (Connections) واقعی هر workload را نشان میدهد؛ از آن Allow policy بسازید، سپس در محیط عملیاتی اعمال کنید. Probe تحت تأثیر نیست، چون Node به Pod همیشه مجاز است. API server و DB بیرونی موارد غافلگیرکنندهاند، چون ipBlock یا همتای اختصاصی CNI میخواهند.
انتخاب (Choosing)
کدام لایهٔ سیاست
| قاعده | لایه | دلیل |
|---|---|---|
| Privileged، hostPath، Capability، root | Pod Security Admission | داخلی؛ Fail open نمیشود |
Label اجباری، سقف Replica، منع :latest، Limits اجباری | ValidatingAdmissionPolicy | CEL داخل Process؛ بدون مؤلفهٔ اضافه |
| امضای Image و تثبیت Digest | Kyverno ImageValidatingPolicy یا Sigstore policy-controller | نیاز به Registry و Transparency log |
| مقدار پیشفرض، تزریق Label و Sidecar، تولید Default deny | MutatingAdmissionPolicy یا Kyverno | Mutation و Generation |
| گزارش اجراهای موجود | Background scan در Kyverno یا Audit در Gatekeeper | Admission فقط نوشتن جدید را میبیند |
| سازمان از قبل Rego دارد | OPA Gatekeeper | یک زبان سیاست برای Terraform، CI و Kubernetes |
احراز هویت انسان با چه روشی
| Cluster | ورود انسان | Break-glass |
|---|---|---|
| kubeadm / k3s در محل سازمان | OIDC با AuthenticationConfiguration و Dex، Keycloak یا IdP سازمان | یک گواهی در Vault با هشدار مصرف |
| EKS | IAM Identity Center و Access entry | IAM role جدا با Access policy برای cluster-admin |
| GKE | هویت Google و Google Groups برای RBAC | مدیر سازمانی با Audit |
| AKS | Microsoft Entra ID، حساب محلی غیرفعال | گروه Entra برای دسترسی اضطراری |
| لپتاپ با kind یا Docker Desktop | گواهی مدیر تولیدشده | — |
کدام Workload identity
| Platform | انتخاب | نکته |
|---|---|---|
| EKS جدید | EKS Pod Identity | بدون OIDC provider هر Cluster؛ Agent DaemonSet |
| EKS موجود یا Federation بین حسابها | IRSA | همهجا با OIDC issuer، حتی مدیریت شخصی |
| GKE | Workload Identity Federation با Principal binding | Pool مشترک Fleet؛ نام Namespace مهم است |
| AKS | Microsoft Entra Workload ID | Label با azure.workload.identity/use: "true" الزامی |
| Secret مبتنی بر Vault در هر محیط | Vault Kubernetes یا JWT auth با Projected token مخصوص Audience | Audience برابر vault و انقضای کوتاه |
کدام CNI برای سیاست
| نیاز | انتخاب |
|---|---|
| NetworkPolicy استاندارد و پشتیبانی گسترده | Calico یا Cilium، یا پیشفرض مدیریتشده با Policy فعال |
| FQDN egress، HTTP در L7، دید Hubble | Cilium |
| ترتیب سیاست با Deny، سیاست سراسری، حفاظت Host | Calico |
| EKS با IP بومی VPC برای Pod | AWS VPC CNI با Network policy فعال یا Cilium در حالت Chaining |
| رمزنگاری ترافیک Pod و L7 مبتنی بر هویت | Service mesh یا Cilium mutual authentication؛ mTLS و امنیت سرویس |
کدام مدل مستأجر
| مستأجرها | مدل |
|---|---|
| تیمهای یک شرکت با شیفت مشترک | Namespace هر تیم و بستهٔ این فصل |
| تیم نیازمند CRD، Webhook یا cluster-admin مستقل | vCluster روی Node مشترک |
| مشتری بیرونی با کد خودش | vCluster روی Node خصوصی یا Cluster هر مشتری |
| Workload با مقررات کارت بانکی یا سلامت | Cluster و حساب ابری جدا |
در معماری: از یک پردازه تا سیستم توزیعشده (In architecture: from a single process to a distributed system)
امنیت Kubernetes بیشتر با تعداد هویتها رشد میکند تا تعداد Podها. هر تیم، Pipeline و سرویس تازه Subject جدیدی است که Binding، Label مربوط به Namespace، قاعدهٔ شبکه و ردگیری ممیزی (Audit trail) میخواهد.
یکپارچه: یک برنامه، یک Namespace (Monolith)
Laravel یکپارچه در shop سه Deployment برای Web، Queue و Scheduler و یک DB دارد. حداقل درست، همین فصل در مقیاس کوچک است: SAهای shop-web، shop-queue و shop-scheduler بدون Binding و توکن؛ PSA restricted؛ NetworkPolicy با Default deny و DNS؛ Ingress وب از ingress-nginx و Egress به MySQL و Redis؛ Deployer Role برای Pipeline؛ ورود OIDC برای دو توسعهدهنده با view و edit؛ Audit در Metadata. هیچکدام Policy Engine لازم ندارد.
یکپارچهٔ ماژولار: Namespace و مالکیت (Modular monolith)
همان Codebase اکنون Go orders-api و Back-office مدیریتی با مالکان متفاوت دارد. جداسازی بر اساس اعتماد است: shop رو به مشتری، shop-admin داخلی با Ingress متفاوت و Egress سختگیرانهتر، shop-jobs برای Batch. هر Namespace گروه مالک با admin، Deployer و NetworkPolicy خود را دارد؛ فراخوانی بین Namespaceها با namespaceSelector صریح مجاز میشود. Role تکی orders-api برای ConfigMap در shop همچنان تنها مجوز API بین workloadهاست.
ریزسرویسها: تیمهای متعدد و تیم Platform (Microservices)
بیست سرویس و ده تیم داریم. تیم Platform مالک موارد سراسری است: PSA default، ValidatingAdmissionPolicy، Policy Engine، Audit، CNI و ClusterRole تجمیعی برای CRDها. همچنین Template هر Namespace را با GitOps میدهد. تیمها مالک اشیای Namespace هستند. جریان معمول عضوسازی، همگی با Pull request:
1 team opens a PR to the platform repo: tenants/orders.yaml (owners, cost centre, tier)
2 CI renders the bundle with Helm or Kustomize: Namespace + PSA labels, RoleBindings for OIDC groups,
deployer ServiceAccount + Role, ResourceQuota, default-deny NetworkPolicy, Argo CD AppProject
3 CI runs rbaccheck (no HIGH findings), kyverno test / gator verify, kubectl --dry-run=server
4 Argo CD syncs; Terraform has already created the cloud role for the team's workload identity
5 the team's own repo deploys only into its namespace; any ClusterRoleBinding in it fails the policyمدل عمومی مالکیت و بازبینی مجوز در مجوز: RBAC، ABAC و Zero Trust و دلیل معماری انتخاب Kubernetes در کانتینر و Kubernetes است.
دادهٔ توزیعشده: Cluster، Region و هویت متعدد (Distributed data)
با Cluster جدا برای Region و محیط، سختی به سازگاری تنظیم و Federation هویت منتقل میشود. RBAC، PSA label و Policy با GitOps، مانند Argo CD ApplicationSets و Flux، کپی میشوند تا Bindingها یکسان باشند؛ انحراف تنظیم (Drift) یافتهٔ امنیتی است. هویت انسان یکبار Federate میشود: Issuer و نام گروه OIDC یکسان در همهٔ API serverها. Audit همهٔ Clusterها با نام Cluster به یک SIEM میرود. Workload identity برای هر Cluster Issuer و کلید خودش را دارد؛ در GKE، Pool مشترک باعث میشود ns/shop/sa/orders-api در همهٔ Fleet یک Principal باشد؛ راحت است ولی باید عمدی باشد. سیاست شبکه بین Clusterها با Cilium Cluster Mesh یا Service mesh گسترش مییابد. بررسی امضا باید در همهٔ Regionها کار کند؛ بنابراین امضا و گواهی ساخت (Attestation) همراه Image کپی میشوند.
مسیر مقیاسدهی: یکبرابر، دهبرابر، صدبرابر (Scaling path)
| مقیاس | هویت | مجوز | Admission | شبکه و Audit |
|---|---|---|---|---|
| 1x، یک تیم و Cluster | OIDC انسان، SA هر workload | ClusterRoleهای داخلی (Built-in) view/edit هر Namespace و Deployer Role | PSA restricted و یک یا دو VAP | Default deny و Allow؛ Metadata به فایل |
| 10x، چند تیم | Group از IdP، Workload identity | Template با GitOps، rbaccheck در CI، نقش تجمیعی CRD | Kyverno یا Gatekeeper با بررسی امضا (Signature verification)؛ Audit → Enforce | CNI با Flow log، هشدار exec و خواندن Secret |
| 100x، Cluster و Region متعدد | یک Federation، رویهٔ Break-glass | repo سیاست بهصورت کد، بازبینی دورهای دسترسیها، حذف خودکار Binding کهنه | سیاست یکسان، تجمیع گزارش Policy | SIEM مرکزی، سیاست شبکهٔ چندCluster، اسکن CIS زمانبندیشده |
آزمایشگاه (Lab)
وضعیت اجرا: تمام فرمانهای kubectl، kube-bench و cosign پایین مورد انتظار، اجرا نشده (expected, not run) هستند؛ میزبان ساخت Cluster ندارد و طبق قاعدهٔ هزینهٔ AUTHORING نباید اینجا Cluster شروع شود. خروجی، مثال مستند Kubernetes یا شکل توصیفشده است، نه مقدار ساختگی. مراحل با عنوان اجراشده روی میزبان (ran on the host) قبلاً در macOS با Go 1.27.4 و darwin/arm64، از ریشهٔ قطعهکدها با bash scripts/lab-offline.sh اجرا شدهاند؛ خروجی واقعی ثبتشده در pipeline/sources/kubernetes-security-rbac/lab-host-output.txt را نشان میدهند.
۱. ساخت و تست ماژول Go، اجراشده روی میزبان
cd docs/snippets/platform/kubernetes-security-rbac/go
gofmt -l . ; go vet ./... ; go test -race -count=1 ./...
# ? academy/kubernetes-security-rbac/before [no test files]
# ? academy/kubernetes-security-rbac/cmd/config-lister [no test files]
# ? academy/kubernetes-security-rbac/cmd/rbaccheck [no test files]
# ok academy/kubernetes-security-rbac/lister 2.037s
# ok academy/kubernetes-security-rbac/manifests 1.588s
# ok academy/kubernetes-security-rbac/rbaccheck 1.412s
go test -count=1 -run 'TestStrictDecode$' -v ./manifests/
# manifests_test.go:125: 55 documents, 44 decoded into k8s.io/api types
# --- PASS: TestStrictDecode (0.01s)۲. Lint آفلاین RBAC قبل و بعد، اجراشده روی میزبان
go run ./cmd/rbaccheck ../k8s/rbac/before-overgrant.yaml
# HIGH ClusterRole support-readonly: list/watch on secrets returns the data of every Secret
# HIGH ClusterRole support-readonly: wildcard in verbs/resources/apiGroups also covers resources added later
# HIGH ClusterRole team-onboarding: verb "bind" bypasses RBAC's privilege-escalation checks
# HIGH ClusterRole team-onboarding: verb "escalate" bypasses RBAC's privilege-escalation checks
# HIGH ClusterRole team-onboarding: verb "impersonate" bypasses RBAC's privilege-escalation checks
# HIGH ClusterRoleBinding ci-deployer-cluster-admin: binds cluster-admin
# HIGH Role shop/shop-debug: create pods = run as any ServiceAccount and mount any Secret in the namespace
# HIGH Role shop/shop-debug: pods/exec gives code execution or credentials beyond this role
# HIGH RoleBinding shop/default-sa-edit: grants to the default ServiceAccount, inherited by every Pod that names none
# 9 findings, 9 HIGH (exit 1)
go run ./cmd/rbaccheck ../k8s/rbac/orders-api-rbac.yaml ../k8s/rbac/people-and-ci.yaml
# NOTE Role shop/shop-deployer: create cronjobs implies running Pods as any ServiceAccount in the namespace
# NOTE Role shop/shop-deployer: create deployments implies running Pods as any ServiceAccount in the namespace
# NOTE Role shop/shop-deployer: create jobs implies running Pods as any ServiceAccount in the namespace
# NOTE Role shop/shop-deployer: create statefulsets implies running Pods as any ServiceAccount in the namespace
# 4 findings, 0 HIGH (exit 0)۳. can-i آفلاین روی YAML، اجراشده روی میزبان
R=../k8s/rbac; SA=system:serviceaccount:shop:orders-api
go run ./cmd/rbaccheck -as $SA -verb list -resource configmaps -n shop $R/orders-api-rbac.yaml $R/people-and-ci.yaml
# yes - RoleBinding shop/orders-api-config-reader
go run ./cmd/rbaccheck -as $SA -verb list -resource configmaps -n payments $R/orders-api-rbac.yaml $R/people-and-ci.yaml
# no
go run ./cmd/rbaccheck -as $SA -verb get -resource secrets -n shop $R/orders-api-rbac.yaml $R/people-and-ci.yaml
# no
go run ./cmd/rbaccheck -as oidc:jane@acme.example -as-group oidc:shop-developers -verb get -resource pods/log -n shop $R/people-and-ci.yaml
# yes - RoleBinding shop/shop-developers-logs
go run ./cmd/rbaccheck -as oidc:jane@acme.example -as-group oidc:shop-developers -verb create -resource pods/exec -n shop $R/people-and-ci.yaml
# no
go run ./cmd/config-lister
# ERROR config-lister failed err="not running in a Pod (or automountServiceAccountToken is false and no token is projected):
# unable to load in-cluster configuration, KUBERNETES_SERVICE_HOST and KUBERNETES_SERVICE_PORT must be defined"
ruby ../scripts/check-yaml.rb
# 55 YAML documents parsed۴. اعمال و بررسی RBAC روی Cluster، مورد انتظار و اجرا نشده
cd .. # back from go/ to the snippet root: the paths below are relative to it
kubectl apply -f k8s/psa/namespaces.yaml -f k8s/rbac/orders-api-rbac.yaml -f k8s/rbac/people-and-ci.yaml
kubectl auth can-i list configmaps -n shop --as=system:serviceaccount:shop:orders-api
# yes
kubectl auth can-i get secrets -n shop --as=system:serviceaccount:shop:orders-api
# no
kubectl auth can-i --list -n shop --as=oidc:jane@acme.example --as-group=oidc:shop-developers
# a table of Resources / Non-Resource URLs / Resource Names / Verbs (shape as in the kubectl docs)
kubectl auth whoami
# ATTRIBUTE VALUE
# Username oidc:jane@acme.example
# Groups [oidc:shop-developers system:authenticated]۵. اجرای config-lister در Cluster و خرابکردن عمدی آن، مورد انتظار و اجرا نشده
# 0. The Job carries a placeholder digest (sha256:000...). Build go/Dockerfile (ENTRYPOINT
# /config-lister), push it to a registry you control, then pin the digest the push produced:
docker buildx build --platform linux/amd64,linux/arm64 -t ghcr.io/acme/config-lister:1.4.2 --push go/
DIGEST=$(docker buildx imagetools inspect ghcr.io/acme/config-lister:1.4.2 --format '{{json .Manifest.Digest}}' | tr -d '"')
sed -i.bak "s|sha256:0\{64\}|$DIGEST|" k8s/serviceaccount/config-lister-job.yaml
# 1. The API server is not a Pod, so orders-api-netpol.yaml names it by IP. 10.0.0.1/32 is a
# placeholder: put the address(es) of the "kubernetes" EndpointSlice in its ipBlock
# (whether ipBlock matches after Service NAT depends on the CNI; Cilium: use toEntities instead)
kubectl get endpointslices -n default -l kubernetes.io/service-name=kubernetes -o jsonpath='{.items[*].endpoints[*].addresses[*]}'
kubectl apply -f k8s/netpol/shop-default-deny.yaml -f k8s/netpol/orders-api-netpol.yaml
kubectl apply -f k8s/serviceaccount/config-lister-job.yaml
kubectl wait -n shop --for=condition=complete job/orders-api-config-check --timeout=60s
kubectl logs -n shop job/orders-api-config-check
# expected: a log line "INFO access review namespace=shop verb=list resource=configmaps allowed=true reason=..."
# then the names of the ConfigMaps labelled acme.io/flags=true; the Job completes
kubectl delete job -n shop orders-api-config-check
kubectl delete rolebinding -n shop orders-api-config-reader
kubectl apply -f k8s/serviceaccount/config-lister-job.yaml && kubectl logs -n shop job/orders-api-config-check -f
# expected: allowed=false, then: ServiceAccount may not list configmaps in "shop": check the RoleBinding;
# exit 1, the Job fails at once (backoffLimit: 0)
kubectl apply -f k8s/rbac/orders-api-rbac.yaml; kubectl delete job -n shop orders-api-config-check
kubectl delete networkpolicy -n shop orders-api # default deny stays, so egress to the API server is gone
kubectl apply -f k8s/serviceaccount/config-lister-job.yaml && kubectl logs -n shop job/orders-api-config-check -f
# expected: the new Pod's access review fails when the 10 s context deadline expires (no route to the API server)۶. Pod Security Admission و ValidatingAdmissionPolicy، مورد انتظار و اجرا نشده
kubectl label --dry-run=server --overwrite ns payments pod-security.kubernetes.io/enforce=restricted
# expected: "Warning: ..." lines naming the existing Pods that would violate restricted:latest;
# nothing is changed because of --dry-run=server
kubectl apply -f k8s/admission/vap-pod-rules.yaml
# a Pod that passes PSA restricted but uses the latest tag: only the VAP objects to it
sed 's|orders-api:1.4.2@sha256:[0-9a-f]*|orders-api:latest|' k8s/serviceaccount/orders-api-deployment.yaml \
| kubectl apply --dry-run=server -f -
# expected: accepted (binding is [Warn, Audit]) with a "Warning: Validation failed for ValidatingAdmissionPolicy
# 'acme-pod-rules.acme.io' ..." line naming the latest-tag image; after switching the binding to [Deny]: rejected۷. Audit، بررسی امضا و اسکن CIS، مورد انتظار و اجرا نشده
# self-managed control plane: watch for exec and Secret reads
sudo tail -f /var/log/kubernetes/audit/audit.log | jq -c 'select(.objectRef.subresource=="exec" or .objectRef.resource=="secrets")
| {user: .user.username, verb, ns: .objectRef.namespace, name: .objectRef.name, code: .responseStatus.code}'
# Kyverno: install it, apply the signature policy, then try a Pod that passes PSA restricted
# and the VAP, so the signature is the only thing that can reject it
helm repo add kyverno https://kyverno.github.io/kyverno/
helm install kyverno kyverno/kyverno --version 3.10.0 -n kyverno --create-namespace
# wait until the admission controller serves and its webhooks are registered, or the next
# applies fail with "failed calling webhook" instead of the policy decision
kubectl -n kyverno wait --for=condition=Available deploy/kyverno-admission-controller --timeout=120s
until kubectl get validatingwebhookconfigurations,mutatingwebhookconfigurations -o name | grep -q kyverno; do sleep 2; done
kubectl apply -f k8s/kyverno/imagevalidatingpolicy.yaml
sleep 5 # give Kyverno a moment to register the new policy in its webhook
kubectl apply -f k8s/kyverno/unsigned-test-pod.yaml
# expected: rejected by the Kyverno admission webhook with the policy's message
# "image is not signed by an acme release workflow"
cosign verify ghcr.io/acme/orders-api@sha256:<digest> \
--certificate-identity-regexp 'https://github.com/acme/.*/.github/workflows/release.yml@refs/tags/.*' \
--certificate-oidc-issuer https://token.actions.githubusercontent.com
# CIS Kubernetes Benchmark with kube-bench
kubectl apply -f https://raw.githubusercontent.com/aquasecurity/kube-bench/main/job.yaml
kubectl logs job/kube-bench
# expected: [PASS]/[FAIL]/[WARN] lines per CIS check and a summary per sectionبدفهمیهای رایج (Common misconceptions)
| باور | واقعیت |
|---|---|
| RBAC میتواند Deny بدهد | "Permissions are purely additive (there are no "deny" rules)"؛ منع محتوای شیء در Admission است |
| ClusterRole دسترسی سراسری میدهد | ClusterRoleBinding چنین میکند؛ RoleBinding به ClusterRole فقط همان Namespace را مجاز میکند |
get/list روی Secret فقطخواندنی و بیخطر است | "list on secrets will reveal the data attributes of any returned resources" |
| بدون مجوز Secret نمیشود Secret خواند | create روی Pod هر Secret را Mount و هر ServiceAccount را اجرا میکند |
edit نقش امن توسعهدهنده است | Secret میخواند و هر SA را اجرا میکند؛ view انتخاب امنتر است |
حذف Binding، دسترسی system:masters را لغو میکند | این گروه "bypasses all RBAC rights checks"؛ با این روش لغو نمیشود |
| میتوان User را از Kubernetes حذف کرد | شیء User وجود ندارد؛ گواهی تا انقضا معتبر است |
| توکن ServiceAccount بعد یک ساعت منقضی میشود | توکن تزریقشدهٔ Admission پیشفرض تا یک سال تمدید میشود؛ warnafter در 3,607 ثانیه |
| برنامهٔ بدون فراخوانی API نیاز به مراقبت از SA ندارد | توکن پیشفرض Mount میشود مگر automountServiceAccountToken: false |
| PSA enforce، Deployment را رد میکند | Enforce فقط روی Pod؛ Deployment فقط Warning و Audit annotation میگیرد |
failurePolicy: Ignore پیشفرض امن است | پیشفرض Fail است؛ Ignore در Webhook امنیتی Fail open است |
| VAP با ساختن مؤثر میشود | ValidatingAdmissionPolicyBinding لازم دارد |
| NetworkPolicy همیشه ترافیک را میبندد | فقط با CNI پشتیبان؛ وگرنه "no effect" |
| NetworkPolicyها بهترتیب بررسی میشوند | اجتماع افزایشی هستند؛ Egress و Ingress هر دو باید اجازه دهند |
| DNS با Default deny همچنان کار میکند | "A default deny-all egress policy also blocks DNS traffic" |
| Audit logging پیشفرض فعال است | بدون --audit-policy-file رخداد ندارید؛ در سرویس مدیریتشده هم فعالسازی لازم است |
| Namespace مرز سخت مستأجر است | kubelet، API server، CRD و Webhook مشترکاند؛ جداسازی سخت، Cluster مجازی یا جدا میخواهد |
برگهٔ تقلب (Cheat sheet)
| موضوع | به خاطر بسپارید |
|---|---|
| مسیر درخواست (Request flow) | Authentication با 401 → Authorization با 403 → Mutation → Schema → Validating admission → etcd؛ Audit کنار همه |
| احراز هویت (Authentication) | گواهی: CN کاربر و O گروه؛ OIDC id_token کوتاه با پیشوند Username؛ توکن SA؛ anonymous فقط سلامت |
| ServiceAccount | یکی برای هر workload؛ automountServiceAccountToken: false؛ Projected token حداقل 600 ثانیه؛ تازهسازی در 80 % |
| توکن | TokenRequest API، وابسته به Pod/Secret/Node، بررسی Audience؛ حذف Secretهای قدیمی kubernetes.io/service-account-token |
| اشیای RBAC | Role/ClusterRole قاعده دارند؛ RoleBinding یک Namespace، ClusterRoleBinding همهجا؛ roleRef تغییرناپذیر |
| قاعده | apiGroups × resources و pods/log، pods/exec × verbs؛ resourceNames؛ nonResourceURLs فقط ClusterRole؛ بدون * |
| نقش داخلی | view بدون Secret < edit با Secret و هر SA < admin با RBAC همان Namespace < cluster-admin اضطراری |
| افزایش امتیاز | escalate، bind، impersonate، create pods، nodes/proxy، serviceaccounts/token، تأیید CSR، Webhook config، patch namespaces، system:masters |
| بررسی | kubectl auth can-i ... --as=... --as-group=...، --list، auth whoami، SelfSubjectAccessReview در کد |
| هویت بار کاری (Workload identity) | IRSA / EKS Pod Identity / GKE WIF / Azure WI؛ تبادل توکن با اعتبارنامهٔ ابر؛ Egress متناسب Platform؛ GKE به 169.254.169.252:988 یا در Dataplane V2 به 169.254.169.254:80 نیاز دارد |
| PSA | pod-security.kubernetes.io/{enforce,audit,warn}[-version]؛ enforce فقط Pod؛ enforce-version ثابت؛ استثنای ثابت |
| Webhook | پیشفرض failurePolicy: Fail و Timeout برابر 10 ثانیه با بازهٔ 1-30؛ حذف kube-system و Namespace خودش؛ matchConditions |
| VAP | CEL داخل API server، نیازمند Binding؛ [Warn, Audit] → [Deny]؛ هرگز Deny+Warn |
| موتور | Kyverno ValidatingPolicy/ImageValidatingPolicy و ClusterPolicy قدیمی؛ Gatekeeper ConstraintTemplate و Constraint؛ dryrun → deny |
| امضا (Signature) | cosign Keyless در CI؛ بررسی Digest در Admission؛ mutateDigest |
| ممیزی (Audit) | اولین تطبیق؛ None/Metadata/Request/RequestResponse؛ Metadata برای Secret؛ هشدار exec و خواندن Secret |
| NetworkPolicy | Default deny هر دو جهت و DNS؛ تفاوت یک/دو ورودی from؛ ipBlock بیرونی؛ اجرای CNI الزامی |
| مقاومسازی (Hardening) | --authorization-mode=Node,RBAC، anonymous محدود، kubelet با Webhook برای authn/authz، readOnlyPort برابر 0، kube-bench |
| چندمستأجری (Tenancy) | بستهٔ Namespace شامل RBAC، PSA، NetworkPolicy، Quota؛ vCluster یا Cluster جدا برای جداسازی سخت |
خودآزمایی: پرسش و پاسخ (Self-check: questions & answers)
- حیاتی تقریباً در هر مصاحبه پرسیده میشود
- مهم پرتکرار؛ در سطح senior انتظار میرود
- تکمیلی عمق بیشتر؛ تمایز ایجاد میکند
۱ — Pipeline پیام deployments.apps "orders-api" is forbidden: User "system:serviceaccount:ci:deployer" cannot patch resource "deployments" میگیرد؛ کدام دروازه شکست خورده و چه باید تغییر کند؟ حیاتی
پاسخ
پاسخ: احراز هویت (Authentication) موفق بوده چون سرور نام کاربر را گفته؛ مجوز (Authorization) با ۴۰۳ شکست خورده چون هیچ Binding، patch روی deployments در گروه apps و Namespace مقصد را نمیدهد. در همان Namespace یک Role با patch و get، list، watch، create، update برای deployments در apps بسازید و با RoleBinding همان Namespace به SA بدهید. با kubectl auth can-i patch deployments.apps -n shop --as=system:serviceaccount:ci:deployer بررسی کنید؛ ClusterRoleBinding و cluster-admin لازم نیست. مسیر درخواست و اشیای RBAC.
۲ — چرا create روی Pod عملاً دسترسی به همهٔ Secret و ServiceAccountهای Namespace است و چه چیزی آسیب را محدود میکند؟ حیاتی
پاسخ
پاسخ: Pod spec، serviceAccountName و Volume را انتخاب میکند؛ سازنده هر Secret را Mount میکند، kubelet با هویت خودش آن را میخواند و کد با توکن هر SA اجرا میشود. تنظیم privileged حتی دسترسی Node میدهد. RBAC، Spec را نمیبیند؛ محدودیت از Namespace جدا برای سطح اعتماد، PSA restricted، Admission policy، Default-deny egress و ممیزی ساخت Pod میآید. مرز داخل Namespace، "should be considered weak"؛ راههای افزایش امتیاز.
۳ — تفاوت Role با RoleBinding، ClusterRole با RoleBinding و ClusterRole با ClusterRoleBinding چیست؟ حیاتی
پاسخ
پاسخ: Role و RoleBinding، قاعده را در یک Namespace تعریف و اعطا میکنند. ClusterRole و RoleBinding، مجموعهٔ قابل استفادهٔ مجدد مانند view یا edit را فقط در Namespace آن Binding میدهند. ClusterRole و ClusterRoleBinding در همهٔ Namespaceها، منابع سراسری و nonResourceURLs مجوز میدهند. حوزه (Scope) را Binding تعیین میکند، نه Kind نقش؛ اشیای RBAC.
۴ — برنامهٔ Laravel هرگز API را صدا نمیزند؛ کدام سه تنظیم مانع استفاده از API پس از اجرای کد مهاجم میشوند؟ حیاتی
پاسخ
پاسخ: ServiceAccount اختصاصی shop-web بدون RoleBinding؛ automountServiceAccountToken: false روی SA و Pod template تا فایل توکن نباشد؛ و NetworkPolicy با Default-deny egress که فقط DNS، MySQL و Redis را مجاز کند تا API server و Metadata endpoint ابر در دسترس نباشند. تست پس از استقرار، نبود فایل توکن و بیپاسخ بودن Port API را بررسی میکند. Laravel.
۵ — توکن Bound و Projected چه تفاوتی با Secret قدیمی دارد و --service-account-extend-token-expiration چه چیزی را عوض میکند؟ حیاتی
پاسخ
پاسخ: Secret قدیمی kubernetes.io/service-account-token، "don't expire and don't rotate". توکن Projected از TokenRequest API میآید، به Pod وابسته است و با حذفش باطل میشود، Audience و انقضا دارد؛ پیشفرض یک ساعت، حداقل ۶۰۰ ثانیه، و تازهسازی kubelet در ۸۰ درصد TTL. پیشفرض --service-account-extend-token-expiration=true توکن تزریقشدهٔ Admission را برای کلاینتی که فایل را بازخوانی نمیکند "up to 1 year" تمدید میکند؛ Payload مستند، exp − iat برابر ۳۶۵ روز و warnafter در ۳٬۶۰۷ ثانیه دارد. توکن Projectشده توسط خودتان تمدید نمیشود؛ ServiceAccount و بایتبهبایت توکن.
۶ — پس از Label با pod-security.kubernetes.io/enforce: restricted، Deployment پذیرفته شده ولی Pod ندارد؛ چرا و Rollout درست چه بود؟ مهم
پاسخ
پاسخ: Enforce فقط روی Pod اعمال میشود؛ Deployment پذیرفته و ساخت Pod توسط ReplicaSet با Event برابر FailedCreate رد میشود. ابتدا kubectl label --dry-run=server برای فهرست تخلفها، سپس warn و audit روی restricted با enforce روی baseline؛ Manifestها را اصلاح کنید. بعد enforce: restricted را با enforce-version ثابت فعال کنید؛ Pod Security Admission.
۷ — ارتقای Kyverno خراب شده و هر kubectl apply ده ثانیه معطل و سپس ناموفق میشود؛ سازوکار و راهحل فوری و پایدار چیست؟ مهم
پاسخ
پاسخ: با failurePolicy: Fail، یعنی پیشفرض API و تنظیم Fail closed، API server تا timeoutSeconds، پیشفرض ده ثانیه، منتظر Webhook میماند و در خطای تماس درخواست را رد میکند. اگر Namespace خود Engine هم Match شود، Podهایش دوباره ساخته نمیشوند. فوراً Deployment را بازیابی یا Webhook configuration را موقتاً حذف و بعد با GitOps برگردانید. برای رفع پایدار، kube-system و Namespace موتور را مستثنا کنید؛ matchConditions برای User سیستمی، چند Replica با PDB و Timeout کوتاه داشته باشید و قواعد ساده را به ValidatingAdmissionPolicy داخل Process ببرید؛ Admission webhook.
۸ — چه زمانی ValidatingAdmissionPolicy را به Kyverno یا Gatekeeper ترجیح میدهید و چه زمانی نه؟ مهم
پاسخ
پاسخ: وقتی قاعده عبارتی روی شیء، Namespace، Request و پارامتر اختیاری است، مانند Label اجباری، منع :latest، وجود Limits و غیر root، VAP در kube-apiserver اجرا میشود و Webhook کند یا قطعشونده ندارد؛ از [Warn, Audit] به [Deny] بروید. برای دادهٔ بیرونی مانند امضا و Registry lookup، Mutation یا Generation فراتر از MutatingAdmissionPolicy، گزارش پسزمینهٔ اشیای موجود و گردش کار استثنا از Engine استفاده کنید. ValidatingAdmissionPolicy و موتورهای سیاست.
۹ — چه راهبرد Audit اجازهٔ هشدار روی exec و خواندن Secret میدهد بدون اینکه مقدار Secret وارد لاگ شود؟ مهم
پاسخ
پاسخ: اولین Rule مطابق برنده است؛ با None برای Endpoint سلامت و Watch پرحجم سیستمی شروع کنید. سپس Metadata برای secrets، configmaps و serviceaccounts/token با هویت، Verb، Name و Response code؛ هرگز Body را ثبت نکنید؛ سطح Metadata برای pods/exec، pods/attach، pods/portforward و pods/ephemeralcontainers. برای تغییر RBAC و Admission configuration، RequestResponse؛ نوشتن workload، Request؛ و پیشفرض نهایی Metadata، با حذف RequestReceived. به SIEM بفرستید و روی منابع بالا و موج ۴۰۳ هشدار دهید؛ ثبت ممیزی.
۱۰ — پس از default-deny-all در shop همهٔ Podها "could not resolve host" میدهند؛ چه کم است و دام یک خط تیرهٔ YAML چیست؟ مهم
پاسخ
پاسخ: Default-deny egress، DNS را هم میبندد؛ برای همهٔ Podها خروجی به kube-dns در kube-system روی UDP و TCP پورت ۵۳ بدهید. در اجازهٔ Ingress controller، namespaceSelector و podSelector باید در یک ورودی from باشند تا فقط Podهای Controller در Namespace ورودی مجاز شوند. دو ورودی یعنی هر Pod آن Namespace یا Podهای دارای آن Label در این Namespace. اجرای NetworkPolicy توسط CNI را هم تأیید کنید؛ NetworkPolicy.
۱۱ — IRSA چگونه بدون Access key دسترسی Pod به S3 را میدهد و چه چیزی هنوز باید بسته شود؟ تکمیلی
پاسخ
پاسخ: SA با ARN نقش IAM Annotation میگیرد؛ Pod توکن Projected با Audience برابر sts.amazonaws.com میگیرد؛ AWS SDK، sts:AssumeRoleWithWebIdentity را صدا میزند. STS با کلیدهای عمومی OIDC discovery خوشه و Trust policy شامل Issuer، Audience و sub = system:serviceaccount:<ns>:<sa> توکن را بررسی و اعتبارنامهٔ کوتاه میدهد. در EKS اعتبارنامهٔ Metadata خود Node قابل دسترس میماند مگر Egress به 169.254.169.254 بسته شود؛ EKS Pod Identity بهجای آن Agent با آدرس Link-local برابر 169.254.170.23 دارد که باید باز بماند. در GKE آدرس Metadata باید باز باشد، چون Workload Identity از آن اعتبارنامه میدهد؛ GKE و Azure Workload Identity نیز بر پایهٔ تبادل توکناند. هویت بار کاری.
۱۲ — ابتدا کدام تنظیم kube-apiserver و kubelet را در Cluster خودمدیریتشده بررسی میکنید و ابزار سنجش CIS چیست؟ تکمیلی
پاسخ
پاسخ: در API server، --authorization-mode=Node,RBAC؛ در نبود Authorization config، Flag پیشفرض AlwaysAllow است. Anonymous فقط Endpoint سلامت؛ --audit-policy-file، --encryption-provider-config، --kubelet-certificate-authority، --profiling=false و NodeRestriction فعال باشند. در kubelet، Authentication ناشناس خاموش، Token authentication با Webhook، Authorization برابر Webhook و Read-only port برابر صفر؛ پیشفرض Flagهای مربوط مقادیر ناامناند. kube-bench بررسی CIS را بهشکل Job اجرا میکند؛ روی Cluster مدیریتشده فقط بررسی Node اعمال میشود؛ مقاومسازی.
۱۳ — توسعهدهنده Secret access ندارد ولی kubectl auth can-i create pods/exec -n payments پاسخ yes میدهد؛ چرا مهم است و چه مجوزی جایگزین میکنید؟ حیاتی
پاسخ
پاسخ: pods/exec فرمان را داخل کانتینر اجرا میکند؛ فرمان هرچه کانتینر بخواند، شامل Secret نصبشده، Env و توکن SA، را میخواند. این Subresource جداست و جایی صریح اعطا شده؛ با --list، Bindingها را بررسی کنید. برای عیبیابی معمول pods/log بدهید و exec را پشت گروه Break-glass با Impersonation و هشدار Audit روی pods/exec بگذارید؛ قاعدهها.
واژهنامه (Glossary)
| اصطلاح | معنا |
|---|---|
| احراز هویت (Authentication) | تشخیص فرستنده با Client certificate، Bearer token در OIDC یا ServiceAccount، یا Authenticating proxy؛ شکست 401 |
| مجوز (Authorization) | تصمیم دربارهٔ Verb روی Resource برای هویت احرازشده؛ Authorizer مرتب، Default deny، شکست 403 |
| کنترل پذیرش (Admission control) | Plugin و Webhook برای تغییر و اعتبارسنجی شیء پس از Authorization و پیش از ذخیره |
| مسیر درخواست (Request flow) | Authentication → Authorization → Mutating admission → Schema validation → Validating admission → etcd، همراه Audit |
| گواهی کلاینت (Client certificates) | X.509 امضاشده با CA؛ CN نام کاربر و O گروه است |
| OIDC | OpenID Connect؛ API server، id_token از IdP را بهعنوان Bearer token میپذیرد |
| AuthenticationConfiguration | فایل apiserver.config.k8s.io/v1 با --authentication-config برای JWT authenticator و anonymous؛ پایدار v1.34 |
system:anonymous / system:unauthenticated | کاربر و گروه درخواست بدون اعتبارنامه |
system:masters | گروه دورزنندهٔ همهٔ Authorization؛ پیشفرض دارای Binding به cluster-admin |
| ServiceAccount | هویت workload در Namespace؛ Username برابر system:serviceaccount:<ns>:<name> |
| توکن ServiceAccount (ServiceAccount token) | JWT امضاشده توسط API server برای شناسایی SA |
| توکن وابسته (Bound service account token) | وابسته به Pod، Secret یا Node؛ پس از حذف شیء نامعتبر |
| توکن درجشده در Volume ترکیبی (Projected token) | منبع serviceAccountToken در Projected volume؛ نوشته و تازهشده توسط kubelet |
| TokenRequest API | زیرمنبع serviceaccounts/token برای توکن محدود به زمان و Audience |
| automountServiceAccountToken | فیلد SA یا Pod؛ false مانع Volume پیشفرض؛ تنظیم Pod مقدم است |
kube-root-ca.crt | ConfigMap هر Namespace با CA bundle برای بررسی API server |
| کنترل دسترسی مبتنی بر نقش (RBAC) | API با rbac.authorization.k8s.io/v1؛ قواعد صرفاً افزایشی |
| Role / ClusterRole | مجموعهٔ قواعد در Namespace / سراسری |
| RoleBinding / ClusterRoleBinding | اعطای قواعد نقش به Subject در یک Namespace / همهجا |
| roleRef | نقش اعطاشده توسط Binding؛ تغییرناپذیر |
| فعلها (Verbs) | get list watch create update patch delete deletecollection؛ ویژه: bind، escalate، impersonate، approve |
| منبع و زیرمنبع (Resources and subresources) | نام جمع مانند pods و زیرمسیر مثل pods/log، pods/exec، deployments/scale |
resourceNames | محدودسازی به نام شیء؛ برای create سطح بالا و deletecollection نیست |
nonResourceURLs | مسیرهایی مثل /healthz و /metrics در قواعد ClusterRole |
| ClusterRole تجمیعی (Aggregated ClusterRole) | اجتماع قواعد ClusterRoleهای انتخابشده با aggregationRule |
| ClusterRole پیشفرض (Default ClusterRoles) | view، edit، admin، cluster-admin و نقشهای مؤلفه با system:*؛ هماهنگی خودکار |
kubectl auth can-i | CLI روی SelfSubjectAccessReview؛ --list همهٔ قواعد Namespace را نشان میدهد |
| ایفای هویت دیگر (Impersonation) | هدر Impersonate-* با --as و --as-group؛ نیازمند فعل impersonate |
| SelfSubjectAccessReview / SubjectAccessReview | پرسش از زنجیرهٔ Authorizer دربارهٔ خود / هر هویت |
| کمترین امتیاز (Least privilege) | کمترین فعل روی کمترین منبع در کمترین Namespace |
| فعلهای Escalate / bind | دورزدن کنترل منع اعطای مجوزی که خود فرد ندارد |
| Node authorizer | محدودکردن kubelet به اشیای مرتبط با Podهای Node خودش |
| NodeRestriction | Plugin پذیرش محدودکنندهٔ تغییرهای kubelet |
| هویت بار کاری (Workload identity) | تبادل Projected ServiceAccount token با اعتبارنامهٔ ابر |
| IRSA | IAM Roles for Service Accounts در EKS؛ OIDC provider و eks.amazonaws.com/role-arn |
| EKS Pod Identity | ارتباطهای EKS API و Agent DaemonSet بهجای OIDC provider |
| GKE Workload Identity | Federation برای GKE؛ Principal در PROJECT_ID.svc.id.goog |
| Azure Workload Identity | Entra Workload ID؛ Federated credential و Annotation/Label با azure.workload.identity/* |
| Pod Security Standards | سطوح تجمعی (Cumulative) privileged، baseline، restricted؛ هر سطح شامل محدودیتهای سطح قبلی است |
| Pod Security Admission | Plugin داخلی اعمال سطح با Label هر Namespace |
| حالتهای PSA (PSA modes) | enforce رد Pod، audit درج Annotation، warn هشدار کلاینت |
| استثناهای PSA (PSA exemptions) | Username، Runtime class و Namespace بدون هیچ بررسی؛ تنظیم ثابت |
| Admission webhooks | HTTPS callback ثبتشده با MutatingWebhookConfiguration / ValidatingWebhookConfiguration |
| failurePolicy | Fail پیشفرض، رد در خطای Webhook؛ Ignore ادامهٔ درخواست |
| matchConditions | پیشفیلتر CEL در Webhook و Policy؛ حداکثر 64 |
| ValidatingAdmissionPolicy | Validation با CEL داخل Process، پایدار v1.30؛ فقط همراه Binding مؤثر |
| MutatingAdmissionPolicy | Mutation با CEL داخل Process، Apply configuration یا JSON patch؛ پایدار v1.36 |
| CEL | Common Expression Language در VAP، MAP، CRD validation و Authentication config |
| Kyverno | Policy Engine بومی Kubernetes؛ ValidatingPolicy، ImageValidatingPolicy و ClusterPolicy قدیمی |
| OPA Gatekeeper | اجرای Rego از ConstraintTemplate با اعمال از طریق Constraint |
| ConstraintTemplate / Constraint | Rego و Schema در Gatekeeper / Instance (مصداق) آن با Match و پارامتر |
| cosign | ابزار Sigstore برای امضا و بررسی Artefact در OCI؛ Keyless با OIDC |
| بررسی امضای Image (Image signature verification) | بررسی وجود امضای معتبر روی Digest در Admission |
| سیاست ممیزی (Audit policy) | Policy در audit.k8s.io/v1؛ ارزیابی مرتب و تعیین سطح با اولین Match |
| سطح ممیزی (Audit levels) | None، Metadata، Request، RequestResponse |
| مرحلهٔ ممیزی (Audit stages) | RequestReceived، ResponseStarted، ResponseComplete، Panic |
| Backendهای ممیزی (Audit backends) | Log در فایل و Webhook با HTTP؛ حالت Blocking یا Batch |
| NetworkPolicy | Allow list لایهٔ L3/L4 برای Pod در networking.k8s.io/v1 با اجرای CNI |
| منع پیشفرض (Default deny) | Policy انتخابکنندهٔ همهٔ Podها بدون Rule؛ جداسازی جهتهای مشخص |
ipBlock | همتای CIDR در NetworkPolicy؛ برای آدرس خارج Cluster |
| CNI | افزونهٔ Container Network Interface مانند Calico، Cilium و CNI ابری؛ مجری NetworkPolicy |
| CiliumNetworkPolicy | Kind سیاست Cilium با HTTP/DNS در L7، toFQDNs و Entity |
| Calico GlobalNetworkPolicy | سیاست سراسری و مرتب Calico با Deny |
| رمزنگاری در حالت سکون (At rest) | رمزنگاری Secret در etcd با --encryption-provider-config؛ KMS توصیه میشود |
| CIS Kubernetes Benchmark | راهنمای توافقی تنظیم Kubernetes نسخهٔ 2.1.0 و گونههای مدیریتشده |
| kube-bench | ابزار Aqua Security برای اجرای بررسی CIS بهشکل Job |
| چندمستأجری (Multi-tenancy) | اشتراک Cluster میان تیم یا مشتری با کنترل جداسازی |
| مرز Namespace (Namespace boundary) | حوزهٔ RBAC، PSA، NetworkPolicy و Quota؛ مرز داخلی ضعیف، واحد اعتماد میان آنها |
| Namespace سلسلهمراتبی (Hierarchical namespaces) | الگوی HNC برای زیرNamespace وارث Policy؛ repo آرشیو شده |
| vCluster | Cluster مجازی؛ Control plane مستأجر در Namespace خوشهٔ میزبان |
| client-go | کتابخانهٔ Go برای Kubernetes API با k8s.io/client-go |
| تنظیم داخل خوشه (In-cluster config) | rest.InClusterConfig()؛ آدرس API از Env، توکن و CA از Mount مربوط به SA |
منابع (References)
- مفاهیم امنیت Kubernetes: overview https://kubernetes.io/docs/concepts/security/ — Pod Security Standards https://kubernetes.io/docs/concepts/security/pod-security-standards/ — Pod Security Admission https://kubernetes.io/docs/concepts/security/pod-security-admission/ — multi-tenancy https://kubernetes.io/docs/concepts/security/multi-tenancy/ — service accounts https://kubernetes.io/docs/concepts/security/service-accounts/ — controlling access https://kubernetes.io/docs/concepts/security/controlling-access/ — RBAC good practices https://kubernetes.io/docs/concepts/security/rbac-good-practices/ — Secrets good practices https://kubernetes.io/docs/concepts/security/secrets-good-practices/ — security checklist https://kubernetes.io/docs/concepts/security/security-checklist/
- مرجع کنترل دسترسی: authentication https://kubernetes.io/docs/reference/access-authn-authz/authentication/ — authorization https://kubernetes.io/docs/reference/access-authn-authz/authorization/ — RBAC https://kubernetes.io/docs/reference/access-authn-authz/rbac/ — user impersonation https://kubernetes.io/docs/reference/access-authn-authz/user-impersonation/ — admission controllers https://kubernetes.io/docs/reference/access-authn-authz/admission-controllers/ — dynamic admission control https://kubernetes.io/docs/reference/access-authn-authz/extensible-admission-controllers/ — ValidatingAdmissionPolicy https://kubernetes.io/docs/reference/access-authn-authz/validating-admission-policy/ — MutatingAdmissionPolicy https://kubernetes.io/docs/reference/access-authn-authz/mutating-admission-policy/ — ServiceAccount admin https://kubernetes.io/docs/reference/access-authn-authz/service-accounts-admin/ — Node authorization https://kubernetes.io/docs/reference/access-authn-authz/node/ — kubelet authn/authz https://kubernetes.io/docs/reference/access-authn-authz/kubelet-authn-authz/
- روشهای درست Admission webhook: https://kubernetes.io/docs/concepts/cluster-administration/admission-webhooks-good-practices/ — CEL in Kubernetes: https://kubernetes.io/docs/reference/using-api/cel/
- راهنماها: configure ServiceAccounts https://kubernetes.io/docs/tasks/configure-pod-container/configure-service-account/ — enforce PSA with namespace labels https://kubernetes.io/docs/tasks/configure-pod-container/enforce-standards-namespace-labels/ — PSA admission configuration https://kubernetes.io/docs/tasks/configure-pod-container/enforce-standards-admission-controller/ — migrate from PSP https://kubernetes.io/docs/tasks/configure-pod-container/migrate-from-psp/ — auditing https://kubernetes.io/docs/tasks/debug/debug-cluster/audit/ — encrypting data at rest https://kubernetes.io/docs/tasks/administer-cluster/encrypt-data/ — securing a cluster https://kubernetes.io/docs/tasks/administer-cluster/securing-a-cluster/ — accessing the API from a Pod https://kubernetes.io/docs/tasks/run-application/access-api-from-pod/
- شبکه: NetworkPolicy https://kubernetes.io/docs/concepts/services-networking/network-policies/ — NetworkPolicy API https://kubernetes.io/docs/reference/kubernetes-api/policy-resources/network-policy-v1/ — projected volumes https://kubernetes.io/docs/concepts/storage/projected-volumes/
- مرجع API و ابزار: TokenRequest https://kubernetes.io/docs/reference/kubernetes-api/authentication-resources/token-request-v1/ — ValidatingAdmissionPolicy API https://kubernetes.io/docs/reference/kubernetes-api/policy-resources/validating-admission-policy-v1/ —
kubectl auth can-ihttps://kubernetes.io/docs/reference/kubectl/generated/kubectl_auth/kubectl_auth_can-i/ —kubectl auth whoamihttps://kubernetes.io/docs/reference/kubectl/generated/kubectl_auth/kubectl_auth_whoami/ —kubectl create tokenhttps://kubernetes.io/docs/reference/kubectl/generated/kubectl_create/kubectl_create_token/ — kube-apiserver https://kubernetes.io/docs/reference/command-line-tools-reference/kube-apiserver/ — kubelet https://kubernetes.io/docs/reference/command-line-tools-reference/kubelet/ — KubeletConfiguration https://kubernetes.io/docs/reference/config-api/kubelet-config.v1beta1/ — well-known labels https://kubernetes.io/docs/reference/labels-annotations-taints/ — releases https://kubernetes.io/releases/ - وبلاگ Kubernetes: RBAC GA in 1.8 https://kubernetes.io/blog/2017/10/using-rbac-generally-available-18/ — PSA stable in 1.25 https://kubernetes.io/blog/2022/08/25/pod-security-admission-stable/ — VAP GA in 1.30 https://kubernetes.io/blog/2024/04/24/validating-admission-policy-ga/
- کد منبع با نسخهٔ ثابت: RBAC
RuleAllowshttps://raw.githubusercontent.com/kubernetes/kubernetes/v1.34.1/plugin/pkg/auth/authorizer/rbac/rbac.go — evaluation helpers https://raw.githubusercontent.com/kubernetes/kubernetes/v1.34.1/pkg/apis/rbac/v1/evaluation_helpers.go — client-gorest.InClusterConfighttps://raw.githubusercontent.com/kubernetes/client-go/v0.34.1/rest/config.go — clientset https://raw.githubusercontent.com/kubernetes/client-go/v0.34.1/kubernetes/clientset.go — fake clientset https://raw.githubusercontent.com/kubernetes/client-go/v0.34.1/kubernetes/fake/clientset_generated.go — testing reactors https://raw.githubusercontent.com/kubernetes/client-go/v0.34.1/testing/fake.go — API errors https://raw.githubusercontent.com/kubernetes/apimachinery/v0.34.1/pkg/api/errors/errors.go — sigs.k8s.io/yaml https://raw.githubusercontent.com/kubernetes-sigs/yaml/v1.6.0/yaml.go — in-cluster example https://raw.githubusercontent.com/kubernetes/client-go/master/examples/in-cluster-client-configuration/main.go - Kyverno: policy types https://kyverno.io/docs/policy-types/ — ValidatingPolicy https://kyverno.io/docs/policy-types/validating-policy/ — ImageValidatingPolicy https://kyverno.io/docs/policy-types/image-validating-policy/ — ClusterPolicy https://kyverno.io/docs/policy-types/cluster-policy/ — validate rules https://kyverno.io/docs/policy-types/cluster-policy/validate/ — verify images https://kyverno.io/docs/policy-types/cluster-policy/verify-images/ — Sigstore https://kyverno.io/docs/policy-types/cluster-policy/verify-images/sigstore/ — installation https://kyverno.io/docs/installation/ — policy library https://github.com/kyverno/policies
- OPA Gatekeeper: docs https://open-policy-agent.github.io/gatekeeper/website/docs/ — how to use https://open-policy-agent.github.io/gatekeeper/website/docs/howto/ — audit https://open-policy-agent.github.io/gatekeeper/website/docs/audit/ — failing closed https://open-policy-agent.github.io/gatekeeper/website/docs/failing-closed/ — OPA versions https://open-policy-agent.github.io/gatekeeper/website/docs/opa-versions/ — library https://github.com/open-policy-agent/gatekeeper-library
- Sigstore: overview https://docs.sigstore.dev/about/overview/ — signing containers https://docs.sigstore.dev/cosign/signing/signing_with_containers/ — verifying https://docs.sigstore.dev/cosign/verifying/verify/
- Cilium: policy https://docs.cilium.io/en/stable/security/policy/ — منابع لایهٔ ۷ و لایهٔ ۳ https://raw.githubusercontent.com/cilium/cilium/main/Documentation/security/policy/layer7.rst and https://raw.githubusercontent.com/cilium/cilium/main/Documentation/security/policy/layer3.rst — overview https://docs.cilium.io/en/stable/overview/intro/
- Calico: network policy https://docs.tigera.io/calico/latest/network-policy/ — Calico policy https://docs.tigera.io/calico/latest/network-policy/get-started/calico-policy/calico-network-policy — Kubernetes policy https://docs.tigera.io/calico/latest/network-policy/get-started/kubernetes-policy/kubernetes-network-policy
- CIS و kube-bench: CIS Kubernetes Benchmark https://www.cisecurity.org/benchmark/kubernetes — kube-bench https://github.com/aquasecurity/kube-bench — running kube-bench https://github.com/aquasecurity/kube-bench/blob/main/docs/running.md
- هویت بار کاری: IRSA https://docs.aws.amazon.com/eks/latest/userguide/iam-roles-for-service-accounts.html — configure IRSA https://docs.aws.amazon.com/eks/latest/userguide/associate-service-account-role.html — EKS Pod Identity https://docs.aws.amazon.com/eks/latest/userguide/pod-identities.html — EKS access entries https://docs.aws.amazon.com/eks/latest/userguide/access-entries.html — GKE Workload Identity https://cloud.google.com/kubernetes-engine/docs/concepts/workload-identity and https://cloud.google.com/kubernetes-engine/docs/how-to/workload-identity — Azure Workload Identity https://learn.microsoft.com/en-us/azure/aks/workload-identity-overview and https://azure.github.io/azure-workload-identity/docs/ — GitHub Actions OIDC https://docs.github.com/en/actions/security-for-github-actions/security-hardening-your-deployments/about-security-hardening-with-openid-connect
- ابزارهای چندمستأجری: Hierarchical Namespace Controller (archived) https://github.com/kubernetes-retired/hierarchical-namespaces — vCluster https://www.vcluster.com/docs/vcluster/introduction/what-are-virtual-clusters and https://github.com/loft-sh/vcluster
- Audit مدیریتشده: EKS control-plane logging https://docs.aws.amazon.com/eks/latest/userguide/control-plane-logs.html — GKE audit logging https://cloud.google.com/kubernetes-engine/docs/how-to/audit-logging — AKS monitoring reference https://learn.microsoft.com/en-us/azure/aks/monitor-aks-reference
- ابزارهای RBAC: kubectl-who-can https://github.com/aquasecurity/kubectl-who-can — rakkess https://github.com/corneliusweig/rakkess — client-go informers factory https://raw.githubusercontent.com/kubernetes/client-go/v0.34.1/informers/factory.go — clientcmd https://raw.githubusercontent.com/kubernetes/client-go/v0.34.1/tools/clientcmd/client_config.go — client-go v0.34.1 go.mod https://proxy.golang.org/k8s.io/client-go/@v/v0.34.1.mod and v0.35.0 https://proxy.golang.org/k8s.io/client-go/@v/v0.35.0.mod — buildx imagetools inspect https://docs.docker.com/reference/cli/docker/buildx/imagetools/inspect/
- درخواست و Proxy مورد اعتماد در Laravel 13: https://laravel.com/docs/13.x/requests
- مرتبط: Argo CD RBAC https://argo-cd.readthedocs.io/en/stable/operator-manual/rbac/ — Falco https://github.com/falcosecurity/falco — Laravel 13 deployment https://laravel.com/docs/13.x/deployment