# Security Fundamentals

## Konsep Dasar Keamanan Kubernetes

### Zero Trust Security Model

Kubernetes mengadopsi model "Zero Trust" dimana tidak ada kepercayaan default, semua komponen harus diverifikasi.

```
┌─────────────────┐    ┌──────────────────┐    ┌─────────────────┐
│   API Server    │◀───│  Authentication  │◀───│   User/Service  │
│                 │    │                  │    │                 │
│ • RBAC          │    │ • Tokens         │    │ • kubectl       │
│ • Admission     │    │ • Certificates   │    │ • Service Acc   │
│ • Audit Log     │    │ • Webhook        │    │ • OIDC          │
└─────────────────┘    └──────────────────┘    └─────────────────┘
```

### Defense in Depth

Multi-layer security approach untuk melindungi cluster:

1. **Infrastructure Layer** - Node security, network isolation
2. **Container Layer** - Image scanning, runtime security
3. **Cluster Layer** - RBAC, Network Policies, Secrets management
4. **Application Layer** - Pod security, admission controllers

## Authentication & Authorization

### Authentication Methods

#### X.509 Client Certificates

```bash
# Generate client certificate
openssl genrsa -out user.key 2048
openssl req -new -key user.key -out user.csr -subj "/CN=developer/O=dev-team"
openssl x509 -req -in user.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out user.crt -days 365

# Configure kubectl
kubectl config set-credentials developer \
  --client-certificate=user.crt \
  --client-key=user.key
kubectl config set-context dev-context \
  --cluster=kubernetes \
  --user=developer
kubectl config use-context dev-context
```

#### Service Account Tokens

```yaml
apiVersion: v1
kind: ServiceAccount
metadata:
  name: api-service-account
  namespace: production
  annotations:
    kubernetes.io/service-account.name: "api-service-account"
---
apiVersion: v1
kind: Secret
metadata:
  name: api-service-account-token
  namespace: production
  annotations:
    kubernetes.io/service-account.name: "api-service-account"
type: kubernetes.io/service-account-token
```

#### OIDC Integration

```yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: oidc-config
  namespace: kube-system
data:
  oidc-config.yaml: |
    oidc:
      issuer-url: "https://your-oidc-provider.com"
      client-id: "kubernetes-client"
      username-claim: "email"
      groups-claim: "groups"
      required-claim: "iss"
      extra-scopes: "profile,email"
```

### Role-Based Access Control (RBAC)

#### Role dan RoleBinding

```yaml
# Role untuk namespace tertentu
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  namespace: development
  name: developer-role
rules:
- apiGroups: [""]
  resources: ["pods", "services", "configmaps"]
  verbs: ["get", "list", "watch", "create", "update", "patch", "delete"]
- apiGroups: ["apps"]
  resources: ["deployments", "replicasets"]
  verbs: ["get", "list", "watch", "create", "update", "patch", "delete"]
---
# Bind role ke user/service account
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: developer-binding
  namespace: development
subjects:
- kind: User
  name: "developer@example.com"
  apiGroup: rbac.authorization.k8s.io
- kind: ServiceAccount
  name: "dev-service-account"
  namespace: development
roleRef:
  kind: Role
  name: developer-role
  apiGroup: rbac.authorization.k8s.io
```

#### ClusterRole dan ClusterRoleBinding

```yaml
# Cluster-wide permissions
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: cluster-admin-role
rules:
- apiGroups: [""]
  resources: ["nodes", "namespaces", "persistentvolumes"]
  verbs: ["get", "list", "watch"]
- apiGroups: ["storage.k8s.io"]
  resources: ["storageclasses"]
  verbs: ["get", "list", "watch"]
- apiGroups: ["rbac.authorization.k8s.io"]
  resources: ["roles", "rolebindings", "clusterroles", "clusterrolebindings"]
  verbs: ["get", "list", "watch", "create", "update", "patch", "delete"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: cluster-admin-binding
subjects:
- kind: User
  name: "admin@example.com"
  apiGroup: rbac.authorization.k8s.io
roleRef:
  kind: ClusterRole
  name: cluster-admin-role
  apiGroup: rbac.authorization.k8s.io
```

#### Aggregated ClusterRoles

```yaml
# Base role untuk application developers
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: app-developer-base
  labels:
    rbac.example.com/aggregate-to-app-developer: "true"
rules:
- apiGroups: [""]
  resources: ["pods", "services", "configmaps", "secrets"]
  verbs: ["get", "list", "watch", "create", "update", "patch", "delete"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: app-developer
  aggregationRule:
    clusterRoleSelectors:
    - matchLabels:
        rbac.example.com/aggregate-to-app-developer: "true"
rules: []  # Rules are aggregated from matching cluster roles
```

### RBAC Best Practices

#### Principle of Least Privilege

```yaml
# Minimal permissions for CI/CD service account
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  namespace: production
  name: cicd-deployer
rules:
- apiGroups: ["apps"]
  resources: ["deployments"]
  verbs: ["get", "list", "watch", "update", "patch"]  # No create/delete
- apiGroups: [""]
  resources: ["pods"]
  verbs: ["get", "list", "watch"]  # Read-only for debugging
- apiGroups: [""]
  resources: ["configmaps"]
  verbs: ["get", "list", "watch", "update", "patch"]
```

#### Environment-Specific Roles

```yaml
# Development environment - more permissive
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  namespace: development
  name: dev-full-access
rules:
- apiGroups: ["*"]
  resources: ["*"]
  verbs: ["*"]
---
# Production environment - restricted
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  namespace: production
  name: prod-restricted-access
rules:
- apiGroups: [""]
  resources: ["pods", "services"]
  verbs: ["get", "list", "watch"]  # Read-only
- apiGroups: ["apps"]
  resources: ["deployments"]
  verbs: ["get", "list", "watch"]  # Read-only, changes via CI/CD only
```

## Network Security

### Network Policies

#### Basic Network Policy

```yaml
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: frontend-network-policy
  namespace: production
spec:
  podSelector:
    matchLabels:
      app: frontend
  policyTypes:
  - Ingress
  - Egress
  ingress:
  - from:
    - podSelector:
        matchLabels:
          app: backend
    - namespaceSelector:
        matchLabels:
          name: monitoring
    ports:
    - protocol: TCP
      port: 80
  egress:
  - to:
    - podSelector:
        matchLabels:
          app: backend
    ports:
    - protocol: TCP
      port: 8080
  - to: []
    ports:
    - protocol: TCP
      port: 53
    - protocol: UDP
      port: 53
```

#### Multi-Tier Network Policy

```yaml
# Database tier - most restrictive
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: database-network-policy
  namespace: production
spec:
  podSelector:
    matchLabels:
      tier: database
  policyTypes:
  - Ingress
  - Egress
  ingress:
  - from:
    - podSelector:
        matchLabels:
          tier: backend
    ports:
    - protocol: TCP
      port: 5432
  egress:
  - to: []  # Allow DNS
    ports:
    - protocol: TCP
      port: 53
    - protocol: UDP
      port: 53
---
# Backend tier
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: backend-network-policy
  namespace: production
spec:
  podSelector:
    matchLabels:
      tier: backend
  policyTypes:
  - Ingress
  - Egress
  ingress:
  - from:
    - podSelector:
        matchLabels:
          tier: frontend
    ports:
    - protocol: TCP
      port: 8080
  - from:
    - namespaceSelector:
        matchLabels:
          name: monitoring
    ports:
    - protocol: TCP
      port: 9090
  egress:
  - to:
    - podSelector:
        matchLabels:
          tier: database
    ports:
    - protocol: TCP
      port: 5432
  - to: []
    ports:
    - protocol: TCP
      port: 53
    - protocol: UDP
      port: 53
```

#### Namespace Isolation

```yaml
# Default deny all traffic in namespace
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: default-deny-all
  namespace: production
spec:
  podSelector: {}
  policyTypes:
  - Ingress
  - Egress
---
# Allow same namespace communication
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: allow-same-namespace
  namespace: production
spec:
  podSelector: {}
  policyTypes:
  - Ingress
  - Egress
  ingress:
  - from:
    - podSelector: {}
  egress:
  - to:
    - podSelector: {}
```

### Service Mesh Security (Basic)

#### Istio Authentication Policy

```yaml
apiVersion: authentication.istio.io/v1alpha1
kind: Policy
metadata:
  name: default
  namespace: production
spec:
  peers:
  - mtls: {}
---
apiVersion: networking.istio.io/v1alpha3
kind: DestinationRule
metadata:
  name: default
  namespace: production
spec:
  host: "*.production.svc.cluster.local"
  trafficPolicy:
    tls:
      mode: ISTIO_MUTUAL
```

## Secrets Management

### Kubernetes Secrets

#### Secret Types

```yaml
# Opaque secret (generic)
apiVersion: v1
kind: Secret
metadata:
  name: app-secrets
  namespace: production
type: Opaque
data:
  database-url: cG9zdGdyZXNxbDovL3VzZXI6cGFzc0BkYi5leGFtcGxlLmNvbS9hcHBkYg==
  api-key: YXBpa2V5dmFsdWUxMjM0NTY3ODkw
---
# TLS secret
apiVersion: v1
kind: Secret
metadata:
  name: tls-cert
  namespace: production
type: kubernetes.io/tls
data:
  tls.crt: LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0t...
  tls.key: LS0tLS1CRUdJTiBQUklWQVRFIEtFWS0tLS0t...
---
# Docker registry secret
apiVersion: v1
kind: Secret
metadata:
  name: docker-registry
  namespace: production
type: kubernetes.io/dockerconfigjson
data:
  .dockerconfigjson: eyJhdXRocyI6eyJyZWdpc3RyeS5leGFtcGxlLmNvbSI6eyJ1c2VybmFtZSI6InVzZXIiLCJwYXNzd29yZCI6InBhc3MiLCJhdXRoIjoiZFhObGNqcHdZWE56In19fQ==
```

#### Secret Management Best Practices

```yaml
# Use secret as environment variables
apiVersion: v1
kind: Pod
metadata:
  name: secure-app
  namespace: production
spec:
  containers:
  - name: app
    image: myapp:v1.0.0
    env:
    - name: DATABASE_URL
      valueFrom:
        secretKeyRef:
          name: app-secrets
          key: database-url
    - name: API_KEY
      valueFrom:
        secretKeyRef:
          name: app-secrets
          key: api-key
---
# Mount secret as volume
apiVersion: v1
kind: Pod
metadata:
  name: secure-app-vol
  namespace: production
spec:
  containers:
  - name: app
    image: myapp:v1.0.0
    volumeMounts:
    - name: secret-volume
      mountPath: /etc/secrets
      readOnly: true
  volumes:
  - name: secret-volume
    secret:
      secretName: app-secrets
      items:
      - key: database-url
        path: database-url.txt
      - key: api-key
        path: api-key.txt
```

### External Secret Management

#### HashiCorp Vault Integration

```yaml
apiVersion: v1
kind: Secret
metadata:
  name: vault-secret
  namespace: production
  annotations:
    vault.hashicorp.com/agent-inject: "true"
    vault.hashicorp.com/role: "app-role"
    vault.hashicorp.com/agent-inject-secret-database: "secret/data/app/database"
    vault.hashicorp.com/agent-inject-template-database: |
      {{- with secret "secret/data/app/database" -}}
      export DB_HOST="{{ .Data.data.host }}"
      export DB_USER="{{ .Data.data.username }}"
      export DB_PASS="{{ .Data.data.password }}"
      {{- end }}
type: Opaque
```

#### External Secrets Operator

```yaml
apiVersion: external-secrets.io/v1beta1
kind: SecretStore
metadata:
  name: vault-store
  namespace: production
spec:
  provider:
    vault:
      server: "https://vault.example.com"
      path: "secret"
      version: "v2"
      auth:
        kubernetes:
          mountPath: "kubernetes"
          role: "external-secrets"
---
apiVersion: external-secrets.io/v1beta1
kind: ExternalSecret
metadata:
  name: database-credentials
  namespace: production
spec:
  refreshInterval: 1h
  secretStoreRef:
    name: vault-store
    kind: SecretStore
  target:
    name: database-credentials
    creationPolicy: Owner
  data:
  - secretKey: username
    remoteRef:
      key: app/database
      property: username
  - secretKey: password
    remoteRef:
      key: app/database
      property: password
```

## Pod Security

### Security Context

#### Pod-level Security Context

```yaml
apiVersion: v1
kind: Pod
metadata:
  name: secure-pod
  namespace: production
spec:
  securityContext:
    runAsNonRoot: true
    runAsUser: 1000
    runAsGroup: 3000
    fsGroup: 2000
    seccompProfile:
      type: RuntimeDefault
  containers:
  - name: app
    image: myapp:v1.0.0
    securityContext:
      allowPrivilegeEscalation: false
      readOnlyRootFilesystem: true
      capabilities:
        drop:
        - ALL
      volumeMounts:
      - name: tmp-volume
        mountPath: /tmp
  volumes:
  - name: tmp-volume
    emptyDir: {}
```

#### Container-level Security Context

```yaml
apiVersion: v1
kind: Pod
metadata:
  name: secure-container
  namespace: production
spec:
  containers:
  - name: app
    image: myapp:v1.0.0
    securityContext:
      runAsUser: 1000
      runAsGroup: 3000
      allowPrivilegeEscalation: false
      readOnlyRootFilesystem: true
      capabilities:
        drop:
        - ALL
        - NET_RAW
      privileged: false
      seLinuxOptions:
        level: "s0:c123,c456"
    volumeMounts:
    - name: cache-volume
      mountPath: /var/cache/app
  - name: sidecar
    image: sidecar:v1.0.0
    securityContext:
      runAsUser: 2000
      allowPrivilegeEscalation: false
      readOnlyRootFilesystem: true
      capabilities:
        drop:
        - ALL
```

### Pod Security Standards

#### Pod Security Admission

```yaml
apiVersion: v1
kind: Namespace
metadata:
  name: production
  labels:
    pod-security.kubernetes.io/enforce: restricted
    pod-security.kubernetes.io/audit: restricted
    pod-security.kubernetes.io/warn: restricted
    pod-security.kubernetes.io/enforce-version: v1.24
    pod-security.kubernetes.io/audit-version: v1.24
    pod-security.kubernetes.io/warn-version: v1.24
---
apiVersion: v1
kind: Namespace
metadata:
  name: development
  labels:
    pod-security.kubernetes.io/enforce: baseline
    pod-security.kubernetes.io/audit: restricted
    pod-security.kubernetes.io/warn: restricted
```

#### Pod Security Policy (Legacy - for older clusters)

```yaml
apiVersion: policy/v1beta1
kind: PodSecurityPolicy
metadata:
  name: restricted-psp
spec:
  privileged: false
  allowPrivilegeEscalation: false
  requiredDropCapabilities:
    - ALL
  volumes:
    - 'configMap'
    - 'emptyDir'
    - 'projected'
    - 'secret'
    - 'downwardAPI'
    - 'persistentVolumeClaim'
  runAsUser:
    rule: 'MustRunAsNonRoot'
  seLinux:
    rule: 'RunAsAny'
  fsGroup:
    rule: 'RunAsAny'
```

## Admission Controllers

### ValidatingAdmissionWebhook

#### Security Validation Webhook

```yaml
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingWebhookConfiguration
metadata:
  name: security-validator
webhooks:
- name: security.validator.io
  clientConfig:
    service:
      name: security-validator-service
      namespace: security-system
      path: "/validate"
  rules:
  - operations: ["CREATE", "UPDATE"]
    apiGroups: [""]
    apiVersions: ["v1"]
    resources: ["pods"]
  - operations: ["CREATE", "UPDATE"]
    apiGroups: ["apps"]
    apiVersions: ["v1"]
    resources: ["deployments"]
  admissionReviewVersions: ["v1", "v1beta1"]
  sideEffects: None
  failurePolicy: Fail
```

#### OPA Gatekeeper Policies

```yaml
apiVersion: templates.gatekeeper.sh/v1
kind: ConstraintTemplate
metadata:
  name: k8srequiredlabels
spec:
  crd:
    spec:
      names:
        kind: K8sRequiredLabels
      validation:
        openAPIV3Schema:
          type: object
          properties:
            labels:
              type: array
              items:
                type: string
  targets:
    - target: admission.k8s.gatekeeper.sh
      rego: |
        package k8srequiredlabels
        violation[{"msg": msg, "details": {"missing_labels": missing}}] {
          provided := {label | input.review.object.metadata.labels[label]}
          required := {label | label := input.parameters.labels[_]}
          missing := required - provided
          count(missing) > 0
          msg := sprintf("missing required labels: %v", [missing])
        }
---
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sRequiredLabels
metadata:
  name: all-must-have-owner
spec:
  enforcementAction: deny
  match:
    kinds:
      - apiGroups: [""]
        kinds: ["Pod"]
      - apiGroups: ["apps"]
        kinds: ["Deployment"]
  parameters:
    labels: ["owner", "environment"]
```

### MutatingAdmissionWebhook

#### Security Hardening Webhook

```yaml
apiVersion: admissionregistration.k8s.io/v1
kind: MutatingWebhookConfiguration
metadata:
  name: security-mutator
webhooks:
- name: security.mutator.io
  clientConfig:
    service:
      name: security-mutator-service
      namespace: security-system
      path: "/mutate"
  rules:
  - operations: ["CREATE"]
    apiGroups: [""]
    apiVersions: ["v1"]
    resources: ["pods"]
  admissionReviewVersions: ["v1", "v1beta1"]
  sideEffects: None
  failurePolicy: Fail
```

## Audit Logging

### Audit Policy Configuration

```yaml
apiVersion: audit.k8s.io/v1
kind: Policy
rules:
- level: Metadata
  namespaces: ["kube-system", "kube-public", "kube-node-lease"]
  resources:
  - group: ""
    resources: ["secrets", "configmaps"]
- level: Request
  namespaces: ["production"]
  resources:
  - group: ""
    resources: ["pods"]
  verbs: ["create", "delete", "update"]
- level: Metadata
  namespaces: ["development", "staging"]
  resources:
  - group: ["apps"]
    resources: ["deployments", "replicasets"]
- level: None
  users: ["system:kube-proxy"]
  verbs: ["watch"]
  resources:
  - group: ""
    resources: ["endpoints", "services"]
- level: RequestResponse
  resources:
  - group: ""
    resources: ["secrets"]
  namespaces: ["production"]
```

### Audit Log Analysis

```bash
# Search for secret access
grep "resource=secrets" /var/log/kubernetes/audit.log | grep "production"

# Find privileged operations
grep "privileged=true" /var/log/kubernetes/audit.log

# Analyze failed authentications
grep "user=anonymous" /var/log/kubernetes/audit.log | grep "stage=ResponseStarted"

# Monitor RBAC violations
grep "RBAC" /var/log/kubernetes/audit.log | jq -r '.stage' | sort | uniq -c
```

## Security Monitoring

### Security Metrics dan Alerts

#### Prometheus Security Rules

```yaml
apiVersion: monitoring.coreos.com/v1
kind: PrometheusRule
metadata:
  name: kubernetes-security-rules
  namespace: monitoring
spec:
  groups:
  - name: kubernetes.security
    rules:
    - alert: K8sAnonymousAccess
      expr: increase(kubernetes_audit_requests_total{user="anonymous"}[5m]) > 0
      for: 0m
      labels:
        severity: critical
      annotations:
        summary: "Anonymous access detected in Kubernetes"
        description: "Anonymous user accessed Kubernetes API"

    - alert: K8sPrivilegedPod
      expr: kube_pod_info{privileged_pod="true"} > 0
      for: 0m
      labels:
        severity: warning
      annotations:
        summary: "Privileged pod detected"
        description: "Pod {{ $labels.pod }} is running as privileged"

    - alert: K8sRBACViolation
      expr: increase(kubernetes_audit_requests_total{verb="create",user!="system:serviceaccount:kube-system:*"}[5m]) > 10
      for: 5m
      labels:
        severity: warning
      annotations:
        summary: "High rate of resource creation"
        description: "User {{ $labels.user }} created {{ $value }} resources in 5 minutes"
```

#### Falco Rules for Security

```yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: falco-rules
  namespace: falco
data:
  kubernetes_security_rules.yaml: |
    - rule: Detect privileged container
      desc: Detect privileged container started in Kubernetes
      condition: >
        spawned_process and
        container and
        kubernetes.pod.name starts with "privileged-" and
        kubernetes.namespace.name = "production"
      output: >
        Privileged container started (user=%user.name command=%proc.cmdline
        container=%container.name pod=%kubernetes.pod.name namespace=%kubernetes.namespace.name)
      priority: WARNING
      tags: [kubernetes, security]

    - rule: Unauthorized mount access
      desc: Detect unauthorized mount access in container
      condition: >
        open_read and
        container and
        fd.name contains "/etc/kubernetes" and
        not proc.name in (nginx, apache, envoy)
      output: >
        Unauthorized access to Kubernetes files (user=%user.name process=%proc.name
        file=%fd.name container=%container.name)
      priority: CRITICAL
      tags: [kubernetes, security]
```

## Security Best Practices

### Cluster Hardening Checklist

```yaml
# Enable RBAC
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: restrict-default-account
subjects:
- kind: ServiceAccount
  name: default
  namespace: default
roleRef:
  kind: ClusterRole
  name: restricted
  apiGroup: rbac.authorization.k8s.io
---
# Network policies for default deny
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: default-deny-all-ingress
  namespace: default
spec:
  podSelector: {}
  policyTypes:
  - Ingress
---
# Pod security standards
apiVersion: v1
kind: Namespace
metadata:
  name: secure-namespace
  labels:
    pod-security.kubernetes.io/enforce: restricted
    pod-security.kubernetes.io/audit: restricted
    pod-security.kubernetes.io/warn: restricted
```

### Regular Security Tasks

#### Security Scan Commands

```bash
# Image vulnerability scanning
trivy image myapp:v1.0.0
clair-scanner myapp:v1.0.0

# Cluster security audit
kubectl auth can-i --list --as=system:serviceaccount:production:app-sa
kubectl get rolebindings,clusterrolebindings --all-namespaces

# Network policy verification
kubectl get networkpolicy --all-namespaces
kubectl get pods -n production -o wide

# Secret security check
kubectl get secrets --all-namespaces -o json | jq '.items[].data | keys'
kubectl get pods --all-namespaces -o json | jq '.items[].spec.containers[].env[] | select(.valueFrom.secretKeyRef)'
```

#### Security Monitoring Setup

```yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: security-monitoring
  namespace: monitoring
data:
  security-config.yaml: |
    monitoring:
      rbac_changes:
        enabled: true
        alert_threshold: 5 per hour
      secret_access:
        enabled: true
        log_level: info
      network_policy_violations:
        enabled: true
        alert_on_violation: true
      privileged_containers:
        enabled: true
        auto_quarantine: false
```

***

## 🚀 **Production Security Setup**

### Complete Production Security Configuration

```yaml
# Namespace with security policies
apiVersion: v1
kind: Namespace
metadata:
  name: production
  labels:
    pod-security.kubernetes.io/enforce: restricted
    pod-security.kubernetes.io/audit: restricted
    pod-security.kubernetes.io/warn: restricted
---
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: prod-deny-all
  namespace: production
spec:
  podSelector: {}
  policyTypes:
  - Ingress
  - Egress
---
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: production-operator
  namespace: production
rules:
- apiGroups: [""]
  resources: ["pods", "services", "configmaps"]
  verbs: ["get", "list", "watch", "create", "update", "patch"]
- apiGroups: ["apps"]
  resources: ["deployments"]
  verbs: ["get", "list", "watch", "update", "patch"]
```

***

## 📚 **Resources dan Referensi**

### Dokumentasi Official

* [Kubernetes Security Overview](https://kubernetes.io/docs/concepts/security/)
* [RBAC Authorization](https://kubernetes.io/docs/reference/access-authn-authz/rbac/)
* [Network Policies](https://kubernetes.io/docs/concepts/services-networking/network-policies/)

### Security Tools

* [Open Policy Agent Gatekeeper](https://github.com/open-policy-agent/gatekeeper)
* [Falco Runtime Security](https://falco.org/)
* [Trivy Vulnerability Scanner](https://github.com/aquasecurity/trivy)

### Cheatsheet Summary

```bash
# RBAC Commands
kubectl create role <name> --verb=get,list,watch --resource=pods
kubectl create rolebinding <name> --role=<role> --user=<user>
kubectl auth can-i create deployments --as=<user>

# Network Policy Commands
kubectl get networkpolicy
kubectl describe networkpolicy <name>

# Security Commands
kubectl get secrets
kubectl get pods --field-selector=spec.serviceAccountName=default
kubectl get events --field-selector reason=Failed
```

Security fundamentals documentation siap digunakan! 🔐
