SiamCafe · Blog
Nuclei Scanner Infrastructure as Code — Scan
บทความ

Nuclei Scanner Infrastructure as Code — Scan

เผยแพร่ 28 พฤษภาคม 2569
mTLS Service Mesh กับ SaaS Architecture — วิธีใช้ mTLS ใน Service Mesh | SiamCafe Blog เรียนรู้การใช้ mTLS ใน Service Mesh สำหรับ SaaS Architecture ตั้งแต่ Certificate Management, Istio Configuration, Zero Trust ไปจนถึง Production Best Practices FAQ_Q:mTLS คืออะไร FAQ_A:mTLS (Mutual TLS) เป็นการเข้ารหัสการสื่อสารแบบสองทาง ทั้ง Client และ Server ต้องยืนยันตัวตนด้วย Certificate ต่างจาก TLS ปกติที่แค่ Server ยืนยันตัวตน mTLS ใช้ใน Service-to-Service Communication ป้องกัน Man-in-the-Middle Attack FAQ_Q:Service Mesh คืออะไร FAQ_A:Service Mesh เป็น Infrastructure Layer ที่จัดการ Service-to-Service Communication ใน Microservices ใช้ Sidecar Proxy (เช่น Envoy) แนบกับทุก Pod จัดการ Traffic Routing, Load Balancing, mTLS, Observability อัตโนมัติ ตัวอย่าง Istio, Linkerd, Consul Connect FAQ_Q:Istio ทำงานอย่างไร FAQ_A:Istio ติดตั้ง Envoy Proxy เป็น Sidecar ทุก Pod Control Plane (istiod) จัดการ Certificate, Traffic Rules, Telemetry Data Plane (Envoy) จัดการ Traffic จริง mTLS อัตโนมัติระหว่าง Services Traffic Management ด้วย VirtualService DestinationRule FAQ_Q:Zero Trust Architecture คืออะไร FAQ_A:Zero Trust เป็นแนวคิดที่ไม่เชื่อใจอะไรเลย ทุก Request ต้องยืนยันตัวตนและตรวจสอบสิทธิ์ แม้จะอยู่ภายใน Network เดียวกัน mTLS บังคับ Certificate ทุก Service, AuthorizationPolicy กำหนดว่า Service ไหนคุยกับ Service ไหนได้ BODY_START

mTLS ใน Service Mesh

mTLS เข้ารหัสการสื่อสารสองทาง Client Server ยืนยันตัวตนด้วย Certificate Service Mesh จัดการอัตโนมัติ Istio Linkerd Consul Connect

SaaS Architecture ใช้ mTLS ป้องกัน Service-to-Service Communication Zero Trust ไม่เชื่อใจอะไรเลย ทุก Request ยืนยันตัวตน

Istio mTLS Configuration

=== Istio mTLS Configuration ===

1. Install Istio

curl -L https://istio.io/downloadIstio | sh -

cd istio-1.21.0

export PATH=$PWD/bin:$PATH

istioctl install --set profile=demo -y

2. Enable Sidecar Injection

kubectl label namespace default istio-injection=enabled

3. PeerAuthentication — บังคับ mTLS ทั้ง Namespace

apiVersion: security.istio.io/v1beta1

kind: PeerAuthentication

metadata:

name: default

namespace: default

spec:

mtls:

mode: STRICT # STRICT = บังคับ mTLS, PERMISSIVE = ยอมรับทั้ง mTLS และ plaintext

4. PeerAuthentication — Mesh-wide (ทั้ง Cluster)

apiVersion: security.istio.io/v1beta1

kind: PeerAuthentication

metadata:

name: default

namespace: istio-system

spec:

mtls:

mode: STRICT

5. DestinationRule — บังคับ mTLS เมื่อเรียก Service

apiVersion: networking.istio.io/v1beta1

kind: DestinationRule

metadata:

name: api-service

spec:

host: api-service.default.svc.cluster.local

trafficPolicy:

tls:

mode: ISTIO_MUTUAL # ใช้ Istio certificates

6. AuthorizationPolicy — Zero Trust

apiVersion: security.istio.io/v1beta1

kind: AuthorizationPolicy

metadata:

name: api-policy

namespace: default

spec:

selector:

matchLabels:

app: api-service

action: ALLOW

rules:

  • from:
  • source:

principals: ["cluster.local/ns/default/sa/frontend-sa"]

to:

  • operation:

methods: ["GET", "POST"]

paths: ["/api/*"]

7. ตรวจสอบ mTLS Status

istioctl x describe pod <pod-name>

istioctl proxy-config secret <pod-name>

istioctl analyze

8. Kiali Dashboard (Visualization)

istioctl dashboard kiali

from dataclasses import dataclass

from typing import List

@dataclass

class IstioConfig:

name: str

kind: str

namespace: str

description: str

configs = [

IstioConfig("default-mtls", "PeerAuthentication", "default",

"บังคับ mTLS ทั้ง Namespace"),

IstioConfig("mesh-mtls", "PeerAuthentication", "istio-system",

"บังคับ mTLS ทั้ง Mesh"),

IstioConfig("api-dr", "DestinationRule", "default",

"บังคับ mTLS เมื่อเรียก API Service"),

IstioConfig("api-policy", "AuthorizationPolicy", "default",

"อนุญาตเฉพาะ Frontend เรียก API"),

]

print("Istio mTLS Configuration:")

for c in configs:

print(f" [{c.kind}] {c.name}")

print(f" Namespace: {c.namespace}")

print(f" {c.description}")

SaaS Architecture with Service Mesh

# saas_architecture.py — SaaS Architecture with mTLS
from dataclasses import dataclass, field
from typing import List, Dict

@dataclass
class MicroService:
    name: str
    namespace: str
    replicas: int
    port: int
    service_account: str
    allowed_callers: List[str]
    mtls: str = "STRICT"

class SaaSArchitecture:
    """SaaS Architecture with Service Mesh"""

    def __init__(self):
        self.services: List[MicroService] = []
        self.tenants: List[str] = []

    def add_service(self, svc: MicroService):
        self.services.append(svc)

    def add_tenant(self, tenant: str):
        self.tenants.append(tenant)

    def generate_auth_policies(self):
        """Generate AuthorizationPolicy for each service"""
        print(f"\n{'='*55}")
        print(f"AuthorizationPolicies (Zero Trust)")
        print(f"{'='*55}")

        for svc in self.services:
            print(f"\n  [{svc.name}]")
            print(f"    ServiceAccount: {svc.service_account}")
            print(f"    mTLS: {svc.mtls}")
            print(f"    Allowed Callers:")
            for caller in svc.allowed_callers:
                print(f"      - {caller}")

    def architecture_diagram(self):
        """Show Architecture"""
        print(f"\n{'='*55}")
        print(f"SaaS Architecture — Service Mesh")
        print(f"{'='*55}")

        layers = {
            "Edge": ["API Gateway (Kong/Nginx)", "WAF", "Rate Limiting"],
            "Frontend": ["Web App (React)", "Mobile BFF"],
            "API": ["Auth Service", "User Service", "Billing Service"],
            "Core": ["Order Service", "Product Service", "Notification Service"],
            "Data": ["PostgreSQL", "Redis", "Kafka", "S3"],
            "Observability": ["Prometheus", "Grafana", "Jaeger", "Kiali"],
        }

        for layer, components in layers.items():
            print(f"\n  [{layer} Layer]")
            for comp in components:
                print(f"    - {comp}")

    def tenant_isolation(self):
        """Tenant Isolation Strategy"""
        strategies = {
            "Namespace per Tenant": "แต่ละ Tenant มี Namespace แยก mTLS แยก",
            "Shared Services + Headers": "Services ร่วมกัน แยกด้วย Tenant Header",
            "Database per Tenant": "แต่ละ Tenant มี Database แยก",
            "Schema per Tenant": "Database เดียว แยก Schema ต่อ Tenant",
            "Row-level Security": "Table เดียว แยกด้วย tenant_id column",
        }

        print(f"\n  Tenant Isolation Strategies:")
        for strategy, desc in strategies.items():
            print(f"    {strategy}: {desc}")

# ตัวอย่าง
arch = SaaSArchitecture()

services = [
    MicroService("api-gateway", "edge", 3, 8080, "gateway-sa",
                ["istio-ingressgateway"]),
    MicroService("auth-service", "auth", 3, 8081, "auth-sa",
                ["api-gateway"]),
    MicroService("user-service", "core", 2, 8082, "user-sa",
                ["api-gateway", "auth-service"]),
    MicroService("billing-service", "billing", 2, 8083, "billing-sa",
                ["api-gateway", "order-service"]),
    MicroService("order-service", "core", 3, 8084, "order-sa",
                ["api-gateway", "billing-service"]),
    MicroService("notification-service", "core", 2, 8085, "notification-sa",
                ["order-service", "billing-service"]),
]

for svc in services:
    arch.add_service(svc)

arch.architecture_diagram()
arch.generate_auth_policies()
arch.tenant_isolation()

Certificate Management และ Monitoring

=== Certificate Management ===

1. Istio CA (Built-in)

Istio จัดการ Certificates อัตโนมัติ

  • Root CA: istiod สร้างและจัดการ
  • Workload Certificates: ออกให้ทุก Pod อัตโนมัติ
  • Auto-rotation: หมุนเวียน Certificate อัตโนมัติ (24 ชม.)
  • SPIFFE Identity: spiffe://cluster.local/ns/<ns>/sa/<sa>

2. External CA (cert-manager)

apiVersion: cert-manager.io/v1

kind: Certificate

metadata:

name: istio-ca

namespace: istio-system

spec:

isCA: true

duration: 8760h # 1 year

secretName: istio-ca-secret

issuerRef:

name: vault-issuer

kind: ClusterIssuer

commonName: istio-ca

3. Vault Integration

apiVersion: cert-manager.io/v1

kind: ClusterIssuer

metadata:

name: vault-issuer

spec:

vault:

path: pki/sign/istio

server: https://vault.company.com

auth:

kubernetes:

role: cert-manager

mountPath: /v1/auth/kubernetes

4. Monitoring mTLS

Prometheus Queries:

istio_requests_total{connection_security_policy="mutual_tls"}

istio_tcp_connections_opened_total

envoy_cluster_ssl_handshake

5. Grafana Dashboard

Import Istio dashboards:

  • Istio Mesh Dashboard (ID: 7639)
  • Istio Service Dashboard (ID: 7636)
  • Istio Workload Dashboard (ID: 7630)

6. Jaeger Tracing

istioctl dashboard jaeger

7. Security Audit

istioctl analyze --all-namespaces

istioctl proxy-config secret <pod-name> -o json

kubectl get peerauthentication --all-namespaces

kubectl get authorizationpolicy --all-namespaces

cert_management = {

"Istio CA": "Built-in CA, Auto-rotation ทุก 24 ชม.",

"cert-manager": "External CA, Vault, Let's Encrypt",

"SPIFFE": "Identity: spiffe://cluster.local/ns/xxx/sa/yyy",

"Rotation": "อัตโนมัติ ไม่ต้อง Restart Pods",

}

monitoring = {

"Kiali": "Service Mesh Visualization, mTLS Status",

"Prometheus": "Metrics: requests, connections, SSL handshakes",

"Grafana": "Dashboards: Mesh, Service, Workload",

"Jaeger": "Distributed Tracing ระหว่าง Services",

}

print("Certificate Management:")

for tool, desc in cert_management.items():

print(f" {tool}: {desc}")

print(f"\nMonitoring:")

for tool, desc in monitoring.items():

print(f" {tool}: {desc}")

Best Practices

  • STRICT mTLS: บังคับ mTLS ทั้ง Mesh ไม่ใช้ PERMISSIVE ใน Production
  • AuthorizationPolicy: กำหนด Zero Trust ทุก Service ระบุ Callers ชัดเจน
  • Certificate Rotation: ตั้ง Auto-rotation สั้น (24 ชม.) ลด Risk
  • Namespace Isolation: แยก Namespace ตาม Tenant หรือ Team
  • Monitoring: ใช้ Kiali ดู mTLS Status, Prometheus Metrics, Jaeger Tracing
  • Audit: รัน istioctl analyze ตรวจสอบ Configuration เป็นประจำ

mTLS คืออะไร

Mutual TLS เข้ารหัสสองทาง Client Server ยืนยันตัวตน Certificate Service-to-Service Communication ป้องกัน Man-in-the-Middle Attack