# Security Advanced

## Mutual TLS (mTLS) Implementation

### Konsep mTLS di Kubernetes

Mutual TLS provides end-to-end encryption and authentication between services within the cluster.

```
┌─────────────┐    TLS    ┌─────────────┐    TLS    ┌─────────────┐
│   Service   │◀───────▶│  Service    │◀───────▶│   Service   │
│     A       │          │     Mesh    │         │      B      │
│             │          │             │          │             │
│ • Cert      │          │ • mTLS      │          │ • Cert      │
│ • Private   │          │ • Identity  │          │ • Private   │
│ • Rotation  │          │ • Rotation  │          │ • Rotation  │
└─────────────┘          └─────────────┘          └─────────────┘
```

### Istio mTLS Configuration

#### Strict mTLS Policy

```yaml
apiVersion: security.istio.io/v1beta1
kind: PeerAuthentication
metadata:
  name: default
  namespace: production
spec:
  mtls:
    mode: STRICT
---
apiVersion: security.istio.io/v1beta1
kind: PeerAuthentication
metadata:
  name: frontend-mtls
  namespace: production
spec:
  selector:
    matchLabels:
      app: frontend
  mtls:
    mode: STRICT
---
apiVersion: networking.istio.io/v1alpha3
kind: DestinationRule
metadata:
  name: default
  namespace: production
spec:
  host: "*.production.svc.cluster.local"
  trafficPolicy:
    tls:
      mode: ISTIO_MUTUAL
```

#### Permissive mTLS (Migration Mode)

```yaml
apiVersion: security.istio.io/v1beta1
kind: PeerAuthentication
metadata:
  name: permissive-mtls
  namespace: staging
spec:
  mtls:
    mode: PERMISSIVE
---
apiVersion: networking.istio.io/v1alpha3
kind: DestinationRule
metadata:
  name: permissive-traffic
  namespace: staging
spec:
  host: "*.staging.svc.cluster.local"
  trafficPolicy:
    tls:
      mode: ISTIO_MUTUAL
    connectionPool:
      tcp:
        maxConnections: 100
      http:
        http1MaxPendingRequests: 50
        maxRequestsPerConnection: 10
```

#### Custom Certificate Management

```yaml
apiVersion: cert-manager.io/v1
kind: Certificate
metadata:
  name: istio-gateway-cert
  namespace: istio-system
spec:
  secretName: istio-ingressgateway-certs
  dnsNames:
  - "*.example.com"
  - "example.com"
  issuerRef:
    name: letsencrypt-prod
    kind: ClusterIssuer
---
apiVersion: v1
kind: Secret
metadata:
  name: istio-cacerts
  namespace: istio-system
type: Opaque
data:
  ca-cert.pem: LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0t...
  ca-key.pem: LS0tLS1CRUdJTiBQUklWQVRFIEtFWS0tLS0t...
```

### Linkerd mTLS Implementation

#### Linkerd Installation with mTLS

```bash
# Install Linkerd with automatic mTLS
linkerd install | kubectl apply -f -

# Enable mTLS for all namespaces
linkerd install --identity-trust-anchors-file ca.crt \
               --identity-issuer-certificate-file issuer.crt \
               --identity-issuer-key-file issuer.key | kubectl apply -f -

# Inject into specific namespaces
kubectl annotate namespace production linkerd.io/inject=enabled
kubectl annotate namespace development linkerd.io/inject=enabled
```

#### Linkerd mTLS Policy

```yaml
apiVersion: policy.linkerd.io/v1beta1
kind: Server
metadata:
  name: webapp-server
  namespace: production
spec:
  podSelector:
    matchLabels:
      app: webapp
  port:
    port: 8080
    protocol: HTTP
  proxyProtocol: HTTP/1
---
apiVersion: policy.linkerd.io/v1beta1
kind: ServerAuthorization
metadata:
  name: webapp-authz
  namespace: production
spec:
  server:
    name: webapp-server
  client:
    unauthenticated: true
    networks:
    - cidr: 10.0.0.0/8
```

### Custom mTLS Implementation

#### Self-Signed Certificate Setup

```yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: mtls-ca-config
  namespace: security-system
data:
  ca.conf: |
    [req]
    distinguished_name = req_distinguished_name
    x509_extensions = v3_req
    prompt = no

    [req_distinguished_name]
    C = US
    ST = CA
    L = San Francisco
    O = Company
    OU = Security
    CN = Kubernetes mTLS CA

    [v3_req]
    basicConstraints = CA:TRUE
    keyUsage = keyCertSign, cRLSign
    subjectKeyIdentifier = hash

  server.conf: |
    [req]
    distinguished_name = req_distinguished_name
    x509_extensions = v3_req
    prompt = no

    [req_distinguished_name]
    C = US
    ST = CA
    L = San Francisco
    O = Company
    OU = Security
    CN = service.svc.cluster.local

    [v3_req]
    basicConstraints = CA:FALSE
    keyUsage = digitalSignature, keyEncipherment
    extendedKeyUsage = serverAuth, clientAuth
    subjectAltName = @alt_names

    [alt_names]
    DNS.1 = service
    DNS.2 = service.production.svc.cluster.local
```

#### Certificate Rotation Automation

```yaml
apiVersion: batch/v1
kind: CronJob
metadata:
  name: cert-rotation
  namespace: security-system
spec:
  schedule: "0 2 1 * *"  # First day of every month at 2 AM
  jobTemplate:
    spec:
      template:
        spec:
          serviceAccountName: cert-rotator
          containers:
          - name: rotator
            image: cert-rotator:v1.0.0
            env:
            - name: TARGET_NAMESPACE
              value: "production"
            - name: CERT_DURATION
              value: "2160h"  # 90 days
            - name: ROTATION_THRESHOLD
              value: "720h"  # 30 days before expiry
          restartPolicy: OnFailure
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: cert-rotator
rules:
- apiGroups: [""]
  resources: ["secrets", "configmaps"]
  verbs: ["get", "list", "watch", "create", "update", "patch", "delete"]
- apiGroups: ["cert-manager.io"]
  resources: ["certificates"]
  verbs: ["get", "list", "watch", "create", "update", "patch"]
```

## Service Mesh Security

### Advanced Istio Security

#### Authorization Policies

```yaml
apiVersion: security.istio.io/v1beta1
kind: AuthorizationPolicy
metadata:
  name: frontend-allow-backend
  namespace: production
spec:
  selector:
    matchLabels:
      app: backend
  action: ALLOW
  rules:
  - from:
    - source:
        principals: ["cluster.local/ns/production/sa/frontend-sa"]
  - to:
    - operation:
        methods: ["GET", "POST"]
        paths: ["/api/*"]
---
apiVersion: security.istio.io/v1beta1
kind: AuthorizationPolicy
metadata:
  name: deny-external-access
  namespace: production
spec:
  action: DENY
  rules:
  - from:
    - source:
        notNamespace: ["production", "istio-system"]
---
apiVersion: security.istio.io/v1beta1
kind: AuthorizationPolicy
metadata:
  name: jwt-validation
  namespace: production
spec:
  selector:
    matchLabels:
      app: api-gateway
  action: ALLOW
  rules:
  - from:
    - source:
        requestPrincipals: ["*"]
  when:
  - key: request.auth.claims[role]
    values: ["admin", "user"]
```

#### Request Authentication

```yaml
apiVersion: security.istio.io/v1beta1
kind: RequestAuthentication
metadata:
  name: jwt-authentication
  namespace: production
spec:
  selector:
    matchLabels:
      app: api-service
  jwtRules:
  - issuer: "https://auth.example.com"
    jwksUri: "https://auth.example.com/.well-known/jwks.json"
    forwardOriginalToken: true
    fromHeaders:
    - name: x-auth-token
    fromParams:
    - access_token
  - issuer: "https://token.auth.example.com"
    jwksUri: "https://token.auth.example.com/jwks"
    outputPayloadToHeader: x-jwt-payload
---
apiVersion: security.istio.io/v1beta1
kind: RequestAuthentication
metadata:
  name: api-key-auth
  namespace: production
spec:
  selector:
    matchLabels:
      app: external-api
  jwtRules:
  - issuer: "https://api-keys.example.com"
    forwardOriginalToken: true
    fromHeaders:
    - name: x-api-key
```

### Service Mesh Network Security

#### Egress Traffic Control

```yaml
apiVersion: networking.istio.io/v1alpha3
kind: ServiceEntry
metadata:
  name: external-db
  namespace: production
spec:
  hosts:
  - external-db.example.com
  ports:
  - number: 5432
    name: tcp-postgres
    protocol: TCP
  location: MESH_EXTERNAL
  resolution: DNS
---
apiVersion: networking.istio.io/v1alpha3
kind: Sidecar
metadata:
  name: default
  namespace: production
spec:
  egress:
  - hosts:
    - "istio-system/*"
    - "production/*"
    - "external-db.example.com"
  outboundPortSelection:
    mode: REGISTER_ONLY
```

#### Ingress Security Gateway

```yaml
apiVersion: networking.istio.io/v1alpha3
kind: Gateway
metadata:
  name: secure-gateway
  namespace: istio-system
spec:
  selector:
    istio: ingressgateway
  servers:
  - port:
      number: 443
      name: https
      protocol: HTTPS
    tls:
      mode: SIMPLE
      credentialName: gateway-secret
    hosts:
    - "api.example.com"
  - port:
      number: 8443
      name: https-admin
      protocol: HTTPS
    tls:
      mode: MUTUAL
      credentialName: admin-gateway-secret
    hosts:
    - "admin-api.example.com"
---
apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
  name: routing-rules
  namespace: production
spec:
  hosts:
  - "api.example.com"
  gateways:
  - istio-system/secure-gateway
  http:
  - match:
    - headers:
        x-api-version:
          exact: "v1"
    route:
    - destination:
        host: api-service
        subset: v1
  - match:
    - headers:
        x-api-version:
          exact: "v2"
    route:
    - destination:
        host: api-service
        subset: v2
  - fault:
      delay:
        percentage:
          value: 0.1
        fixedDelay: 5s
    route:
    - destination:
        host: api-service
        subset: v1
```

## Advanced Container Security

### Runtime Security

#### Falco Advanced Rules

```yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: falco-advanced-rules
  namespace: falco
data:
  advanced_security_rules.yaml: |
    - rule: Detect container escape
      desc: Detect attempts to escape container using mount namespace
      condition: >
        spawned_process and
        container and
        proc.name in (nsenter, unshare) and
        proc.args contains "mount" and
        not user.name in (root, systemd-network)
      output: >
        Container escape attempt (user=%user.name command=%proc.cmdline
        container=%container.name pod=%kubernetes.pod.name)
      priority: CRITICAL
      tags: [container, escape, mitre]

    - rule: Detect crypto mining
      desc: Detect cryptocurrency mining activities
      condition: >
        spawned_process and
        container and
        proc.name in (xmrig, cgminer, bfgminer, cpuminer) and
        not proc.cmdline contains "test"
      output: >
        Cryptocurrency mining detected (user=%user.name command=%proc.cmdline
        container=%container.name pod=%kubernetes.pod.name)
      priority: HIGH
      tags: [crypto, mining, mitre]

    - rule: Detect reverse shell
      desc: Detect reverse shell connections
      condition: >
        spawned_process and
        container and
        proc.name in (bash, sh, nc, netcat, telnet) and
        proc.args contains "-e" and
        proc.args matches "(/dev/tcp|/dev/udp)"
      output: >
        Reverse shell detected (user=%user.name command=%proc.cmdline
        container=%container.name)
      priority: CRITICAL
      tags: [shell, reverse, mitre]
```

#### Seccomp Profiles

```yaml
apiVersion: v1
kind: Pod
metadata:
  name: secure-app
  namespace: production
spec:
  securityContext:
    seccompProfile:
      type: Localhost
      localhostProfile: profiles/secure-app.json
  containers:
  - name: app
    image: myapp:v1.0.0
    securityContext:
      allowPrivilegeEscalation: false
      readOnlyRootFilesystem: true
      capabilities:
        drop:
        - ALL
---
apiVersion: v1
kind: ConfigMap
metadata:
  name: seccomp-profiles
  namespace: production
data:
  secure-app.json: |
    {
      "defaultAction": "SCMP_ACT_ERRNO",
      "architectures": ["SCMP_ARCH_X86_64", "SCMP_ARCH_X86", "SCMP_ARCH_X32"],
      "syscalls": [
        {
          "names": [
            "accept", "accept4", "access", "adjtimex", "alarm", "bind", "brk", "capget", "capset",
            "chdir", "chmod", "chown", "chown32", "clock_getres", "clock_gettime", "clock_nanosleep",
            "close", "connect", "copy_file_range", "creat", "dup", "dup2", "dup3", "epoll_create",
            "epoll_create1", "epoll_ctl", "epoll_ctl_old", "epoll_pwait", "epoll_wait",
            "epoll_wait_old", "eventfd", "eventfd2", "execve", "execveat", "exit", "exit_group",
            "faccessat", "fadvise64", "fadvise64_64", "fallocate", "fanotify_mark", "fchdir",
            "fchmod", "fchmodat", "fchown", "fchown32", "fchownat", "fcntl", "fcntl64", "fdatasync",
            "fgetxattr", "flistxattr", "flock", "fork", "fremovexattr", "fsetxattr", "fstat",
            "fstat64", "fstatat64", "fstatfs", "fstatfs64", "fsync", "ftruncate", "ftruncate64",
            "futex", "getcwd", "getdents", "getdents64", "getegid", "getegid32", "geteuid",
            "geteuid32", "getgid", "getgid32", "getgroups", "getgroups32", "getitimer", "getpeername",
            "getpgid", "getpgrp", "getpid", "getppid", "getpriority", "getrandom", "getresgid",
            "getresgid32", "getresuid", "getresuid32", "getrlimit", "get_robust_list", "getrusage",
            "getsid", "getsockname", "getsockopt", "get_thread_area", "gettid", "gettimeofday",
            "getuid", "getuid32", "getxattr", "inotify_add_watch", "inotify_init", "inotify_init1",
            "inotify_rm_watch", "io_cancel", "ioctl", "io_destroy", "io_getevents", "ioperm",
            "iopl", "io_setup", "io_submit", "ipc", "kill", "lchown", "lchown32", "lgetxattr",
            "link", "linkat", "listen", "listxattr", "llistxattr", "lremovexattr", "lseek",
            "lsetxattr", "lstat", "lstat64", "madvise", "memfd_create", "mincore", "mkdir",
            "mkdirat", "mknod", "mknodat", "mlock", "mlock2", "mlockall", "mmap", "mmap2",
            "mprotect", "mq_getsetattr", "mq_notify", "mq_open", "mq_timedreceive", "mq_timedsend",
            "mq_unlink", "mremap", "msgctl", "msgget", "msgrcv", "msgsnd", "msync", "munlock",
            "munlockall", "munmap", "nanosleep", "newfstatat", "open", "openat", "pause",
            "pipe", "pipe2", "poll", "ppoll", "prctl", "pread64", "preadv", "prlimit64",
            "pselect6", "ptrace", "pwrite64", "pwritev", "read", "readahead", "readlink",
            "readlinkat", "readv", "recv", "recvfrom", "recvmmsg", "recvmsg", "remap_file_pages",
            "removexattr", "rename", "renameat", "renameat2", "restart_syscall", "rmdir",
            "rt_sigaction", "rt_sigpending", "rt_sigprocmask", "rt_sigqueueinfo", "rt_sigreturn",
            "rt_sigsuspend", "rt_sigtimedwait", "rt_tgsigqueueinfo", "sched_getaffinity",
            "sched_getattr", "sched_getparam", "sched_get_priority_max", "sched_get_priority_min",
            "sched_getscheduler", "sched_rr_get_interval", "sched_setaffinity", "sched_setattr",
            "sched_setparam", "sched_setscheduler", "sched_yield", "seccomp", "select", "semctl",
            "semget", "semop", "semtimedop", "send", "sendfile", "sendfile64", "sendmmsg",
            "sendmsg", "sendto", "setfsgid", "setfsgid32", "setfsuid", "setfsuid32", "setgid",
            "setgid32", "setgroups", "setgroups32", "setitimer", "setpgid", "setpriority",
            "setregid", "setregid32", "setresgid", "setresgid32", "setresuid", "setresuid32",
            "setreuid", "setreuid32", "setrlimit", "set_robust_list", "setsid", "setsockopt",
            "set_thread_area", "set_tid_address", "setuid", "setuid32", "setxattr", "shmat",
            "shmctl", "shmdt", "shmget", "shutdown", "sigaltstack", "signalfd", "signalfd4",
            "sigreturn", "socket", "socketcall", "socketpair", "splice", "stat", "stat64",
            "statfs", "statfs64", "statx", "symlink", "symlinkat", "sync", "sync_file_range",
            "syncfs", "sysinfo", "tee", "tgkill", "time", "timer_create", "timer_delete",
            "timerfd_create", "timerfd_gettime", "timerfd_settime", "timer_getoverrun",
            "timer_gettime", "timer_settime", "times", "tkill", "truncate", "truncate64",
            "ugetrlimit", "umask", "uname", "unlink", "unlinkat", "utime", "utimensat",
            "utimes", "vfork", "vmsplice", "wait4", "waitid", "waitpid", "write", "writev"
          ],
          "action": "SCMP_ACT_ALLOW"
        },
        {
          "names": [
            "personality", "ptrace", "process_vm_readv", "process_vm_writev", "syslog"
          ],
          "action": "SCMP_ACT_ERRNO",
          "args": []
        }
      ]
    }
```

### AppArmor/SELinux Profiles

#### AppArmor Profile

```yaml
apiVersion: v1
kind: Pod
metadata:
  name: apparmor-pod
  namespace: production
  annotations:
    container.apparmor.security.beta.kubernetes.io/app: localhost/k8s-apparmor
spec:
  securityContext:
    runAsNonRoot: true
    runAsUser: 1000
  containers:
  - name: app
    image: myapp:v1.0.0
    securityContext:
      allowPrivilegeEscalation: false
      readOnlyRootFilesystem: true
      capabilities:
        drop:
        - ALL
```

#### AppArmor Profile Definition

```bash
# /etc/apparmor.d/k8s-apparmor
#include <tunables/global>

profile k8s-apparmor flags=(attach_disconnected,mediate_deleted) {
  #include <abstractions/base>

  # Network access
  network inet tcp,
  network inet udp,
  network inet6 tcp,
  network inet6 udp,

  # File system access
  / r,
  /bin/** ix,
  /sbin/** ix,
  /lib/** mr,
  /lib64/** mr,
  /usr/bin/** ix,
  /usr/sbin/** ix,
  /usr/lib/** mr,
  /usr/lib64/** mr,

  # Application specific
  /app/** r,
  /tmp/** rw,
  /var/log/app/** w,

  # Deny dangerous operations
  capability sys_admin,
  capability sys_module,
  capability sys_rawio,
  capability sys_ptrace,
  capability sys_time,
  capability sys_boot,
  capability mac_admin,
  capability mac_override,

  # Mount operations
  deny mount,
  deny umount,

  # System calls
  deny ptrace,
  deny signal,
}
```

## Advanced Secret Management

### External Secret Store Integration

#### HashiCorp Vault Advanced Configuration

```yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: vault-config
  namespace: security-system
data:
  vault.hcl: |
    ui = true

    listener "tcp" {
      address = "0.0.0.0:8200"
      tls_disable = 1
      cluster_address = "0.0.0.0:8201"
    }

    storage "consul" {
      address = "consul.service.consul:8500"
      path = "vault/"
    }

    api_addr = "http://vault.security-system.svc.cluster.local:8200"
    cluster_addr = "http://vault.security-system.svc.cluster.local:8201"

    telemetry {
      prometheus_retention_time = "30s"
      disable_hostname = true
    }

    plugin_directory = "/vault/plugins"

    auth "kubernetes" {
      mount_path = "auth/kubernetes"
    }

    secrets "transit" {
      path = "transit/"
    }
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: vault
  namespace: security-system
spec:
  replicas: 3
  selector:
    matchLabels:
      app: vault
  template:
    metadata:
      labels:
        app: vault
    spec:
      serviceAccountName: vault
      containers:
      - name: vault
        image: hashicorp/vault:1.12.0
        args:
        - server
        - -config=/vault/config/vault.hcl
        env:
        - name: VAULT_ADDR
          value: "http://localhost:8200"
        - name: VAULT_API_ADDR
          value: "http://vault.security-system.svc.cluster.local:8200"
        ports:
        - containerPort: 8200
          name: vault
        - containerPort: 8201
          name: cluster
        securityContext:
          capabilities:
            add:
            - IPC_LOCK
        volumeMounts:
        - name: config
          mountPath: /vault/config
        - name: file
          mountPath: /vault/file
      volumes:
      - name: config
        configMap:
          name: vault-config
      - name: file
        emptyDir: {}
```

#### Vault Secret Engines

```yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: vault-policies
  namespace: security-system
data:
  app-policy.hcl: |
    path "secret/data/app/*" {
      capabilities = ["read", "list"]
    }

    path "database/creds/app-db" {
      capabilities = ["read"]
    }

    path "transit/encrypt/app-data" {
      capabilities = ["update"]
    }

    path "transit/decrypt/app-data" {
      capabilities = ["update"]
    }

    path "pki/issue/app-cert" {
      capabilities = ["update"]
    }
---
apiVersion: batch/v1
kind: Job
metadata:
  name: vault-init
  namespace: security-system
spec:
  template:
    spec:
      serviceAccountName: vault
      restartPolicy: OnFailure
      containers:
      - name: vault-init
        image: hashicorp/vault:1.12.0
        env:
        - name: VAULT_ADDR
          value: "http://vault.security-system.svc.cluster.local:8200"
        command:
        - /bin/sh
        - -c
        - |
          # Enable secret engines
          vault secrets enable -path=secret kv-v2
          vault secrets enable database
          vault secrets enable transit
          vault secrets enable pki

          # Configure database secret engine
          vault write database/config/app-db \
            plugin_name=postgresql-database-plugin \
            allowed_roles="app-role" \
            connection_url="postgresql://{{username}}:{{password}}@postgres.production.svc.cluster.local:5432/appdb" \
            username="vault" \
            password="vault-password"

          vault write database/roles/app-role \
            db_name=app-db \
            creation_statements="CREATE ROLE \"{{name}}\" WITH LOGIN PASSWORD '{{password}}' VALID UNTIL '{{expiration}}'; GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO \"{{name}}\";" \
            default_ttl="1h" \
            max_ttl="24h"

          # Configure transit
          vault write -f transit/keys/app-key

          # Configure PKI
          vault write pki/config/urls \
            issuing_certificates="http://vault.security-system.svc.cluster.local:8200/v1/pki/ca" \
            crl_distribution_points="http://vault.security-system.svc.cluster.local:8200/v1/pki/crl"

          vault write pki/roles/app-role \
            allowed_domains="app.production.svc.cluster.local" \
            allow_subdomains=true \
            max_ttl="72h"

          # Create policies
          vault policy write app-policy /vault/config/app-policy.hcl

          # Enable kubernetes auth
          vault auth enable kubernetes
          vault write auth/kubernetes/config \
            kubernetes_host="https://kubernetes.default.svc:443" \
            kubernetes_ca_cert="@/var/run/secrets/kubernetes.io/serviceaccount/ca.crt" \
            token_reviewer_jwt="$(cat /var/run/secrets/kubernetes.io/serviceaccount/token)"

          vault write auth/kubernetes/role/app-role \
            bound_service_account_names=app-service-account \
            bound_service_account_namespaces=production \
            policies=app-policy \
            ttl=24h
```

### Secret Rotation dan Management

#### Automatic Secret Rotation

```yaml
apiVersion: external-secrets.io/v1beta1
kind: SecretStore
metadata:
  name: vault-rotating-store
  namespace: production
spec:
  provider:
    vault:
      server: "http://vault.security-system.svc.cluster.local:8200"
      path: "secret"
      version: "v2"
      auth:
        kubernetes:
          mountPath: "kubernetes"
          role: "external-secrets"
---
apiVersion: external-secrets.io/v1beta1
kind: ExternalSecret
metadata:
  name: rotating-database-credentials
  namespace: production
spec:
  refreshInterval: 1h
  secretStoreRef:
    name: vault-rotating-store
    kind: SecretStore
  target:
    name: database-credentials
    creationPolicy: Owner
    deletionPolicy: Delete
  data:
  - secretKey: username
    remoteRef:
      key: database/creds/app-db
      property: username
  - secretKey: password
    remoteRef:
      key: database/creds/app-db
      property: password
---
apiVersion: v1
kind: Secret
metadata:
  name: database-credentials
  namespace: production
  annotations:
    secret-reloader.stakater.com/match: "true"
    secret-reloader.stakater.com/auto: "true"
type: Opaque
data:
  username: ""  # Will be populated by ExternalSecret
  password: ""  # Will be populated by ExternalSecret
```

#### Secret Encryption at Rest

```yaml
apiVersion: apiserver.config.k8s.io/v1
kind: EncryptionConfiguration
resources:
  - resources:
      - secrets
      - configmaps
    providers:
      - aescbc:
          keys:
            - name: key1
              secret: <base64-encoded-32-byte-key>
      - identity: {}
---
apiVersion: v1
kind: Secret
metadata:
  name: encryption-key
  namespace: kube-system
type: Opaque
data:
  key: <base64-encoded-32-byte-random-key>
```

## Advanced Network Security

### Service-to-Service Encryption

#### Custom Sidecar for mTLS

```yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: mtls-proxy-config
  namespace: production
data:
  nginx.conf: |
    events {
        worker_connections 1024;
    }

    http {
        upstream backend {
            server backend.production.svc.cluster.local:8080;
        }

        server {
            listen 8443 ssl;
            ssl_certificate /etc/certs/tls.crt;
            ssl_certificate_key /etc/certs/tls.key;
            ssl_verify_client on;
            ssl_client_certificate /etc/certs/ca.crt;

            location / {
                proxy_pass http://backend;
                proxy_set_header Host $host;
                proxy_set_header X-Real-IP $remote_addr;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_set_header X-Forwarded-Proto $scheme;
            }
        }
    }
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: secure-app
  namespace: production
spec:
  replicas: 3
  selector:
    matchLabels:
      app: secure-app
  template:
    metadata:
      labels:
        app: secure-app
    spec:
      containers:
      - name: app
        image: myapp:v1.0.0
        ports:
        - containerPort: 8080
        securityContext:
          allowPrivilegeEscalation: false
          readOnlyRootFilesystem: true
          capabilities:
            drop:
            - ALL
      - name: mtls-proxy
        image: nginx:1.21
        ports:
        - containerPort: 8443
        volumeMounts:
        - name: certs
          mountPath: /etc/certs
          readOnly: true
        - name: config
          mountPath: /etc/nginx/nginx.conf
          subPath: nginx.conf
      volumes:
      - name: certs
        secret:
          secretName: mtls-certs
      - name: config
        configMap:
          name: mtls-proxy-config
```

### Advanced Network Policies

#### Multi-Tenant Network Isolation

```yaml
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: tenant-a-isolation
  namespace: tenant-a
spec:
  podSelector: {}
  policyTypes:
  - Ingress
  - Egress
  ingress:
  - from:
    - namespaceSelector:
        matchLabels:
          name: tenant-a
    - namespaceSelector:
        matchLabels:
          name: shared-services
  egress:
  - to:
    - namespaceSelector:
        matchLabels:
          name: tenant-a
    - namespaceSelector:
        matchLabels:
          name: shared-services
  - to: []
    ports:
    - protocol: TCP
      port: 53
    - protocol: UDP
      port: 53
---
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: shared-services-policy
  namespace: shared-services
spec:
  podSelector:
    matchLabels:
      tier: database
  policyTypes:
  - Ingress
  ingress:
  - from:
    - namespaceSelector:
        matchLabels:
          name: tenant-a
    - namespaceSelector:
        matchLabels:
          name: tenant-b
    ports:
    - protocol: TCP
      port: 5432
```

## Compliance dan Auditing

### Compliance Automation

#### CIS Benchmark Validation

```yaml
apiVersion: batch/v1
kind: CronJob
metadata:
  name: cis-benchmark
  namespace: security-system
spec:
  schedule: "0 2 * * 0"  # Weekly on Sunday at 2 AM
  jobTemplate:
    spec:
      template:
        spec:
          serviceAccountName: cis-scanner
          containers:
          - name: kube-bench
            image: aquasec/kube-bench:latest
            command:
            - /bin/sh
            - -c
            - |
              kube-bench --config-dir=/cfg --benchmark=cis-1.23 --output=json > /reports/cis-report-$(date +%Y%m%d).json
              curl -X POST -H "Content-Type: application/json" \
                --data-binary @/reports/cis-report-$(date +%Y%m%d).json \
                https://compliance-api.example.com/reports
            volumeMounts:
            - name: config
              mountPath: /cfg
            - name: reports
              mountPath: /reports
          volumes:
          - name: config
            configMap:
              name: cis-config
          - name: reports
            persistentVolumeClaim:
              claimName: compliance-reports
          restartPolicy: OnFailure
```

#### Automated Security Scanning

```yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: security-scan-config
  namespace: security-system
data:
  scan-config.yaml: |
    scanners:
      - name: trivy
        image: aquasec/trivy:latest
        command: ["trivy", "image", "--format", "json", "--output", "/reports/trivy-report.json"]

      - name: falco
        image: falcosecurity/falco:latest
        command: ["falco", "--output", "json", "--output-file", "/reports/falco-report.json"]

    policies:
      - name: critical-vulnerabilities
        severity: ["CRITICAL", "HIGH"]
        action: "alert"

      - name: compliance-check
        frameworks: ["CIS", "PCI-DSS", "SOC2"]
        action: "report"
---
apiVersion: batch/v1
kind: Job
metadata:
  name: security-scan
  namespace: security-system
spec:
  template:
    spec:
      serviceAccountName: security-scanner
      containers:
      - name: security-scanner
        image: security-scanner:v1.0.0
        env:
        - name: SCAN_CONFIG
          value: "/config/scan-config.yaml"
        - name: REPORT_ENDPOINT
          value: "https://security-reports.example.com/api/reports"
        volumeMounts:
        - name: config
          mountPath: /config
        - name: reports
          mountPath: /reports
      volumes:
      - name: config
        configMap:
          name: security-scan-config
      - name: reports
        emptyDir: {}
      restartPolicy: OnFailure
```

### Advanced Audit Configuration

#### Custom Audit Rules

```yaml
apiVersion: audit.k8s.io/v1
kind: Policy
rules:
- level: RequestResponse
  namespaces: ["production"]
  resources:
  - group: ""
    resources: ["secrets"]
  verbs: ["create", "update", "delete", "get", "list", "watch"]

- level: Request
  namespaces: ["production"]
  resources:
  - group: ["rbac.authorization.k8s.io"]
    resources: ["roles", "rolebindings", "clusterroles", "clusterrolebindings"]
  verbs: ["create", "update", "delete", "bind"]

- level: Request
  namespaces: ["production"]
  resources:
  - group: ["networking.k8s.io"]
    resources: ["networkpolicies"]
  verbs: ["create", "update", "delete"]

- level: Metadata
  namespaces: ["kube-system"]
  resources:
  - group: ["extensions", "apps"]
    resources: ["daemonsets", "deployments"]

- level: Request
  users: ["system:anonymous"]
  verbs: ["*"]
  resources: ["*"]

- level: None
  users: ["system:kube-proxy", "system:node"]
  verbs: ["get", "list", "watch"]
  resources: ["endpoints", "services"]
```

#### Audit Log Processing

```yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: audit-processor
  namespace: security-system
data:
  audit-processor.py: |
    import json
    import sys
    from datetime import datetime
    from elasticsearch import Elasticsearch

    es = Elasticsearch(["https://elasticsearch.security-system.svc.cluster.local:9200"])

    def process_audit_log(line):
        try:
            audit_entry = json.loads(line)

            # Extract relevant information
            event = {
                "timestamp": datetime.now().isoformat(),
                "user": audit_entry.get("user", {}).get("username", "unknown"),
                "verb": audit_entry.get("verb", "unknown"),
                "resource": audit_entry.get("objectRef", {}).get("resource", "unknown"),
                "namespace": audit_entry.get("objectRef", {}).get("namespace", "unknown"),
                "source_ip": audit_entry.get("sourceIPs", ["unknown"])[0],
                "response_status": audit_entry.get("responseStatus", {}).get("code", 200),
                "stage": audit_entry.get("stage", "unknown")
            }

            # Check for suspicious activity
            if is_suspicious(event):
                event["alert_level"] = "HIGH"
                send_alert(event)

            # Store in Elasticsearch
            es.index(index="kubernetes-audit", body=event)

        except Exception as e:
            print(f"Error processing audit log: {e}", file=sys.stderr)

    def is_suspicious(event):
        suspicious_patterns = [
            event["user"] == "system:anonymous",
            event["response_status"] >= 400,
            event["verb"] in ["create", "delete"] and event["resource"] in ["secrets", "clusterroles"],
            event["namespace"] == "kube-system" and event["user"] not in ["system:kube-controller-manager", "system:kube-scheduler"]
        ]
        return any(suspicious_patterns)

    def send_alert(event):
        # Send alert to monitoring system
        alert = {
            "alert": "Kubernetes Security Event",
            "description": f"Suspicious activity detected: {event['user']} {event['verb']} {event['resource']} in {event['namespace']}",
            "severity": "HIGH",
            "event": event
        }
        # Send to alerting system (e.g., PagerDuty, Slack, etc.)

    # Process audit log from stdin
    for line in sys.stdin:
        process_audit_log(line.strip())
```

***

## 🚀 **Production Advanced Security Setup**

### Complete Production Security Configuration

```yaml
# Namespace with advanced security
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
    security-level: high
---
# Istio security policies
apiVersion: security.istio.io/v1beta1
kind: PeerAuthentication
metadata:
  name: strict-mtls
  namespace: production
spec:
  mtls:
    mode: STRICT
---
apiVersion: security.istio.io/v1beta1
kind: AuthorizationPolicy
metadata:
  name: deny-all
  namespace: production
spec:
  selector: {}
  action: DENY
---
# Network policies
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: production-deny-all
  namespace: production
spec:
  podSelector: {}
  policyTypes:
  - Ingress
  - Egress
---
# Security monitoring
apiVersion: monitoring.coreos.com/v1
kind: PrometheusRule
metadata:
  name: production-security
  namespace: production
spec:
  groups:
  - name: security
    rules:
    - alert: MTLSViolation
      expr: istio_requests_total{source_workload_namespace="production",connection_security_policy="mutual"} == 0
      for: 0m
      labels:
        severity: critical
      annotations:
        summary: "mTLS violation detected in production"
```

***

## 📚 **Resources dan Referensi**

### Dokumentasi Advanced

* [Istio Security](https://istio.io/latest/docs/concepts/security/)
* [Falco Runtime Security](https://falco.org/docs/)
* [Vault Secrets Management](https://www.vaultproject.io/docs/secrets)

### Security Standards

* [CIS Kubernetes Benchmark](https://www.cisecurity.org/benchmark/kubernetes)
* [NIST Cybersecurity Framework](https://www.nist.gov/cyberframework)
* [OWASP Kubernetes Security](https://owasp.org/www-project-kubernetes-security/)

### Cheatsheet Summary

```bash
# mTLS Commands
istioctl auth check
istioctl proxy-config secret <pod>
kubectl get peerauthentication -A

# Security Commands
kubectl get pods --field-selector=spec.serviceAccountName=default
kubectl get networkpolicy --all-namespaces
kubectl get events --field-selector reason=Failed

# Audit Commands
kubectl get events --sort-by='.lastTimestamp' | grep -i error
grep "system:anonymous" /var/log/kubernetes/audit.log
```

Advanced security documentation siap digunakan! 🛡️
