🔒 Security

CASB

Cloud Access Security Broker

A security solution that sits between an organization and cloud service providers to enforce security policies. Provides visibility into cloud app usage, prevents data leaks, detects Shadow IT, and protects the organization from threats.

📖 Detailed Explanation

CASB (Cloud Access Security Broker) is a security policy enforcement point that sits between an organization's on-premises infrastructure and cloud service providers. When employees access various SaaS applications such as Salesforce, Office 365, Google Workspace, and Dropbox, the CASB monitors traffic in the middle and applies security policies. It is like installing a security checkpoint at the gateway to the cloud.

The background of CASB's emergence is the rapid spread of cloud services. As SaaS applications proliferated explosively in the early 2010s, the use of cloud services that the IT department could not see, known as Shadow IT, emerged as a serious security threat. Gartner defined the concept of CASB in 2012 and presented a way for companies to apply the same level of security control in cloud environments as on-premises.

CASB provides four core pillars (Four Pillars). First, Visibility identifies all cloud apps used by the organization and user activity. Second, Compliance supports adherence to regulations such as GDPR, HIPAA, and PCI-DSS. Third, Data Security prevents the leakage of sensitive data through DLP (Data Loss Prevention). Fourth, Threat Protection detects and blocks malware, account takeover, and insider threats.

In modern security architecture, CASB is evolving into a core component of SASE (Secure Access Service Edge) and Zero Trust. It has moved from a standalone solution to being integrated into SSE (Security Service Edge), providing cloud-native security together with SWG (Secure Web Gateway) and ZTNA (Zero Trust Network Access). In particular, as the spread of remote work means employees access the cloud from anywhere, the importance of CASB is growing even further.

💻 Code Example

# CASB API를 활용한 Shadow IT 탐지 및 앱 분류 예제 - Python
import requests
from datetime import datetime, timedelta
from typing import Dict, List
import json

class CASBClient:
    """CASB API 클라이언트 - 클라우드 앱 가시성 및 정책 관리"""

    def __init__(self, base_url: str, api_key: str):
        self.base_url = base_url
        self.headers = {
            "Authorization": f"Bearer {api_key}",
            "Content-Type": "application/json"
        }

    def discover_cloud_apps(self, days: int = 30) -> List[Dict]:
        """Shadow IT 탐지 - 조직에서 사용 중인 모든 클라우드 앱 발견"""
        params = {
            "timeRange": f"last_{days}_days",
            "includeUnsanctioned": True  # 미승인 앱 포함
        }

        response = requests.get(
            f"{self.base_url}/api/v1/discovery/apps",
            headers=self.headers,
            params=params
        )
        response.raise_for_status()

        apps = response.json()["apps"]
        return self._categorize_apps(apps)

    def _categorize_apps(self, apps: List[Dict]) -> List[Dict]:
        """앱을 위험도와 승인 상태에 따라 분류"""
        categorized = []
        for app in apps:
            risk_level = self._calculate_risk_score(app)
            categorized.append({
                "name": app["name"],
                "category": app["category"],
                "users": app["unique_users"],
                "data_volume_mb": app["data_transferred_mb"],
                "risk_level": risk_level,
                "sanction_status": app.get("sanction_status", "unknown"),
                "compliance_certifications": app.get("certifications", []),
                "recommendation": self._get_recommendation(risk_level, app)
            })
        return sorted(categorized, key=lambda x: x["risk_level"], reverse=True)

    def _calculate_risk_score(self, app: Dict) -> str:
        """클라우드 앱 위험도 점수 계산"""
        score = 0

        # 보안 인증 여부 확인
        certs = app.get("certifications", [])
        if "SOC2" not in certs:
            score += 20
        if "ISO27001" not in certs:
            score += 15

        # 데이터 암호화 지원
        if not app.get("encryption_at_rest"):
            score += 25
        if not app.get("encryption_in_transit"):
            score += 20

        # 인증 방식
        if "SSO" not in app.get("auth_methods", []):
            score += 15
        if "MFA" not in app.get("auth_methods", []):
            score += 20

        if score >= 60:
            return "high"
        elif score >= 30:
            return "medium"
        return "low"

    def _get_recommendation(self, risk_level: str, app: Dict) -> str:
        """위험도에 따른 권장 조치"""
        if risk_level == "high":
            return "즉시 차단 권장 - 대체 승인 앱 사용 유도"
        elif risk_level == "medium":
            return "모니터링 강화 - DLP 정책 적용 필요"
        return "승인 앱으로 등록 검토"

    def apply_dlp_policy(self, app_id: str, policy_config: Dict) -> Dict:
        """DLP(Data Loss Prevention) 정책 적용"""
        policy = {
            "app_id": app_id,
            "rules": [
                {
                    "name": "PII_Detection",
                    "patterns": ["주민등록번호", "신용카드번호", "여권번호"],
                    "action": "block_and_alert",
                    "severity": "critical"
                },
                {
                    "name": "Sensitive_Files",
                    "file_types": [".xlsx", ".docx", ".pdf"],
                    "keywords": ["기밀", "대외비", "confidential"],
                    "action": "encrypt_or_block",
                    "severity": "high"
                }
            ],
            **policy_config
        }

        response = requests.post(
            f"{self.base_url}/api/v1/dlp/policies",
            headers=self.headers,
            json=policy
        )
        response.raise_for_status()
        return response.json()

    def get_user_activity_anomalies(self, user_email: str = None) -> List[Dict]:
        """사용자 행위 이상 탐지 - 계정 탈취/내부자 위협"""
        params = {"detection_type": "anomaly"}
        if user_email:
            params["user"] = user_email

        response = requests.get(
            f"{self.base_url}/api/v1/ueba/alerts",
            headers=self.headers,
            params=params
        )
        response.raise_for_status()

        return response.json()["alerts"]


# 사용 예시
if __name__ == "__main__":
    casb = CASBClient(
        base_url="https://casb.example.com",
        api_key="your-api-key"
    )

    # Shadow IT 탐지
    discovered_apps = casb.discover_cloud_apps(days=30)

    print("=== Shadow IT 탐지 결과 ===")
    for app in discovered_apps[:10]:
        print(f"앱: {app['name']}")
        print(f"  - 사용자: {app['users']}명")
        print(f"  - 데이터 전송량: {app['data_volume_mb']}MB")
        print(f"  - 위험도: {app['risk_level']}")
        print(f"  - 권장 조치: {app['recommendation']}")
        print()
# CASB 정책 설정 파일 예제 - YAML
# 클라우드 앱 접근 제어, DLP, 위협 방지 정책 정의

casb_policy:
  name: "Enterprise Cloud Security Policy"
  version: "2.0"
  effective_date: "2024-01-01"

# 1. 클라우드 앱 분류 및 접근 제어
app_governance:
  sanctioned_apps:
    - name: "Microsoft 365"
      category: "productivity"
      risk_level: "low"
      allowed_actions: ["all"]

    - name: "Salesforce"
      category: "crm"
      risk_level: "low"
      allowed_actions: ["all"]
      dlp_enabled: true

    - name: "Slack"
      category: "collaboration"
      risk_level: "medium"
      allowed_actions: ["read", "write"]
      restrictions:
        - "no_file_upload_to_external"
        - "no_external_channel_join"

  unsanctioned_apps:
    default_action: "monitor_and_alert"
    high_risk_action: "block"
    categories_to_block:
      - "personal_storage"  # Dropbox 개인용, Google Drive 개인용
      - "social_media"
      - "gaming"

  shadow_it_response:
    discovery_interval: "daily"
    auto_categorization: true
    alert_threshold:
      users: 10        # 10명 이상 사용 시 알림
      data_volume_gb: 1  # 1GB 이상 전송 시 알림

# 2. DLP (Data Loss Prevention) 정책
dlp_policies:
  - name: "PII Protection"
    description: "개인식별정보 유출 방지"
    enabled: true
    detection_rules:
      - pattern: "주민등록번호"
        regex: "\\d{6}-[1-4]\\d{6}"
        action: "block"

      - pattern: "신용카드번호"
        regex: "\\d{4}[- ]?\\d{4}[- ]?\\d{4}[- ]?\\d{4}"
        action: "block"

      - pattern: "여권번호"
        regex: "[A-Z]{1,2}\\d{7,8}"
        action: "alert_and_encrypt"

    exceptions:
      - app: "HR System"
        users: ["hr-team@company.com"]

  - name: "Confidential Document Control"
    description: "기밀 문서 외부 공유 방지"
    enabled: true
    file_rules:
      - file_types: [".docx", ".xlsx", ".pptx", ".pdf"]
        keywords: ["기밀", "대외비", "Confidential", "Internal Only"]
        labels: ["CONFIDENTIAL", "RESTRICTED"]
        actions:
          external_share: "block"
          download: "watermark"
          print: "log_and_alert"

# 3. 위협 방지 (Threat Protection)
threat_protection:
  malware_detection:
    enabled: true
    scan_uploads: true
    scan_downloads: true
    quarantine_action: "isolate_and_alert"

  account_takeover_prevention:
    impossible_travel:
      enabled: true
      threshold_hours: 2  # 2시간 내 불가능한 이동 탐지
      action: "require_mfa"

    suspicious_login:
      enabled: true
      signals:
        - "new_device"
        - "new_location"
        - "tor_exit_node"
        - "anonymous_vpn"
      action: "block_and_verify"

  insider_threat:
    bulk_download_detection:
      threshold_files: 100
      threshold_size_gb: 5
      time_window_hours: 24
      action: "alert_and_investigate"

    off_hours_access:
      enabled: true
      business_hours: "09:00-18:00"
      timezone: "Asia/Seoul"
      action: "log_enhanced"

# 4. 컴플라이언스 모니터링
compliance:
  frameworks:
    - name: "GDPR"
      enabled: true
      requirements:
        - data_residency: "EU"
        - right_to_erasure: true
        - consent_management: true

    - name: "개인정보보호법"
      enabled: true
      requirements:
        - encryption_required: true
        - access_logging: true
        - retention_policy: "3_years"

  audit_logging:
    retention_days: 365
    export_to_siem: true
    include_events:
      - "login_success"
      - "login_failure"
      - "file_download"
      - "file_share"
      - "policy_violation"
      - "admin_action"
// CASB와 SIEM 연동 - Node.js
// CASB 알림을 SIEM으로 전달하여 통합 보안 모니터링 구현

const axios = require('axios');
const { Kafka } = require('kafkajs');

class CASBSIEMIntegration {
    constructor(config) {
        this.casbApiUrl = config.casbApiUrl;
        this.casbApiKey = config.casbApiKey;
        this.siemWebhook = config.siemWebhook;

        // Kafka for high-volume event streaming
        this.kafka = new Kafka({
            clientId: 'casb-siem-connector',
            brokers: config.kafkaBrokers
        });
        this.producer = this.kafka.producer();
    }

    async initialize() {
        await this.producer.connect();
        console.log('CASB-SIEM Integration initialized');
    }

    // CASB 이벤트를 SIEM 형식으로 변환
    transformToSIEMFormat(casbEvent) {
        return {
            timestamp: new Date(casbEvent.timestamp).toISOString(),
            source: 'CASB',
            event_type: this.mapEventType(casbEvent.type),
            severity: this.mapSeverity(casbEvent.risk_level),

            // Common Event Format (CEF) 필드
            cef: {
                version: 0,
                device_vendor: 'CASB_Vendor',
                device_product: 'Cloud Security',
                device_version: '3.0',
                signature_id: casbEvent.alert_id,
                name: casbEvent.alert_name,
                severity: casbEvent.risk_score
            },

            // 상세 정보
            details: {
                user: casbEvent.user_email,
                user_department: casbEvent.user_department,
                source_ip: casbEvent.source_ip,
                geo_location: casbEvent.geo_location,
                cloud_app: casbEvent.app_name,
                app_category: casbEvent.app_category,
                action_taken: casbEvent.action,
                policy_violated: casbEvent.policy_name,

                // 데이터 관련
                file_name: casbEvent.file_name,
                file_type: casbEvent.file_type,
                file_size_bytes: casbEvent.file_size,
                data_classification: casbEvent.data_classification,

                // DLP 관련
                dlp_patterns_matched: casbEvent.dlp_matches,
                sensitive_data_types: casbEvent.sensitive_data_types
            },

            // 위협 인텔리전스
            threat_intel: {
                indicators: casbEvent.threat_indicators,
                mitre_attack_techniques: casbEvent.mitre_techniques,
                confidence_score: casbEvent.confidence
            },

            // 대응 권장사항
            recommendations: this.getRecommendations(casbEvent)
        };
    }

    mapEventType(casbType) {
        const mapping = {
            'dlp_violation': 'Data Exfiltration Attempt',
            'malware_detected': 'Malware Detection',
            'account_compromise': 'Account Takeover',
            'impossible_travel': 'Suspicious Login',
            'shadow_it': 'Unauthorized App Usage',
            'policy_violation': 'Policy Violation',
            'bulk_download': 'Insider Threat',
            'external_share': 'Unauthorized Sharing'
        };
        return mapping[casbType] || 'Unknown Event';
    }

    mapSeverity(riskLevel) {
        const mapping = {
            'critical': 10,
            'high': 8,
            'medium': 5,
            'low': 2,
            'info': 1
        };
        return mapping[riskLevel] || 1;
    }

    getRecommendations(event) {
        const recommendations = [];

        if (event.type === 'account_compromise') {
            recommendations.push('사용자 세션 즉시 종료');
            recommendations.push('비밀번호 강제 재설정');
            recommendations.push('최근 활동 감사 로그 검토');
        }

        if (event.type === 'dlp_violation') {
            recommendations.push('해당 파일 격리 조치');
            recommendations.push('사용자 접근 권한 검토');
            recommendations.push('정보보호팀 에스컬레이션');
        }

        if (event.type === 'shadow_it' && event.risk_level === 'high') {
            recommendations.push('해당 앱 즉시 차단');
            recommendations.push('대체 승인 앱 안내');
            recommendations.push('사용자 보안 교육 필요');
        }

        return recommendations;
    }

    // 실시간 이벤트 스트리밍
    async streamToSIEM(casbEvent) {
        const siemEvent = this.transformToSIEMFormat(casbEvent);

        // Kafka로 이벤트 발행
        await this.producer.send({
            topic: 'security-events',
            messages: [{
                key: casbEvent.alert_id,
                value: JSON.stringify(siemEvent),
                headers: {
                    'source': 'casb',
                    'severity': String(siemEvent.severity)
                }
            }]
        });

        // 고위험 이벤트는 웹훅으로도 즉시 전달
        if (siemEvent.severity >= 8) {
            await this.sendHighPriorityAlert(siemEvent);
        }

        return siemEvent;
    }

    async sendHighPriorityAlert(event) {
        try {
            await axios.post(this.siemWebhook, {
                alert: event,
                priority: 'HIGH',
                require_acknowledgment: true
            });
            console.log(`High priority alert sent: ${event.details.cloud_app}`);
        } catch (error) {
            console.error('Failed to send high priority alert:', error.message);
        }
    }

    // CASB 이벤트 폴링 및 처리
    async pollAndProcess(intervalMs = 60000) {
        console.log('Starting CASB event polling...');

        setInterval(async () => {
            try {
                const response = await axios.get(
                    `${this.casbApiUrl}/api/v1/alerts`,
                    {
                        headers: { 'Authorization': `Bearer ${this.casbApiKey}` },
                        params: {
                            since: new Date(Date.now() - intervalMs).toISOString(),
                            status: 'new'
                        }
                    }
                );

                for (const event of response.data.alerts) {
                    await this.streamToSIEM(event);
                }

                console.log(`Processed ${response.data.alerts.length} events`);
            } catch (error) {
                console.error('Polling error:', error.message);
            }
        }, intervalMs);
    }
}

// 사용 예시
const integration = new CASBSIEMIntegration({
    casbApiUrl: 'https://casb.example.com',
    casbApiKey: process.env.CASB_API_KEY,
    siemWebhook: 'https://siem.example.com/webhook/casb',
    kafkaBrokers: ['kafka-1:9092', 'kafka-2:9092']
});

integration.initialize().then(() => {
    integration.pollAndProcess(60000);  // 1분 간격 폴링
});

🗣️ Say It Like This in Practice

💬 In a Cloud Security Strategy Meeting
"According to the current Shadow IT analysis, more than 150 unapproved cloud apps were discovered. We need to introduce a CASB to gain visibility into all cloud traffic, block high-risk apps, and build a framework that manages the apps needed for work through an approval process."
💬 In a DLP Policy Review Meeting
"With CASB's DLP feature, we are blocking sensitive information such as resident registration numbers and credit card numbers from being shared externally from cloud apps in real time. Last month alone, we stopped 47 data leakage attempts, and 12 of them were mistakes rather than malicious intent, so we linked them to user training."
💬 In a Security Architecture Design
"For the SASE transition, we will integrate CASB with SWG and ZTNA. If we migrate the CASB we currently operate independently to an SSE (Security Service Edge) platform, we can apply consistent policies from endpoints to the cloud with a single agent."

⚠️ Cautions & Best Practices

❌
A policy that blocks all apps unconditionally

If you block every Shadow IT you discover unconditionally, employees will look for workarounds or work efficiency will drop. Assess the risk level and block only high-risk apps, monitor medium-risk ones, and formalize low-risk ones through an approval process.

❌
Deployment using only API mode

Using only API mode (Out-of-band) makes real-time blocking impossible and allows only after-the-fact detection. Apply Proxy mode (Inline) to apps that require sensitive data protection to implement real-time DLP and threat blocking.

❌
False positives caused by excessive DLP rules

Too many pattern-matching rules cause false positives (False Positive) and disrupt work. Start with the core sensitive information, use machine learning-based classification, and set exception policies appropriately.

✅
CASB Best Practices

Implement phased deployment (visibility → monitoring → control), integrated security operations through SIEM/SOAR integration, periodic re-evaluation of app risk levels, activation of user behavior analytics (UEBA), and integration with a Zero Trust architecture. For CASB, continuous policy tuning matters more than adoption.

🔗 Related Terms

📚 Learn More