🔒 Security

Zero Trust

Zero Trust (Never Trust, Always Verify)

A modern security model based on the principles "Never Trust, Always Verify" and "Assume Breach." Unlike traditional perimeter-based security (Castle-and-Moat), it continuously verifies every access by every user, device, and application regardless of network location. NIST SP 800-207 defines the standard framework, and NIST SP 1800-35 in 2025 presented 19 real-world implementation models together with 24 vendors.

📖 Detailed Explanation

Zero Trust is a security model first proposed in 2010 by John Kindervag of Forrester Research, and it emerged to overcome the limitations of traditional "Perimeter Security." The earlier model assumed that "the internal network is trusted and the outside is untrusted," but with the adoption of the cloud, the spread of remote work, and the increase in insider threats, the network perimeter lost its meaning. Zero Trust defines identity, rather than location, as the new security perimeter.

NIST SP 800-207 defines the core principles of Zero Trust Architecture (ZTA): (1) all data sources and computing services are considered resources, (2) all communication is protected regardless of network location, (3) access to individual resources is granted on a per-session basis, (4) access is determined by dynamic policy (user identity, application, device state, etc.), (5) the integrity and security posture of all assets are continuously monitored. In 2025, NIST SP 1800-35 presented 19 real-world implementation models in collaboration with 24 vendors.

The 7 core areas (Pillars) of Zero Trust are Identity, Device, Network, Application, Data, Infrastructure, and Analytics/Visibility. In each area, maturity is raised through the Foundation (basic), Advanced (high-level), and Optimal (optimized) levels. For example, in the Identity area, Foundation is SSO+MFA, Advanced is phishing-resistant MFA, and Optimal is continuous authentication and behavioral analytics.

In actual implementations, Zero Trust is realized through technologies such as ZTNA (Zero Trust Network Access), SASE (Secure Access Service Edge), and microsegmentation. It verifies the JWT token on every API request, checks the device state (OS version, security patches, EDR status), and analyzes the access context (time, location, behavior patterns) to dynamically allow access or require additional authentication. Gartner predicted that by 2026, 75% of U.S. federal agencies would fail to implement Zero Trust due to a lack of funding and expertise, but an incremental approach (Identity-first) is recommended.

💻 Code Example

// Zero Trust API 미들웨어 - Node.js/Express
// 모든 요청을 검증: 토큰, 기기 상태, 컨텍스트
const express = require('express');
const jwt = require('jsonwebtoken');
const app = express();

// Zero Trust 컨텍스트 수집 미들웨어
function collectContext(req, res, next) {
    req.zeroTrustContext = {
        // 요청 컨텍스트
        timestamp: new Date().toISOString(),
        ip: req.ip || req.headers['x-forwarded-for'],
        userAgent: req.headers['user-agent'],

        // 기기 상태 (클라이언트가 전송)
        deviceId: req.headers['x-device-id'],
        deviceHealth: req.headers['x-device-health'],  // JSON 인코딩
        osVersion: req.headers['x-os-version'],

        // 위치 정보
        geoLocation: req.headers['x-geo-location'],

        // 세션 정보
        sessionId: req.headers['x-session-id']
    };
    next();
}

// Zero Trust 검증 미들웨어
function zeroTrustVerify(options = {}) {
    return async (req, res, next) => {
        const ctx = req.zeroTrustContext;

        try {
            // 1. 토큰 검증 (항상 검증)
            const authHeader = req.headers.authorization;
            if (!authHeader?.startsWith('Bearer ')) {
                return res.status(401).json({
                    error: 'Missing token',
                    action: 'LOGIN_REQUIRED'
                });
            }

            const token = authHeader.substring(7);
            const decoded = jwt.verify(token, process.env.JWT_SECRET);
            req.user = decoded;

            // 2. 기기 상태 검증 (Assume Breach)
            const deviceHealth = await verifyDeviceHealth(ctx);
            if (!deviceHealth.compliant) {
                return res.status(403).json({
                    error: 'Device not compliant',
                    reason: deviceHealth.reason,
                    action: 'DEVICE_REMEDIATION_REQUIRED'
                });
            }

            // 3. 접근 컨텍스트 평가
            const riskScore = await evaluateRisk(req.user, ctx, options.resource);

            // 4. 리스크 기반 동적 접근 제어
            if (riskScore > 80) {
                // 고위험: 접근 거부
                await logSecurityEvent('HIGH_RISK_ACCESS_DENIED', req);
                return res.status(403).json({
                    error: 'Access denied due to high risk',
                    riskScore,
                    action: 'CONTACT_SECURITY'
                });
            } else if (riskScore > 50) {
                // 중위험: Step-up 인증 요구
                const stepUpCompleted = await checkStepUpAuth(req.user, ctx.sessionId);
                if (!stepUpCompleted) {
                    return res.status(403).json({
                        error: 'Additional authentication required',
                        riskScore,
                        action: 'STEP_UP_AUTH_REQUIRED',
                        stepUpMethods: ['FIDO2', 'TOTP']
                    });
                }
            }

            // 5. 권한 검증 (최소 권한 원칙)
            if (options.permission) {
                const hasAccess = await checkPermission(
                    req.user,
                    options.permission,
                    options.resource
                );
                if (!hasAccess) {
                    return res.status(403).json({
                        error: 'Insufficient permissions',
                        required: options.permission
                    });
                }
            }

            // 6. 감사 로깅 (항상)
            await logAccessEvent({
                user: req.user.sub,
                resource: options.resource,
                action: req.method,
                context: ctx,
                riskScore,
                decision: 'ALLOW'
            });

            next();

        } catch (error) {
            if (error.name === 'TokenExpiredError') {
                return res.status(401).json({
                    error: 'Token expired',
                    action: 'REFRESH_TOKEN'
                });
            }
            throw error;
        }
    };
}

// 기기 상태 검증
async function verifyDeviceHealth(ctx) {
    if (!ctx.deviceHealth) {
        return { compliant: false, reason: 'Device health not reported' };
    }

    const health = JSON.parse(ctx.deviceHealth);

    // 최소 보안 요구사항
    const requirements = {
        osUpdated: health.osLastPatched > Date.now() - 30 * 24 * 60 * 60 * 1000,
        firewallEnabled: health.firewall === true,
        antivirusActive: health.antivirus?.status === 'active',
        diskEncrypted: health.diskEncryption === true,
        edrRunning: health.edrStatus === 'running'
    };

    const compliant = Object.values(requirements).every(v => v);
    const failedChecks = Object.entries(requirements)
        .filter(([, v]) => !v)
        .map(([k]) => k);

    return { compliant, failedChecks, reason: failedChecks.join(', ') };
}

// 리스크 평가 엔진
async function evaluateRisk(user, ctx, resource) {
    let riskScore = 0;

    // 시간 기반 리스크
    const hour = new Date().getHours();
    if (hour < 6 || hour > 22) riskScore += 20;  // 비업무 시간

    // 위치 기반 리스크
    const isKnownLocation = await isUserKnownLocation(user.sub, ctx.geoLocation);
    if (!isKnownLocation) riskScore += 30;  // 새로운 위치

    // 행동 기반 리스크 (UEBA)
    const behaviorAnomaly = await detectBehaviorAnomaly(user.sub, ctx);
    riskScore += behaviorAnomaly.score;

    // 리소스 민감도
    const resourceSensitivity = await getResourceSensitivity(resource);
    riskScore += resourceSensitivity * 10;

    // 최근 실패한 인증 시도
    const recentFailures = await getRecentAuthFailures(user.sub);
    riskScore += recentFailures * 5;

    return Math.min(riskScore, 100);
}

// Zero Trust 적용된 라우트
app.use(collectContext);

app.get('/api/documents/:id',
    zeroTrustVerify({ permission: 'documents:read', resource: 'documents' }),
    async (req, res) => {
        const doc = await getDocument(req.params.id);
        res.json(doc);
    }
);

app.delete('/api/users/:id',
    zeroTrustVerify({ permission: 'users:delete', resource: 'users' }),
    async (req, res) => {
        await deleteUser(req.params.id);
        res.json({ success: true });
    }
);

app.listen(3000);
# Zero Trust Policy Decision Point (PDP) - Python
# 중앙화된 정책 엔진으로 모든 접근 결정
from dataclasses import dataclass
from typing import Optional, List, Dict
from datetime import datetime
from enum import Enum
import asyncio

class Decision(Enum):
    ALLOW = "allow"
    DENY = "deny"
    STEP_UP = "step_up"  # 추가 인증 필요

@dataclass
class Subject:
    """접근 주체 (사용자/서비스)"""
    id: str
    type: str  # 'user' | 'service'
    roles: List[str]
    department: str
    auth_level: int  # 1=password, 2=MFA, 3=FIDO2
    session_start: datetime

@dataclass
class Device:
    """기기 상태"""
    id: str
    compliant: bool
    os_version: str
    last_seen: datetime
    risk_score: int

@dataclass
class Resource:
    """접근 대상 리소스"""
    id: str
    type: str
    sensitivity: int  # 1-5
    owner: str
    department: str

@dataclass
class Environment:
    """환경 컨텍스트"""
    timestamp: datetime
    ip_address: str
    geo_location: str
    is_corporate_network: bool

@dataclass
class AccessRequest:
    """접근 요청"""
    subject: Subject
    device: Device
    resource: Resource
    action: str
    environment: Environment

@dataclass
class AccessDecision:
    """접근 결정"""
    decision: Decision
    reason: str
    risk_score: int
    required_auth_level: Optional[int] = None
    obligations: Optional[List[str]] = None

class ZeroTrustPDP:
    """Zero Trust Policy Decision Point"""

    def __init__(self):
        self.policies = []

    def evaluate(self, request: AccessRequest) -> AccessDecision:
        """모든 정책을 평가하여 접근 결정"""
        risk_score = self._calculate_risk(request)

        # 정책 체인 평가
        for policy in self.policies:
            result = policy.evaluate(request, risk_score)
            if result.decision == Decision.DENY:
                return result

        # 리스크 기반 최종 결정
        if risk_score > 80:
            return AccessDecision(
                decision=Decision.DENY,
                reason="Risk score too high",
                risk_score=risk_score
            )
        elif risk_score > 50:
            required_level = 3 if risk_score > 70 else 2
            if request.subject.auth_level < required_level:
                return AccessDecision(
                    decision=Decision.STEP_UP,
                    reason="Additional authentication required",
                    risk_score=risk_score,
                    required_auth_level=required_level
                )

        return AccessDecision(
            decision=Decision.ALLOW,
            reason="All policies passed",
            risk_score=risk_score,
            obligations=["LOG_ACCESS", "ENCRYPT_RESPONSE"]
        )

    def _calculate_risk(self, request: AccessRequest) -> int:
        """컨텍스트 기반 리스크 점수 계산"""
        score = 0

        # 기기 리스크
        if not request.device.compliant:
            score += 40
        score += request.device.risk_score

        # 시간 기반 리스크
        hour = request.environment.timestamp.hour
        if hour < 6 or hour > 22:
            score += 15

        # 위치 기반 리스크
        if not request.environment.is_corporate_network:
            score += 20

        # 리소스 민감도
        score += request.resource.sensitivity * 5

        # 인증 강도 (낮으면 리스크 증가)
        score += (3 - request.subject.auth_level) * 10

        return min(score, 100)


class DeviceCompliancePolicy:
    """기기 준수 정책"""
    def evaluate(self, request: AccessRequest, risk_score: int) -> AccessDecision:
        if not request.device.compliant:
            return AccessDecision(
                decision=Decision.DENY,
                reason="Device not compliant with security policy",
                risk_score=risk_score
            )
        return AccessDecision(Decision.ALLOW, "Device compliant", risk_score)


class SensitiveResourcePolicy:
    """민감한 리소스 접근 정책"""
    def evaluate(self, request: AccessRequest, risk_score: int) -> AccessDecision:
        if request.resource.sensitivity >= 4:
            # 고민감도 리소스는 FIDO2 필수
            if request.subject.auth_level < 3:
                return AccessDecision(
                    decision=Decision.STEP_UP,
                    reason="High-sensitivity resource requires FIDO2",
                    risk_score=risk_score,
                    required_auth_level=3
                )
            # 같은 부서만 접근 가능
            if request.subject.department != request.resource.department:
                return AccessDecision(
                    decision=Decision.DENY,
                    reason="Cross-department access denied for sensitive resource",
                    risk_score=risk_score
                )
        return AccessDecision(Decision.ALLOW, "Resource access allowed", risk_score)


# 사용 예시
pdp = ZeroTrustPDP()
pdp.policies = [
    DeviceCompliancePolicy(),
    SensitiveResourcePolicy()
]

# 접근 요청 평가
request = AccessRequest(
    subject=Subject(
        id="user_123",
        type="user",
        roles=["developer"],
        department="engineering",
        auth_level=2,  # MFA 완료
        session_start=datetime.now()
    ),
    device=Device(
        id="device_456",
        compliant=True,
        os_version="macOS 14.2",
        last_seen=datetime.now(),
        risk_score=10
    ),
    resource=Resource(
        id="doc_789",
        type="document",
        sensitivity=3,
        owner="user_111",
        department="engineering"
    ),
    action="read",
    environment=Environment(
        timestamp=datetime.now(),
        ip_address="10.0.0.1",
        geo_location="Seoul, KR",
        is_corporate_network=True
    )
)

decision = pdp.evaluate(request)
print(f"Decision: {decision.decision.value}")
print(f"Reason: {decision.reason}")
print(f"Risk Score: {decision.risk_score}")
# Zero Trust Policy - Open Policy Agent (OPA)
# 중앙화된 정책 관리로 마이크로서비스 전체에 일관된 Zero Trust 적용

package zerotrust

import future.keywords.if
import future.keywords.in

# 기본값: 접근 거부 (Deny by default)
default allow := false
default decision := {"allowed": false, "reason": "No matching policy"}

# 리스크 점수 계산
risk_score := score if {
    device_risk := device_risk_score
    time_risk := time_risk_score
    location_risk := location_risk_score
    resource_risk := resource_risk_score
    auth_risk := auth_risk_score

    score := min([device_risk + time_risk + location_risk + resource_risk + auth_risk, 100])
}

# 기기 리스크
device_risk_score := 40 if {
    not input.device.compliant
} else := input.device.risk_score

# 시간 기반 리스크 (비업무 시간)
time_risk_score := 15 if {
    hour := time.clock(time.now_ns())[0]
    hour < 6
} else := 15 if {
    hour := time.clock(time.now_ns())[0]
    hour > 22
} else := 0

# 위치 기반 리스크
location_risk_score := 20 if {
    not input.environment.is_corporate_network
} else := 0

# 리소스 민감도 리스크
resource_risk_score := input.resource.sensitivity * 5

# 인증 강도 리스크
auth_risk_score := (3 - input.subject.auth_level) * 10

# ===== Zero Trust 정책 =====

# 정책 1: 기기 준수 필수
decision := {"allowed": false, "reason": "Device not compliant", "action": "REMEDIATE_DEVICE"} if {
    not input.device.compliant
}

# 정책 2: 고위험 접근 차단
decision := {"allowed": false, "reason": "Risk score too high", "risk_score": risk_score} if {
    risk_score > 80
}

# 정책 3: 중위험 시 Step-up 인증 요구
decision := {
    "allowed": false,
    "reason": "Step-up authentication required",
    "risk_score": risk_score,
    "required_auth_level": required_level,
    "action": "STEP_UP_AUTH"
} if {
    risk_score > 50
    risk_score <= 80
    required_level := 3 if risk_score > 70 else 2
    input.subject.auth_level < required_level
}

# 정책 4: 민감한 리소스는 같은 부서만
decision := {
    "allowed": false,
    "reason": "Cross-department access denied for sensitive resource"
} if {
    input.resource.sensitivity >= 4
    input.subject.department != input.resource.department
}

# 정책 5: 민감한 리소스는 FIDO2 필수
decision := {
    "allowed": false,
    "reason": "Sensitive resource requires FIDO2",
    "required_auth_level": 3,
    "action": "STEP_UP_AUTH"
} if {
    input.resource.sensitivity >= 4
    input.subject.auth_level < 3
}

# 모든 정책 통과 시 허용
allow if {
    input.device.compliant
    risk_score <= 80
    not (risk_score > 50; input.subject.auth_level < 2)
    not (input.resource.sensitivity >= 4; input.subject.department != input.resource.department)
    not (input.resource.sensitivity >= 4; input.subject.auth_level < 3)
}

decision := {
    "allowed": true,
    "reason": "All policies passed",
    "risk_score": risk_score,
    "obligations": ["LOG_ACCESS", "ENCRYPT_RESPONSE"]
} if {
    allow
}

# ===== API 호출 예시 =====
# curl -X POST http://localhost:8181/v1/data/zerotrust/decision \
#   -H "Content-Type: application/json" \
#   -d '{
#     "input": {
#       "subject": {"id": "user_123", "auth_level": 2, "department": "engineering"},
#       "device": {"compliant": true, "risk_score": 10},
#       "resource": {"id": "doc_456", "sensitivity": 3, "department": "engineering"},
#       "action": "read",
#       "environment": {"is_corporate_network": true}
#     }
#   }'

🗣️ Say It Like This in Practice

💬 In a Security Architecture Meeting
"VPN-based access is insufficient from a Zero Trust perspective. Trusting all internal resources based on a VPN connection alone is the 'Castle-and-Moat' model. We need to move to ZTNA, control access per resource, and verify the user identity and device state on every request. Starting with Identity-first and expanding incrementally is the realistic approach."
💬 In a Technical Review
"Only verifying tokens at the API gateway is not Zero Trust. We also need to check device state, evaluate the access context (time, location), and apply risk-based dynamic authorization. Let's add logic that requires Step-up authentication when the risk score is high and blocks access when it is very high. Centralizing policy with OPA lets us apply it consistently across services."
💬 In an Executive Report
"Adopting Zero Trust is a journey of more than a year. NIST recommends raising maturity through the Foundation-Advanced-Optimal stages across five areas: Identity, Device, Network, Application, and Data. We propose a roadmap that first applies phishing-resistant MFA to all users in the Identity area, and then expands to device state verification."

⚠️ Cautions & Best Practices

❌
Big-Bang Transition Attempts

Attempting to implement Zero Trust completely all at once has a high probability of failure. Gartner predicts that by 2026, 75% of organizations will fail due to a lack of funding and expertise. Implement it incrementally with an Identity-first (identity management first) approach.

❌
Missing Device State Verification

Under the "Assume Breach" principle, a device is always a potential threat. Token verification alone is not enough. Verify OS version, security patches, disk encryption, EDR status, and so on, and block non-compliant devices from accessing sensitive resources.

❌
Using Only Static Policies

Granting access based on roles alone is not Zero Trust. A dynamic risk assessment that integrates context (time, location, behavior patterns, device state) is needed. If the risk is high, require additional authentication or deny access.

✅
Zero Trust Best Practices

Refer to NIST SP 800-207 and CISA ZTMM. Start with Identity, apply MFA enterprise-wide, and gradually expand to the Device, Network, Application, and Data areas. Maintain consistency with a centralized policy engine (such as OPA), and log all access to ensure visibility.

🔗 Related Terms

📚 Learn More