🔒 Security

SIEM

Security Information and Event Management

A security information and event management system that centrally collects, normalizes, and correlates logs from the enterprise IT infrastructure to detect and respond to security threats. The global SIEM market is worth $14 billion in 2025, and AI/ML-based next-generation SIEM is growing 20% annually. A core platform of the SOC (Security Operations Center), it is the basis of real-time threat detection and compliance auditing.

📖 Detailed Explanation

SIEM (Security Information and Event Management) is a combination of two functions. SIM (Security Information Management) handles log collection, storage, search, and report generation, while SEM (Security Event Management) handles real-time event monitoring, correlation analysis, and alerting. For example, if an IP blocked by the firewall appears in the VPN logs as a successful login, SIEM correlates these two events and raises a "potential breach" alert. The core value of SIEM is detecting, through correlation, threats that would be missed by looking at a single log alone.

Traditional SIEM relied on rule-based detection. Static rules such as "alert if there are 5 or more failed logins within 5 minutes" are effective against known attack patterns, but have limitations against new attacks or stealthy activity within the normal range. In addition, as the number of rules grows, false positives surge and security analysts fall into alert fatigue. According to a 2025 IDC report, adoption of AI-based SIEM is growing 20% per year, which reflects a move to overcome these limitations with AI/ML.

Next-Gen SIEM places AI/ML at its core. UEBA (User and Entity Behavior Analytics) learns the normal behavior patterns of users and systems to detect anomalous behavior. For example, if an employee who normally only logs in during working hours downloads a large amount of data at 3 a.m., it is detected as an anomaly even without a rule. Machine learning detects stealth attacks that static rules miss, such as lateral movement, credential stuffing, and privilege escalation. AI automatically classifies alerts by severity, greatly reducing false positives, so analysts can focus on real threats.

Cloud-native SIEM and Agentic AI are the major trends of 2025. Cloud SIEM offers superior scalability, cost efficiency, and ease of management compared to on-premises, and organizations are transitioning quickly. Microsoft Sentinel, CrowdStrike Falcon, and Splunk Cloud are representative examples. Agentic AI goes a step further, autonomously performing search analysis, correlation rule creation, data transformation, and workflow automation. In the 2025 Gartner Magic Quadrant, Microsoft and CrowdStrike were selected as Leader/Visionary, and competition among AI SIEMs is intense.

💻 Code Example

# SIEM 스타일 로그 분석 및 위협 탐지 - Python
import json
from datetime import datetime, timedelta
from collections import defaultdict
from typing import List, Dict, Any
import hashlib

class SimpleSIEM:
    """간단한 SIEM 상관관계 분석 엔진"""

    def __init__(self):
        self.events = []
        self.alerts = []
        self.rules = []
        # 사용자별 행동 기록 (UEBA 시뮬레이션)
        self.user_baselines = defaultdict(lambda: {
            'login_hours': set(),
            'source_ips': set(),
            'accessed_resources': set(),
        })

    def ingest_log(self, log: Dict[str, Any]):
        """로그 수집 및 정규화"""
        normalized = {
            'timestamp': datetime.fromisoformat(log.get('timestamp', datetime.now().isoformat())),
            'source': log.get('source', 'unknown'),
            'event_type': log.get('event_type', 'unknown'),
            'user': log.get('user'),
            'source_ip': log.get('source_ip'),
            'destination_ip': log.get('destination_ip'),
            'action': log.get('action'),
            'status': log.get('status'),
            'raw': json.dumps(log),
        }

        self.events.append(normalized)
        self._update_baseline(normalized)
        self._evaluate_rules(normalized)

        return normalized

    def _update_baseline(self, event: Dict):
        """사용자 행동 베이스라인 업데이트 (UEBA)"""
        if not event.get('user'):
            return

        user = event['user']
        baseline = self.user_baselines[user]

        # 로그인 시간대 기록
        if event['event_type'] == 'authentication':
            hour = event['timestamp'].hour
            baseline['login_hours'].add(hour)

        # 소스 IP 기록
        if event.get('source_ip'):
            baseline['source_ips'].add(event['source_ip'])

    def add_correlation_rule(self, rule):
        """상관관계 규칙 추가"""
        self.rules.append(rule)

    def _evaluate_rules(self, event: Dict):
        """모든 규칙 평가"""
        for rule in self.rules:
            if alert := rule(event, self.events, self.user_baselines):
                self.alerts.append(alert)
                self._notify_alert(alert)

    def _notify_alert(self, alert: Dict):
        """알림 발송 (실제로는 Slack, PagerDuty 등 연동)"""
        severity_emoji = {'critical': '🔴', 'high': '🟠', 'medium': '🟡', 'low': '🟢'}
        print(f"\n{severity_emoji.get(alert['severity'], '⚪')} ALERT: {alert['title']}")
        print(f"   Severity: {alert['severity']}")
        print(f"   Description: {alert['description']}")
        print(f"   User: {alert.get('user', 'N/A')}")
        print(f"   Source IP: {alert.get('source_ip', 'N/A')}")


# 상관관계 규칙 정의

def brute_force_rule(event, events, baselines):
    """브루트포스 공격 탐지: 5분 내 동일 IP에서 로그인 실패 5회 이상"""
    if event['event_type'] != 'authentication' or event['status'] != 'failed':
        return None

    source_ip = event.get('source_ip')
    if not source_ip:
        return None

    # 최근 5분 내 같은 IP의 로그인 실패 횟수
    window = timedelta(minutes=5)
    cutoff = event['timestamp'] - window

    failures = [
        e for e in events
        if e['event_type'] == 'authentication'
        and e['status'] == 'failed'
        and e.get('source_ip') == source_ip
        and e['timestamp'] > cutoff
    ]

    if len(failures) >= 5:
        return {
            'title': 'Brute Force Attack Detected',
            'severity': 'high',
            'description': f'{len(failures)} failed login attempts from {source_ip} in 5 minutes',
            'source_ip': source_ip,
            'rule': 'brute_force',
            'timestamp': event['timestamp'],
        }
    return None


def impossible_travel_rule(event, events, baselines):
    """불가능한 이동 탐지: 지리적으로 불가능한 시간 내 로그인"""
    if event['event_type'] != 'authentication' or event['status'] != 'success':
        return None

    user = event.get('user')
    source_ip = event.get('source_ip')
    if not user or not source_ip:
        return None

    # 최근 1시간 내 같은 사용자의 성공한 로그인
    window = timedelta(hours=1)
    cutoff = event['timestamp'] - window

    recent_logins = [
        e for e in events
        if e['event_type'] == 'authentication'
        and e['status'] == 'success'
        and e.get('user') == user
        and e['timestamp'] > cutoff
        and e.get('source_ip') != source_ip
    ]

    # 실제로는 GeoIP로 거리 계산, 여기서는 다른 IP면 의심
    if recent_logins:
        return {
            'title': 'Impossible Travel Detected',
            'severity': 'critical',
            'description': f'User {user} logged in from multiple IPs within 1 hour',
            'user': user,
            'source_ip': source_ip,
            'previous_ips': [e['source_ip'] for e in recent_logins],
            'rule': 'impossible_travel',
            'timestamp': event['timestamp'],
        }
    return None


def anomalous_hour_rule(event, events, baselines):
    """비정상 시간대 접속 탐지 (UEBA)"""
    if event['event_type'] != 'authentication' or event['status'] != 'success':
        return None

    user = event.get('user')
    if not user:
        return None

    baseline = baselines[user]
    current_hour = event['timestamp'].hour

    # 사용자의 정상 로그인 시간대가 10개 이상 기록되어 있고
    # 현재 시간이 정상 범위를 벗어나면 알림
    if len(baseline['login_hours']) >= 10 and current_hour not in baseline['login_hours']:
        return {
            'title': 'Anomalous Login Time Detected',
            'severity': 'medium',
            'description': f'User {user} logged in at unusual hour ({current_hour}:00)',
            'user': user,
            'normal_hours': sorted(baseline['login_hours']),
            'rule': 'anomalous_hour',
            'timestamp': event['timestamp'],
        }
    return None


# 사용 예시
if __name__ == '__main__':
    siem = SimpleSIEM()

    # 상관관계 규칙 등록
    siem.add_correlation_rule(brute_force_rule)
    siem.add_correlation_rule(impossible_travel_rule)
    siem.add_correlation_rule(anomalous_hour_rule)

    # 브루트포스 공격 시뮬레이션
    print("=== Simulating Brute Force Attack ===")
    for i in range(6):
        siem.ingest_log({
            'timestamp': (datetime.now() + timedelta(seconds=i*30)).isoformat(),
            'source': 'auth-server',
            'event_type': 'authentication',
            'user': f'user_{i % 3}',
            'source_ip': '192.168.1.100',
            'status': 'failed',
        })

    # 불가능한 이동 시뮬레이션
    print("\n=== Simulating Impossible Travel ===")
    siem.ingest_log({
        'timestamp': datetime.now().isoformat(),
        'source': 'auth-server',
        'event_type': 'authentication',
        'user': 'admin',
        'source_ip': '1.1.1.1',  # 한국
        'status': 'success',
    })
    siem.ingest_log({
        'timestamp': (datetime.now() + timedelta(minutes=30)).isoformat(),
        'source': 'auth-server',
        'event_type': 'authentication',
        'user': 'admin',
        'source_ip': '8.8.8.8',  # 미국 (30분 만에 이동 불가)
        'status': 'success',
    })

    print(f"\n=== Summary ===")
    print(f"Total events: {len(siem.events)}")
    print(f"Total alerts: {len(siem.alerts)}")
-- Splunk SPL (Search Processing Language) 쿼리 예제

-- 1. 브루트포스 공격 탐지
-- 5분 내 동일 소스에서 로그인 실패 5회 이상
index=auth sourcetype=linux_secure action=failure
| bin _time span=5m
| stats count as failure_count,
        values(user) as targeted_users,
        dc(user) as unique_users
    by src_ip, _time
| where failure_count >= 5
| sort -failure_count
| table _time, src_ip, failure_count, unique_users, targeted_users

-- 2. 비정상 로그인 시간 탐지 (UEBA 스타일)
index=auth action=success
| eval hour=strftime(_time,"%H")
| eval is_business_hours=if(hour>=9 AND hour<=18, "yes", "no")
| where is_business_hours="no"
| stats count as off_hours_logins,
        values(src_ip) as source_ips,
        earliest(_time) as first_login,
        latest(_time) as last_login
    by user
| where off_hours_logins >= 3
| sort -off_hours_logins

-- 3. 권한 상승 탐지
-- 일반 사용자가 관리자 명령 실행
index=linux sourcetype=linux_audit
| search (command="sudo *" OR command="su *" OR command="chmod 777 *")
| stats count as privilege_commands,
        values(command) as commands
    by user, host
| lookup user_roles user OUTPUT role
| where role!="admin"
| sort -privilege_commands

-- 4. 데이터 유출 의심 탐지
-- 대량 파일 다운로드 또는 외부 전송
index=network sourcetype=firewall action=allowed
| where dest_port IN (20, 21, 22, 443, 8080)
| stats sum(bytes_out) as total_bytes,
        dc(dest_ip) as unique_destinations,
        values(dest_ip) as destinations
    by src_ip, user
| eval total_mb = round(total_bytes/1024/1024, 2)
| where total_mb > 100  -- 100MB 이상
| sort -total_mb
| table user, src_ip, total_mb, unique_destinations, destinations

-- 5. 상관관계 분석: 방화벽 차단 후 VPN 성공
-- 동일 IP가 방화벽에서 차단됐는데 VPN으로 들어왔으면 의심
index=firewall action=blocked
| rename src_ip as attacker_ip
| join attacker_ip type=inner
    [search index=vpn action=success
    | rename src_ip as attacker_ip]
| table _time, attacker_ip, user, firewall_reason, vpn_connection_time

-- 6. 실시간 대시보드용 통계
-- 시간별 보안 이벤트 트렌드
index=security
| timechart span=1h count by severity
| addtotals fieldname=total

-- 7. MITRE ATT&CK 매핑
-- 탐지된 공격을 ATT&CK 프레임워크에 매핑
index=alerts
| lookup mitre_attack_mapping technique_id OUTPUT tactic, technique_name
| stats count by tactic, technique_name
| sort -count
# Elastic SIEM Detection Rule 예제
# .detection-rules/brute_force.toml

[rule]
author = ["Security Team"]
description = "Detects potential brute force attacks with multiple failed login attempts"
enabled = true
false_positives = ["Users with forgotten passwords", "Automated testing"]
from = "now-5m"
index = ["logs-*", "winlogbeat-*", "filebeat-*"]
interval = "5m"
language = "kuery"
license = "Elastic License v2"
name = "Brute Force Attack Detected"
risk_score = 73
rule_id = "bf-001"
severity = "high"
tags = ["Brute Force", "Credential Access", "T1110"]
type = "threshold"

[rule.threat]
framework = "MITRE ATT&CK"

[[rule.threat.technique]]
id = "T1110"
name = "Brute Force"
reference = "https://attack.mitre.org/techniques/T1110/"

[rule.threat.tactic]
id = "TA0006"
name = "Credential Access"
reference = "https://attack.mitre.org/tactics/TA0006/"

[rule.threshold]
field = ["source.ip"]
value = 5

[rule.query]
'''
event.category:authentication AND event.outcome:failure
'''

---
# Elastic SIEM API를 통한 알림 조회 및 대응 - Python
from elasticsearch import Elasticsearch
from datetime import datetime, timedelta
import json

class ElasticSIEM:
    def __init__(self, host='localhost:9200', api_key=None):
        self.es = Elasticsearch(
            hosts=[host],
            api_key=api_key
        )

    def search_security_events(self, query, time_range='24h'):
        """보안 이벤트 검색"""
        body = {
            "query": {
                "bool": {
                    "must": [
                        {"query_string": {"query": query}},
                        {"range": {
                            "@timestamp": {
                                "gte": f"now-{time_range}",
                                "lte": "now"
                            }
                        }}
                    ]
                }
            },
            "sort": [{"@timestamp": "desc"}],
            "size": 100
        }

        response = self.es.search(
            index=".alerts-security.alerts-*",
            body=body
        )

        return response['hits']['hits']

    def get_open_alerts(self, severity=None):
        """열린 알림 조회"""
        query = {
            "bool": {
                "must": [
                    {"term": {"kibana.alert.workflow_status": "open"}}
                ]
            }
        }

        if severity:
            query["bool"]["must"].append(
                {"term": {"kibana.alert.severity": severity}}
            )

        response = self.es.search(
            index=".alerts-security.alerts-*",
            query=query,
            sort=[{"@timestamp": "desc"}],
            size=50
        )

        return response['hits']['hits']

    def acknowledge_alert(self, alert_id):
        """알림 확인 처리"""
        self.es.update(
            index=".alerts-security.alerts-*",
            id=alert_id,
            body={
                "doc": {
                    "kibana.alert.workflow_status": "acknowledged",
                    "kibana.alert.workflow_user": "analyst@company.com"
                }
            }
        )

    def create_detection_rule(self, rule_config):
        """탐지 규칙 생성 (Kibana Detection Engine API)"""
        # 실제로는 Kibana API 사용
        # POST /api/detection_engine/rules
        pass

    def get_alert_timeline(self, alert_id):
        """알림 관련 이벤트 타임라인 조회"""
        alert = self.es.get(index=".alerts-security.alerts-*", id=alert_id)
        source_ip = alert['_source'].get('source', {}).get('ip')

        if not source_ip:
            return []

        # 해당 IP의 최근 활동 조회
        events = self.es.search(
            index="logs-*",
            query={
                "bool": {
                    "must": [
                        {"term": {"source.ip": source_ip}},
                        {"range": {"@timestamp": {"gte": "now-1h"}}}
                    ]
                }
            },
            sort=[{"@timestamp": "asc"}],
            size=200
        )

        return events['hits']['hits']

# 사용 예시
if __name__ == '__main__':
    siem = ElasticSIEM(api_key='your-api-key')

    # 열린 고위험 알림 조회
    alerts = siem.get_open_alerts(severity='high')
    for alert in alerts:
        print(f"Alert: {alert['_source']['kibana.alert.rule.name']}")
        print(f"  Severity: {alert['_source']['kibana.alert.severity']}")
        print(f"  Source IP: {alert['_source'].get('source', {}).get('ip')}")

🗣️ Say It Like This in Practice

💬 In a SOC Operations Meeting
"The alert fatigue problem is serious. Of 10,000 alerts a day, fewer than 10 are real threats. We need to switch to AI-based SIEM, use UEBA for behavior-based detection, and automatically filter false positives with ML. Next-gen SIEMs like CrowdStrike or Microsoft Sentinel automatically classify severity so analysts can focus on real threats."
💬 In a Security Architecture Review
"Let's migrate from on-premises SIEM to cloud-native. We currently have 500GB of logs a day, but it goes up to 2TB at peak. On-prem takes several weeks to expand capacity, while the cloud auto-scales. Sentinel or Splunk Cloud natively ingests AWS, Azure, and GCP logs, and even automates response through SOAR integration."
💬 In a Compliance Audit Response
"We've applied a 90-day log retention policy in the SIEM, and audit trail reports are generated automatically. Privileged account activity, data access logs, and policy change history can all be searched centrally. We can also analyze detection coverage through MITRE ATT&CK framework mapping, and view the status by PCI-DSS and ISMS requirement in real time on the compliance dashboard."

⚠️ Cautions & Best Practices

❌
Indiscriminate Collection of All Logs

Because of cost and noise, you should not collect all logs. Collect high-security-value logs (authentication, privileges, network flows) first, and exclude debug-level logs. A surge in log volume leads to a cost explosion and degraded search performance.

❌
Detection Relying Only on Rules

Static rules detect only known attacks. Zero-days, insider threats, and APTs bypass rules. Use UEBA and ML-based anomaly detection together. Use rules for clearly malicious behavior and ML for unknown threats.

❌
Alerts Only, No Response

Even if SIEM raises alerts, they are useless without a response process. Integrate with SOAR (Security Orchestration, Automation and Response) to automate ticket creation, isolation, and blocking. Document playbooks and train on them regularly.

✅
SIEM Best Practices

Implement log source prioritization, normalization and enrichment pipelines, use-case-based detection rule development, coverage analysis through MITRE ATT&CK mapping, rule tuning through a false-positive feedback loop, automated response through SOAR integration, and verification of detection effectiveness through regular red team/purple team exercises.

🔗 Related Terms

📚 Learn More