πŸ”’ Security

SOC

Security Operations Center

Security Operations Center. 24/7 security monitoring and response.

πŸ“– Detailed Explanation

SOC (Security Operations Center) is a centralized security organization that monitors an organization's IT infrastructure, networks, and applications 24 hours a day, 365 days a year, and detects, analyzes, and responds to cyber threats. A SOC team, composed of security analysts, security engineers, and a SOC manager, protects the organization using a variety of security tools such as SIEM, SOAR, EDR, and threat intelligence platforms.

SOC operations are generally divided into a three-tier structure. Tier 1 (junior analysts) monitors SIEM alerts and performs initial triage. Among the thousands of alerts each day, they identify real threats and escalate them to Tier 2. Tier 2 (intermediate analysts) is responsible for in-depth investigation, determining the scope of a breach, and response actions. Tier 3 (senior analysts/threat hunters) performs advanced threat analysis, forensics, threat hunting, and security tool tuning.

Modern SOCs are actively adopting AI/ML-based automation. They analyze log data collected from the SIEM with machine learning models to detect anomalies, and automate repetitive response tasks through SOAR (Security Orchestration, Automation and Response). This reduces MTTR (Mean Time To Respond) and alleviates analysts' Alert Fatigue. UEBA (User and Entity Behavior Analytics) learns the normal behavior patterns of users and entities to detect insider threats.

SOC maturity is evaluated along three axes: people, processes, and technology. A mature SOC has detection rules mapped to the MITRE ATT&CK framework, documented playbooks, regular red team/purple team exercises, and KPI-based performance measurement. It also integrates threat intelligence (TI) to reflect the latest attack techniques and IoCs (Indicators of Compromise) in its detection rules. As cloud environments expand, integration with cloud security tools such as CSPM and CWPP is also essential.

πŸ’» Code Example

SIEM Alert Auto-Triage (Python)

import json
from dataclasses import dataclass
from enum import Enum
from datetime import datetime
from typing import Optional, List

class Severity(Enum):
    LOW = "low"
    MEDIUM = "medium"
    HIGH = "high"
    CRITICAL = "critical"

class AlertStatus(Enum):
    NEW = "new"
    INVESTIGATING = "investigating"
    ESCALATED = "escalated"
    FALSE_POSITIVE = "false_positive"
    RESOLVED = "resolved"

@dataclass
class SecurityAlert:
    alert_id: str
    source: str  # SIEM, EDR, Firewall, etc.
    timestamp: datetime
    severity: Severity
    title: str
    description: str
    source_ip: Optional[str] = None
    dest_ip: Optional[str] = None
    user: Optional[str] = None
    mitre_tactic: Optional[str] = None
    mitre_technique: Optional[str] = None
    ioc: Optional[List[str]] = None
    status: AlertStatus = AlertStatus.NEW

class SOCAlertTriager:
    """Tier 1 μžλ™ λΆ„λ₯˜ μ‹œμŠ€ν…œ"""

    def __init__(self):
        # μ•Œλ €μ§„ μ–‘μ„± νŒ¨ν„΄ (False Positive 필터링)
        self.known_benign = {
            "scheduled_scan": ["Vulnerability Scanner", "Nessus", "Qualys"],
            "backup_traffic": ["backup.internal.com", "10.0.100."],
            "monitoring": ["prometheus", "grafana", "nagios"]
        }

        # κ³ μœ„ν—˜ νŒ¨ν„΄ (μ¦‰μ‹œ μ—μŠ€μ»¬λ ˆμ΄μ…˜)
        self.high_risk_patterns = {
            "ransomware_extension": [".encrypted", ".locked", ".crypto"],
            "c2_domains": ["evil.com", "malware.xyz"],  # TI 연동 ν•„μš”
            "lateral_movement": ["psexec", "wmic", "mimikatz"]
        }

        # MITRE ATT&CK λ§€ν•‘
        self.critical_techniques = [
            "T1486",  # Data Encrypted for Impact (Ransomware)
            "T1003",  # OS Credential Dumping
            "T1021",  # Remote Services
            "T1071",  # Application Layer Protocol (C2)
        ]

    def triage(self, alert: SecurityAlert) -> dict:
        """μ•Œλ¦Ό μžλ™ λΆ„λ₯˜ 및 λŒ€μ‘ ꢌ고"""
        result = {
            "alert_id": alert.alert_id,
            "original_severity": alert.severity.value,
            "adjusted_severity": alert.severity.value,
            "action": "investigate",
            "reason": [],
            "auto_remediation": None
        }

        # 1. False Positive 필터링
        if self._is_known_benign(alert):
            result["action"] = "auto_close"
            result["adjusted_severity"] = Severity.LOW.value
            result["reason"].append("Known benign activity")
            alert.status = AlertStatus.FALSE_POSITIVE
            return result

        # 2. κ³ μœ„ν—˜ νŒ¨ν„΄ 탐지 -> μžλ™ μ—μŠ€μ»¬λ ˆμ΄μ…˜
        high_risk_match = self._check_high_risk(alert)
        if high_risk_match:
            result["action"] = "escalate_tier2"
            result["adjusted_severity"] = Severity.CRITICAL.value
            result["reason"].append(f"High-risk pattern: {high_risk_match}")
            alert.status = AlertStatus.ESCALATED
            return result

        # 3. MITRE ATT&CK 기반 μš°μ„ μˆœμœ„ μ‘°μ •
        if alert.mitre_technique in self.critical_techniques:
            result["adjusted_severity"] = Severity.HIGH.value
            result["action"] = "prioritize"
            result["reason"].append(f"Critical MITRE technique: {alert.mitre_technique}")

        # 4. μžλ™ λŒ€μ‘ μΆ”μ²œ
        result["auto_remediation"] = self._suggest_remediation(alert)

        return result

    def _is_known_benign(self, alert: SecurityAlert) -> bool:
        """μ•Œλ €μ§„ μ–‘μ„± ν™œλ™ 확인"""
        for category, patterns in self.known_benign.items():
            for pattern in patterns:
                if pattern.lower() in alert.description.lower():
                    return True
                if alert.source_ip and pattern in alert.source_ip:
                    return True
        return False

    def _check_high_risk(self, alert: SecurityAlert) -> Optional[str]:
        """κ³ μœ„ν—˜ νŒ¨ν„΄ 확인"""
        for category, patterns in self.high_risk_patterns.items():
            for pattern in patterns:
                if pattern.lower() in alert.description.lower():
                    return f"{category}: {pattern}"
        return None

    def _suggest_remediation(self, alert: SecurityAlert) -> Optional[dict]:
        """μžλ™ λŒ€μ‘ μ•‘μ…˜ μΆ”μ²œ"""
        if "brute_force" in alert.title.lower():
            return {
                "type": "block_ip",
                "target": alert.source_ip,
                "duration": "24h",
                "requires_approval": False
            }
        if "malware" in alert.title.lower() and alert.dest_ip:
            return {
                "type": "isolate_host",
                "target": alert.dest_ip,
                "requires_approval": True  # Tier 2 승인 ν•„μš”
            }
        return None

# μ‚¬μš© 예제
triager = SOCAlertTriager()

alert = SecurityAlert(
    alert_id="ALERT-2024-12345",
    source="CrowdStrike EDR",
    timestamp=datetime.now(),
    severity=Severity.MEDIUM,
    title="Suspicious Process Execution",
    description="mimikatz.exe executed by SYSTEM",
    source_ip="10.0.50.100",
    user="SYSTEM",
    mitre_tactic="Credential Access",
    mitre_technique="T1003"
)

result = triager.triage(alert)
print(json.dumps(result, indent=2))
# {
#   "alert_id": "ALERT-2024-12345",
#   "original_severity": "medium",
#   "adjusted_severity": "critical",
#   "action": "escalate_tier2",
#   "reason": ["High-risk pattern: lateral_movement: mimikatz"],
#   ...
# }

SOAR Playbook Execution Example

import asyncio
from abc import ABC, abstractmethod
from typing import List, Dict, Any

class PlaybookAction(ABC):
    """Playbook μ•‘μ…˜ κΈ°λ³Έ 클래슀"""

    @abstractmethod
    async def execute(self, context: Dict[str, Any]) -> Dict[str, Any]:
        pass

class EnrichWithThreatIntel(PlaybookAction):
    """μœ„ν˜‘ μΈν…”λ¦¬μ „μŠ€λ‘œ IoC 쑰회"""

    async def execute(self, context: Dict[str, Any]) -> Dict[str, Any]:
        ioc = context.get("source_ip")
        # VirusTotal, AbuseIPDB, AlienVault OTX λ“± 쑰회
        ti_result = await self._query_threat_intel(ioc)
        return {"threat_intel": ti_result, "ioc_malicious": ti_result.get("score", 0) > 70}

    async def _query_threat_intel(self, ioc: str) -> dict:
        # μ‹€μ œλ‘œλŠ” TI API 호좜
        await asyncio.sleep(0.1)
        return {"ioc": ioc, "score": 85, "categories": ["malware", "c2"]}

class QuerySIEMLogs(PlaybookAction):
    """SIEMμ—μ„œ κ΄€λ ¨ 둜그 쑰회"""

    async def execute(self, context: Dict[str, Any]) -> Dict[str, Any]:
        source_ip = context.get("source_ip")
        timerange = context.get("timerange", "24h")

        # Elasticsearch/Splunk 쿼리
        query = f"source_ip:{source_ip} AND @timestamp:[now-{timerange} TO now]"
        results = await self._search_siem(query)

        return {
            "related_events": len(results),
            "affected_hosts": list(set(r.get("dest_ip") for r in results)),
            "users_involved": list(set(r.get("user") for r in results))
        }

    async def _search_siem(self, query: str) -> List[dict]:
        await asyncio.sleep(0.2)
        return [{"dest_ip": "10.0.1.50", "user": "admin"}]

class IsolateHost(PlaybookAction):
    """EDR을 ν†΅ν•œ 호슀트 격리"""

    async def execute(self, context: Dict[str, Any]) -> Dict[str, Any]:
        host = context.get("target_host")
        if not context.get("approved", False):
            return {"status": "pending_approval", "host": host}

        # CrowdStrike/Defender ATP API 호좜
        result = await self._isolate_via_edr(host)
        return {"status": "isolated", "host": host, "edr_response": result}

    async def _isolate_via_edr(self, host: str) -> dict:
        await asyncio.sleep(0.5)
        return {"success": True, "isolation_id": "ISO-12345"}

class SOARPlaybook:
    """SOAR Playbook μ‹€ν–‰κΈ°"""

    def __init__(self, name: str, actions: List[PlaybookAction]):
        self.name = name
        self.actions = actions
        self.execution_log = []

    async def execute(self, initial_context: Dict[str, Any]) -> Dict[str, Any]:
        context = initial_context.copy()

        for action in self.actions:
            action_name = action.__class__.__name__
            print(f"[{self.name}] Executing: {action_name}")

            try:
                result = await action.execute(context)
                context.update(result)
                self.execution_log.append({
                    "action": action_name,
                    "status": "success",
                    "result": result
                })
            except Exception as e:
                self.execution_log.append({
                    "action": action_name,
                    "status": "failed",
                    "error": str(e)
                })
                raise

        return context

# Phishing Response Playbook
phishing_playbook = SOARPlaybook(
    name="Phishing Incident Response",
    actions=[
        EnrichWithThreatIntel(),
        QuerySIEMLogs(),
        # BlockSenderInEmailGateway(),
        # NotifyAffectedUsers(),
        # CreateJiraTicket(),
    ]
)

# μ‹€ν–‰
async def main():
    result = await phishing_playbook.execute({
        "alert_id": "ALERT-2024-67890",
        "source_ip": "203.0.113.100",
        "email_subject": "Urgent: Password Reset Required"
    })
    print(f"Playbook completed. Affected hosts: {result.get('affected_hosts')}")

asyncio.run(main())

SOC Dashboard Metrics Collection

from datetime import datetime, timedelta
from dataclasses import dataclass
from typing import Dict, List
import statistics

@dataclass
class SOCMetrics:
    """SOC KPI λ©”νŠΈλ¦­"""
    period_start: datetime
    period_end: datetime

    # λ³Όλ₯¨ λ©”νŠΈλ¦­
    total_alerts: int = 0
    alerts_by_severity: Dict[str, int] = None
    alerts_by_source: Dict[str, int] = None

    # νš¨μœ¨μ„± λ©”νŠΈλ¦­
    mttd: float = 0.0  # Mean Time To Detect (λΆ„)
    mttr: float = 0.0  # Mean Time To Respond (λΆ„)
    mttc: float = 0.0  # Mean Time To Close (λΆ„)

    # ν’ˆμ§ˆ λ©”νŠΈλ¦­
    false_positive_rate: float = 0.0
    true_positive_rate: float = 0.0
    escalation_rate: float = 0.0

    # 컀버리지 λ©”νŠΈλ¦­
    mitre_coverage: float = 0.0  # ATT&CK 기법 νƒμ§€μœ¨

class SOCMetricsCollector:
    """SOC λ©”νŠΈλ¦­ μˆ˜μ§‘κΈ°"""

    def __init__(self, siem_client, ticketing_client):
        self.siem = siem_client
        self.ticketing = ticketing_client

    def collect_daily_metrics(self, date: datetime) -> SOCMetrics:
        period_start = date.replace(hour=0, minute=0, second=0)
        period_end = period_start + timedelta(days=1)

        # μ•Œλ¦Ό 데이터 쑰회
        alerts = self.siem.get_alerts(period_start, period_end)
        incidents = self.ticketing.get_incidents(period_start, period_end)

        metrics = SOCMetrics(
            period_start=period_start,
            period_end=period_end,
            total_alerts=len(alerts),
            alerts_by_severity=self._count_by_field(alerts, "severity"),
            alerts_by_source=self._count_by_field(alerts, "source")
        )

        # MTTD 계산: 곡격 λ°œμƒ β†’ 탐지 μ•Œλ¦Ό
        detection_times = [
            (a.detected_at - a.attack_started_at).total_seconds() / 60
            for a in alerts if a.attack_started_at
        ]
        if detection_times:
            metrics.mttd = statistics.mean(detection_times)

        # MTTR 계산: μ•Œλ¦Ό β†’ λŒ€μ‘ μ‹œμž‘
        response_times = [
            (i.response_started_at - i.created_at).total_seconds() / 60
            for i in incidents if i.response_started_at
        ]
        if response_times:
            metrics.mttr = statistics.mean(response_times)

        # MTTC 계산: μ•Œλ¦Ό β†’ μ’…λ£Œ
        close_times = [
            (i.closed_at - i.created_at).total_seconds() / 60
            for i in incidents if i.closed_at
        ]
        if close_times:
            metrics.mttc = statistics.mean(close_times)

        # False Positive Rate
        false_positives = sum(1 for a in alerts if a.status == "false_positive")
        metrics.false_positive_rate = false_positives / len(alerts) * 100 if alerts else 0

        # MITRE ATT&CK 컀버리지
        metrics.mitre_coverage = self._calculate_mitre_coverage()

        return metrics

    def _count_by_field(self, items: List, field: str) -> Dict[str, int]:
        counts = {}
        for item in items:
            value = getattr(item, field, "unknown")
            counts[value] = counts.get(value, 0) + 1
        return counts

    def _calculate_mitre_coverage(self) -> float:
        """탐지 κ·œμΉ™μ˜ MITRE ATT&CK 컀버리지 계산"""
        total_techniques = 201  # ATT&CK Enterprise 기법 수
        detection_rules = self.siem.get_detection_rules()
        covered_techniques = set()

        for rule in detection_rules:
            if rule.mitre_techniques:
                covered_techniques.update(rule.mitre_techniques)

        return len(covered_techniques) / total_techniques * 100

    def generate_report(self, metrics: SOCMetrics) -> str:
        """일간 SOC 리포트 생성"""
        return f"""
=== SOC Daily Report ===
Period: {metrics.period_start.date()}

πŸ“Š Alert Volume
- Total Alerts: {metrics.total_alerts}
- By Severity: {metrics.alerts_by_severity}

⏱️ Response Metrics
- MTTD (Mean Time To Detect): {metrics.mttd:.1f} minutes
- MTTR (Mean Time To Respond): {metrics.mttr:.1f} minutes
- MTTC (Mean Time To Close): {metrics.mttc:.1f} minutes

πŸ“ˆ Quality Metrics
- False Positive Rate: {metrics.false_positive_rate:.1f}%
- MITRE ATT&CK Coverage: {metrics.mitre_coverage:.1f}%

🎯 Goals
- MTTD Target: < 15 minutes {'βœ…' if metrics.mttd < 15 else '❌'}
- MTTR Target: < 60 minutes {'βœ…' if metrics.mttr < 60 else '❌'}
- FP Rate Target: < 30% {'βœ…' if metrics.false_positive_rate < 30 else '❌'}
"""

πŸ—£οΈ How It's Said in Practice

  • "Last night, a suspected ransomware alert fired in the SOC, but Tier 2 responded right away and isolated it before it spread."
  • "70% of SIEM alerts are False Positives, so the analysts are struggling. Let's add automatic filtering rules with a SOAR playbook."
  • "This month's MTTR is 90 minutes, but the target is 60 minutes. We should expand the scope of automated response."
  • "MITRE ATT&CK coverage is only 40%. We need to strengthen the detection rules for Credential Access."
  • "Explain the 3-Tier structure of a SOC, and what are the roles and required competencies of each Tier?"
  • "What are the differences between MTTD, MTTR, and MTTC, and what strategies can reduce each of them?"
  • "What is Alert Fatigue, and what methods can be used in a SOC to mitigate it?"
  • "Please explain the role of SOAR and its impact on SOC operations."

Take a mock interview on this topic β†’ WIA SOOM AI Interview Β· Start for free

  • "This detection rule is not mapped to MITRE ATT&CK. Please add the T1059 (Command and Scripting) tag."
  • "The playbook has no rollback procedure. Let's add a recovery action in case a host isolation was done by mistake."
  • "This SIEM query seems likely to generate many False Positives. It needs more specific filter conditions."

⚠️ Cautions

Alert Fatigue Management

Out of the thousands of alerts each day, only a portion are real threats. Excessive False Positives exhaust analysts and cause them to miss real threats. Regular detection rule tuning, risk-based prioritization, and SOAR automation are essential.

Preventing Staff Burnout

24/7 shift work, high-pressure environments, and skill stagnation increase SOC staff turnover. Appropriate shift schedules, ongoing training opportunities, reduced repetitive work through automation, and clear escalation paths are important.

Tool Integration and Visibility

If SIEM, EDR, firewalls, and cloud security tools are siloed, threats are missed. Unified visibility across the entire environment must be achieved through XDR (Extended Detection and Response) or an integrated data lake.

πŸ”— Related Terms

πŸ“š Learn More