로그인

관제 모니터링 index.html 스크립트

작성: 2026.08.27 07:03 최근 수정: 2026.08.29 05:16
<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>전주컴의 Advanced SOC & SIEM Core</title>

    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

    <style>
        :root {
            --bg-main: #f8fafc;
            --panel-bg: #ffffff;
            --border: #e2e8f0;

            --green: #059669;
            --green-bright: #10b981;

            --red: #dc2626;
            --yellow: #d97706;
            --blue: #2563eb;

            --text-main: #0f172a;
            --text-muted: #64748b;

            --font-mono:
                'Pretendard',
                -apple-system,
                BlinkMacSystemFont,
                'Segoe UI',
                Roboto,
                sans-serif;
        }

        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
            font-family: var(--font-mono);
        }

        body {
            background-color: var(--bg-main);
            color: var(--text-main);
            padding: 16px;
            display: flex;
            flex-direction: column;
            gap: 14px;
            min-height: 100vh;
        }

        header {
            display: flex;
            justify-content: space-between;
            align-items: center;

            background: var(--panel-bg);
            border: 1px solid var(--border);

            padding: 14px 20px;
            border-radius: 8px;
        }

        .title-group h1 {
            font-size: 1.25rem;
            color: var(--blue);

            display: flex;
            align-items: center;
            gap: 10px;

            font-weight: 800;
            letter-spacing: -0.3px;
        }

        .subtitle {
            font-size: 0.8rem;
            color: var(--text-muted);
            margin-top: 4px;
            font-weight: 500;
        }

        .header-controls {
            display: flex;
            gap: 10px;
            align-items: center;
        }

        .badge {
            font-size: 0.8rem;
            padding: 6px 12px;

            border-radius: 6px;
            border: 1px solid var(--border);

            background: #f8fafc;
            color: var(--text-main);

            font-weight: bold;
        }

        .badge-green {
            border-color: var(--green-bright);
            color: var(--green);
            background: #dcfce7;
        }

        .badge-red {
            border-color: #fca5a5;
            color: var(--red);
            background: #fee2e2;

            animation: pulse 1.5s infinite;
        }

        @keyframes pulse {
            0% {
                opacity: 1;
            }

            50% {
                opacity: 0.5;
            }

            100% {
                opacity: 1;
            }
        }

        .top-dash-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 14px;
        }

        .incident-grid {
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            gap: 14px;
        }

        .incident-card {
            background: #ffffff;
            border: 1px solid var(--border);
            border-left: 5px solid var(--green-bright);

            border-radius: 8px;

            padding: 12px 14px;
            min-height: 94px;
        }

        .incident-card.high {
            border-left-color: var(--yellow);
            background: #fffbeb;
        }

        .incident-card.critical {
            border-left-color: var(--red);
            background: #fef2f2;
        }

        .incident-card .ioc {
            color: var(--blue);
            font-size: 0.82rem;
            font-weight: 800;
            margin-bottom: 5px;
        }

        .incident-card .state {
            color: var(--text-main);
            font-size: 0.82rem;
            font-weight: 700;
            line-height: 1.45;
        }

        .incident-card .state small {
            color: var(--text-muted);
            font-weight: 500;
        }

        .panel {
            background: var(--panel-bg);
            border: 1px solid var(--border);

            border-radius: 8px;

            padding: 14px 16px;

            display: flex;
            flex-direction: column;
            gap: 10px;

            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.02);
        }

        .panel-header {
            font-size: 0.9rem;
            font-weight: 700;

            color: var(--text-main);

            border-bottom: 2px solid #f1f5f9;

            padding-bottom: 8px;
            margin-bottom: 2px;

            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .info-box {
            font-size: 0.8rem;

            display: flex;
            flex-direction: column;

            gap: 6px;

            color: var(--text-muted);
        }

        .info-row {
            display: flex;
            justify-content: space-between;

            background: #f8fafc;

            padding: 6px 10px;

            border-radius: 6px;
            border: 1px solid #f1f5f9;
        }

        .info-row span:last-child {
            color: var(--text-main);
            font-weight: 700;
        }

        .input-group {
            display: flex;
            flex-direction: column;
            gap: 6px;

            font-size: 0.8rem;
        }

        input,
        button,
        select {
            font-family: var(--font-mono);

            background: #ffffff;

            border: 1px solid var(--border);

            color: var(--text-main);

            padding: 6px 10px;

            border-radius: 6px;

            font-size: 0.8rem;

            outline: none;
        }

        button {
            background: #f8fafc;

            color: var(--blue);

            border-color: var(--blue);

            cursor: pointer;

            transition: 0.2s;

            font-weight: 700;
        }

        button:hover {
            background: var(--blue);
            color: #ffffff;
        }

        .charts-row {
            display: grid;
            grid-template-columns: 1.2fr 1fr 1.2fr;
            gap: 14px;
        }

        .chart-box {
            height: 230px;
            position: relative;
            width: 100%;
        }

        .ranking-list {
            height: 230px;

            overflow-y: auto;

            display: flex;
            flex-direction: column;

            gap: 8px;
        }

        .ranking-item {
            display: flex;
            justify-content: space-between;
            align-items: center;

            background: #f8fafc;

            padding: 8px 12px;

            border-radius: 6px;

            border: 1px solid #f1f5f9;

            font-size: 0.8rem;
        }

        .rank-badge {
            font-weight: bold;

            width: 24px;
            height: 24px;

            display: inline-flex;

            align-items: center;
            justify-content: center;

            background: #e2e8f0;

            border-radius: 50%;

            font-size: 0.75rem;
        }

        .rank-1 {
            background: #fef08a;
            color: #854d0e;
        }

        .rank-2 {
            background: #e2e8f0;
            color: #334155;
        }

        .rank-3 {
            background: #fed7aa;
            color: #9a3412;
        }

        .log-table-wrapper {
            background: #ffffff;

            border: 1px solid var(--border);

            border-radius: 6px;

            overflow: hidden;

            max-height: 400px;

            overflow-y: auto;
        }

        table {
            width: 100%;

            border-collapse: collapse;

            font-size: 0.8rem;

            text-align: left;
        }

        th {
            background: #f8fafc;

            color: var(--text-muted);

            font-weight: 700;

            padding: 10px 12px;

            border-bottom: 2px solid var(--border);

            position: sticky;

            top: 0;

            z-index: 2;
        }

        td {
            padding: 8px 12px;

            border-bottom: 1px solid var(--border);

            color: var(--text-main);

            cursor: pointer;

            font-weight: 500;
        }

        tr:hover {
            background: #f8fafc !important;
        }

        /* =====================================================
           프로토콜 체크 필터
           ===================================================== */

        .protocol-filter {
            display: flex;
            flex-wrap: wrap;

            align-items: center;

            gap: 8px;

            padding: 10px 12px;

            background: #f1f5f9;

            border: 1px solid #e2e8f0;

            border-radius: 6px;

            font-size: 0.8rem;
        }

        .protocol-filter-title {
            font-weight: 800;

            color: var(--text-main);

            margin-right: 3px;
        }

        .protocol-check {
            display: inline-flex;

            align-items: center;

            gap: 5px;

            padding: 4px 7px;

            border-radius: 4px;

            background: #e2e8f0;

            color: #334155;

            font-weight: 700;

            cursor: pointer;

            user-select: none;

            transition: 0.15s;
        }

        .protocol-check:hover {
            background: #cbd5e1;
        }

        .protocol-check input {
            width: 14px;
            height: 14px;

            margin: 0;

            padding: 0;

            accent-color: var(--blue);

            cursor: pointer;
        }

        .protocol-check.active {
            background: #dbeafe;

            color: #1d4ed8;

            border: 1px solid #93c5fd;
        }

        .protocol-count {
            margin-left: auto;

            color: var(--blue);

            font-weight: 800;

            white-space: nowrap;
        }

        .modal {
            display: none;

            position: fixed;

            z-index: 10;

            left: 0;
            top: 0;

            width: 100%;
            height: 100%;

            background-color: rgba(0, 0, 0, 0.5);

            align-items: center;
            justify-content: center;
        }

        .modal-content {
            background: #0f172a;

            padding: 24px;

            border-radius: 10px;

            width: 850px;

            max-width: 95vw;

            border: 1px solid #334155;

            box-shadow: 0 15px 30px rgba(0, 0, 0, 0.5);

            color: #f8fafc;
        }

        .modal-header {
            font-weight: 800;

            font-size: 1.1rem;

            margin-bottom: 16px;

            display: flex;

            justify-content: space-between;

            align-items: center;

            border-bottom: 1px solid #334155;

            padding-bottom: 12px;

            color: #f8fafc;
        }

        .modal-header button {
            background: #334155;

            color: #f8fafc;

            border: none;

            padding: 6px 12px;

            border-radius: 6px;

            cursor: pointer;
        }

        .modal-header button:hover {
            background: #475569;
        }

        .packet-tree {
            max-height: 550px;

            overflow-y: auto;
        }

        .packet-tree::-webkit-scrollbar {
            width: 8px;
        }

        .packet-tree::-webkit-scrollbar-track {
            background: #1e293b;

            border-radius: 4px;
        }

        .packet-tree::-webkit-scrollbar-thumb {
            background: #475569;

            border-radius: 4px;
        }

        .packet-tree::-webkit-scrollbar-thumb:hover {
            background: #64748b;
        }

        @media (max-width: 980px) {
            .top-dash-grid,
            .charts-row {
                grid-template-columns: 1fr;
            }

            .incident-grid {
                grid-template-columns: repeat(2, 1fr);
            }

            .protocol-count {
                margin-left: 0;
                width: 100%;
            }
        }

        @media (max-width: 560px) {
            .incident-grid {
                grid-template-columns: 1fr;
            }

            header {
                flex-direction: column;
                align-items: flex-start;

                gap: 10px;
            }

            .header-controls {
                width: 100%;
            }
        }
    </style>
</head>

<body>

<header>
    <div class="title-group">
        <h1>전주컴의 Advanced SOC & SIEM Core</h1>

        <div class="subtitle">
            운영 조직: 통합분석팀 (Security Operations Center)
            | 실시간 고급 파싱(Enrichment) 엔진 구동 중
        </div>
    </div>

    <div class="header-controls">

        <div id="sync-badge" class="badge badge-green">
            시스템 정상 운영중
        </div>

        <div class="badge" id="clock">
            --:--:--
        </div>

    </div>
</header>


<!-- =====================================================
     상단 대시보드
     ===================================================== -->

<div class="top-dash-grid">

    <div class="panel">

        <div class="panel-header">
            <span>[CORE] 통합 분석 프로파일</span>
        </div>

        <div class="info-box">

            <div class="info-row">
                <span>총괄 분석가</span>
                <span>전주컴 (Lead Analyst)</span>
            </div>

            <div class="info-row">
                <span>고급 탐지 모듈</span>
                <span>GeoIP 3D · 구체적 공격 기법(ATT&CK) 분석</span>
            </div>

            <div class="info-row">
                <span>인프라 환경</span>
                <span>VirtualBox & ELK 클러스터</span>
            </div>

            <div class="info-row">
                <span>통합 시스템 상태</span>

                <span
                    id="sys-status-text"
                    style="color: var(--green);"
                >
                    정상 모니터링 중
                </span>
            </div>

        </div>

    </div>


    <div class="panel">

        <div class="panel-header">

            <span>
                ELK & 패킷 관제 제어센터
            </span>

            <span
                style="font-size: 0.7rem; color: var(--blue);"
                id="quick-metrics"
            >
                활성 IP: - | 프로토콜: -
            </span>

        </div>


        <div class="input-group">

            <div style="display: flex; gap: 6px;">

                <input
                    type="date"
                    id="search-date"
                    style="flex: 0.8;"
                    onchange="fetchRealData()"
                >


                <select
                    id="search-hour"
                    style="flex: 0.5;"
                    onchange="fetchRealData()"
                >
                    <option value="">
                        전체 시간
                    </option>

                    <script>
                        for (let i = 0; i < 24; i++) {

                            const h =
                                i.toString().padStart(2, '0');

                            document.write(
                                `<option value="${h}">${h}시</option>`
                            );
                        }
                    </script>
                </select>


                <input
                    type="text"
                    id="elk-host"
                    value="http://192.168.0.232:9200"
                    style="flex: 1.5;"
                    placeholder="Elasticsearch 주소"
                >


                <select
                    id="elk-index"
                    style="flex: 1.5;"
                    onchange="fetchRealData()"
                >

                    <option value="*.*">
                        전체 통합 데이터 (All Logs)
                    </option>

                    <option value=".ds-server-packets-*">
                        📦 실시간 서버 패킷 관제
                    </option>

                    <option value=".ds-packetbeat-*">
                        📡 패킷비트 네트워크 트래픽
                    </option>

                </select>

            </div>


            <div style="display: flex; gap: 6px;">

                <select
                    id="sync-interval"
                    style="flex: 1;"
                    onchange="changeSyncInterval()"
                >

                    <option value="3000">
                        갱신 주기: 3초
                    </option>

                    <option value="5000" selected>
                        갱신 주기: 5초
                    </option>

                    <option value="10000">
                        갱신 주기: 10초
                    </option>

                    <option value="0">
                        자동 갱신 정지
                    </option>

                </select>


                <button
                    style="flex: 1;"
                    id="manual-btn"
                    onclick="fetchRealData()"
                >
                    실시간 포렌식 갱신
                </button>


                <button
                    style="
                        flex: 1;
                        border-color: var(--yellow);
                        color: var(--yellow);
                    "
                    onclick="exportSecurityReport()"
                >
                    📥 PDF 리포트
                </button>

            </div>

        </div>

    </div>

</div>


<!-- =====================================================
     IOC 카드
     ===================================================== -->

<div
    class="incident-grid"
    id="incidentCards"
    aria-live="polite"
>

    <div class="incident-card">

        <div class="ioc">
            C2 / 정보 유출 IOC
        </div>

        <div class="state">
            탐지 데이터 확인 중
            <br>
            <small>192.168.0.86:443</small>
        </div>

    </div>


    <div class="incident-card">

        <div class="ioc">
            악성 파일 유포 IOC
        </div>

        <div class="state">
            탐지 데이터 확인 중
            <br>
            <small>192.168.0.49 · V2.exe</small>
        </div>

    </div>


    <div class="incident-card">

        <div class="ioc">
            SSH 내부 이동 조사
        </div>

        <div class="state">
            탐지 데이터 확인 중
            <br>
            <small>
                192.168.1.1 → 172.16.0.145:22
            </small>
        </div>

    </div>


    <div class="incident-card">

        <div class="ioc">
            피싱 메일 IOC
        </div>

        <div class="state">
            탐지 데이터 확인 중
            <br>
            <small>psc@jjcom.kr</small>
        </div>

    </div>

</div>


<!-- =====================================================
     차트
     ===================================================== -->

<div class="charts-row">

    <div class="panel">

        <div class="panel-header">

            <span>
                시간대별 트래픽 추이
                (Traffic Frequency)
            </span>

            <span
                style="
                    font-size: 0.75rem;
                    font-weight: normal;
                    color: var(--text-muted);
                "
            >
                * 실시간 추이 분석
            </span>

        </div>

        <div class="chart-box">
            <canvas id="freqChart"></canvas>
        </div>

    </div>


    <div class="panel">

        <div class="panel-header">
            <span>
                국가별 트래픽 분포
                (GeoIP 3D Chart)
            </span>
        </div>

        <div class="chart-box">
            <canvas id="geoChart"></canvas>
        </div>

    </div>


    <div class="panel">

        <div class="panel-header">
            <span>
                상위 대역폭 점유 IP 랭킹
                (Top Talkers)
            </span>
        </div>

        <div
            class="ranking-list"
            id="bandwidthRankingList"
        >
            <div
                style="
                    color: var(--text-muted);
                    text-align: center;
                    margin-top: 60px;
                    font-size: 0.8rem;
                "
            >
                데이터 로딩 중...
            </div>
        </div>

    </div>

</div>


<!-- =====================================================
     실시간 데이터 스트림
     ===================================================== -->

<div class="panel">

    <div class="panel-header">

        <span>
            실시간 데이터 스트림
            (행을 클릭하면 자동 포렌식 브리핑 창이 뜹니다)
        </span>

        <div
            style="
                display: flex;
                gap: 8px;
                align-items: center;
            "
        >

            <input
                type="text"
                id="sig-search"
                placeholder="🔍 IP 또는 키워드 검색..."
                onkeyup="handleSearchKeyup(event)"
                style="
                    width: 180px;
                    padding: 4px 8px;
                    font-size: 0.75rem;
                "
            >


            <select
                id="sev-filter"
                onchange="filterLogs()"
            >

                <option value="ALL">
                    전체 등급 보기
                </option>

                <option value="CRITICAL">
                    긴급 등급 (CRITICAL)
                </option>

                <option value="HIGH">
                    위험 등급 (HIGH)
                </option>

                <option value="MEDIUM">
                    경고 등급 (MEDIUM)
                </option>

                <option value="LOW">
                    일반 등급 (LOW)
                </option>

            </select>


            <span
                style="
                    color: var(--blue);
                    font-size: 0.85rem;
                    font-weight: bold;
                "
                id="log-counter"
            >
                0 건
            </span>

        </div>

    </div>


    <!-- =================================================
         ★ 프로토콜 체크 필터
         ================================================= -->

    <div class="protocol-filter">

        <span class="protocol-filter-title">
            🔔 프로토콜 체크 필터 :
        </span>


        <label class="protocol-check active">
            <input
                type="checkbox"
                id="proto-all"
                checked
                onchange="toggleAllProtocols(this)"
            >
            <span>전체 보기</span>
        </label>


        <label class="protocol-check active">
            <input
                type="checkbox"
                class="protocol-checkbox"
                value="UDP"
                checked
                onchange="handleProtocolChange(this)"
            >
            <span>UDP</span>
        </label>


        <label class="protocol-check active">
            <input
                type="checkbox"
                class="protocol-checkbox"
                value="DHCPV4"
                checked
                onchange="handleProtocolChange(this)"
            >
            <span>DHCPV4</span>
        </label>


        <label class="protocol-check active">
            <input
                type="checkbox"
                class="protocol-checkbox"
                value="HTTP"
                checked
                onchange="handleProtocolChange(this)"
            >
            <span>HTTP</span>
        </label>


        <label class="protocol-check active">
            <input
                type="checkbox"
                class="protocol-checkbox"
                value="SSH"
                checked
                onchange="handleProtocolChange(this)"
            >
            <span>SSH</span>
        </label>


        <label class="protocol-check active">
            <input
                type="checkbox"
                class="protocol-checkbox"
                value="IMAP"
                checked
                onchange="handleProtocolChange(this)"
            >
            <span>IMAP</span>
        </label>


        <label class="protocol-check active">
            <input
                type="checkbox"
                class="protocol-checkbox"
                value="LOG"
                checked
                onchange="handleProtocolChange(this)"
            >
            <span>LOG</span>
        </label>


        <label class="protocol-check active">
            <input
                type="checkbox"
                class="protocol-checkbox"
                value="ICMP"
                checked
                onchange="handleProtocolChange(this)"
            >
            <span>ICMP</span>
        </label>


        <label class="protocol-check active">
            <input
                type="checkbox"
                class="protocol-checkbox"
                value="TLS"
                checked
                onchange="handleProtocolChange(this)"
            >
            <span>TLS</span>
        </label>


        <label class="protocol-check active">
            <input
                type="checkbox"
                class="protocol-checkbox"
                value="HTTPS"
                checked
                onchange="handleProtocolChange(this)"
            >
            <span>HTTPS</span>
        </label>


        <label class="protocol-check active">
            <input
                type="checkbox"
                class="protocol-checkbox"
                value="FTP"
                checked
                onchange="handleProtocolChange(this)"
            >
            <span>FTP</span>
        </label>


        <span
            class="protocol-count"
            id="protocol-filter-count"
        >
            10개 프로토콜 표시
        </span>

    </div>


    <!-- =================================================
         데이터 테이블
         ================================================= -->

    <div class="log-table-wrapper">

        <table>

            <thead>

                <tr>

                    <th>번호</th>

                    <th>
                        탐지 시각
                    </th>

                    <th>
                        출발지
                        (소스 IP:Port)
                    </th>

                    <th>
                        목적지
                        (서버 IP:Port)
                    </th>

                    <th>
                        프로토콜 / 서비스
                    </th>

                    <th>
                        출발 국가
                        (GeoIP)
                    </th>

                    <th>
                        보안 이벤트 메시지
                    </th>

                    <th>
                        위협 인텔리전스 / 조치
                    </th>

                </tr>

            </thead>


            <tbody id="log-body"></tbody>

        </table>

    </div>

</div>


<!-- =====================================================
     포렌식 모달
     ===================================================== -->

<div
    id="packetModal"
    class="modal"
>

    <div class="modal-content">

        <div class="modal-header">

            <span id="modalTitle">
                📦 Wireshark Forensic Deep Inspection
            </span>

            <button onclick="closeModal()">
                닫기 ✕
            </button>

        </div>


        <div
            class="packet-tree"
            id="modalBody"
        ></div>

    </div>

</div>


<script>

/* =========================================================
   시계
   ========================================================= */

function updateClock() {

    const clock =
        document.getElementById('clock');

    if (!clock) {
        return;
    }

    clock.innerText =
        new Date().toLocaleTimeString('ko-KR');
}

setInterval(updateClock, 1000);

updateClock();


/* =========================================================
   페이지 로딩
   ========================================================= */

window.onload = function () {

    const now = new Date();

    const todayStr =
        new Date(
            now.getTime() -
            now.getTimezoneOffset() * 60000
        )
        .toISOString()
        .split('T')[0];

    const dateElement =
        document.getElementById('search-date');

    if (dateElement) {
        dateElement.value = todayStr;
    }

};


/* =========================================================
   전역 데이터
   ========================================================= */

let allLogsData = [];

let syncInterval = null;

let isFetching = false;

let searchTimer = null;


/* =========================================================
   프로토콜 목록
   ========================================================= */

const PROTOCOL_NAMES = [
    'UDP',
    'DHCPV4',
    'HTTP',
    'SSH',
    'IMAP',
    'LOG',
    'ICMP',
    'TLS',
    'HTTPS',
    'FTP'
];


/* =========================================================
   PDF 리포트
   ========================================================= */

function exportSecurityReport() {

    const hostElement =
        document.getElementById('elk-host');

    const indexElement =
        document.getElementById('elk-index');

    const host =
        hostElement
            ? hostElement.value.trim()
            : '';

    const index =
        indexElement
            ? indexElement.value.trim()
            : '';

    alert(
        "📥 [보고서 생성 중] 최신 포렌식 리포트를 생성합니다!"
    );

    window.location.href =
        `/api/export-pdf?host=${encodeURIComponent(host)}&index=${encodeURIComponent(index)}`;
}


/* =========================================================
   Chart.js - 시간대별 트래픽
   ========================================================= */

const freqCtx =
    document
        .getElementById('freqChart')
        .getContext('2d');


let gradientBlue =
    freqCtx.createLinearGradient(
        0,
        0,
        0,
        180
    );

gradientBlue.addColorStop(
    0,
    'rgba(37, 99, 235, 0.4)'
);

gradientBlue.addColorStop(
    1,
    'rgba(37, 99, 235, 0.0)'
);


const freqChart =
    new Chart(
        freqCtx,
        {
            type: 'line',

            data: {

                labels: [],

                datasets: [

                    {
                        data: [],

                        borderColor:
                            '#2563eb',

                        backgroundColor:
                            gradientBlue,

                        fill: true,

                        tension: 0.4,

                        borderWidth: 2.5,

                        pointBackgroundColor:
                            '#ffffff',

                        pointRadius: 2
                    }

                ]
            },

            options: {

                responsive: true,

                maintainAspectRatio: false,

                plugins: {

                    legend: {
                        display: false
                    }

                },

                scales: {

                    x: {

                        grid: {
                            display: false
                        },

                        ticks: {

                            font: {
                                size: 10,
                                weight: '700'
                            },

                            color: '#475569',

                            maxRotation: 0,

                            minRotation: 0,

                            autoSkip: true,

                            maxTicksLimit: 8
                        }
                    },

                    y: {

                        beginAtZero: true,

                        border: {
                            display: false
                        },

                        grid: {

                            color: '#f1f5f9',

                            drawBorder: false
                        },

                        ticks: {

                            color: '#64748b',

                            font: {
                                size: 11,
                                weight: '600'
                            }
                        }
                    }

                }
            }
        }
    );


/* =========================================================
   Chart.js - 국가별 트래픽
   ========================================================= */

const geoCtx =
    document
        .getElementById('geoChart')
        .getContext('2d');


const shadowPlugin = {

    id: 'shadowPlugin',

    beforeDraw(chart) {

        const ctx = chart.ctx;

        ctx.save();

        ctx.shadowColor =
            'rgba(0, 0, 0, 0.15)';

        ctx.shadowBlur = 10;

        ctx.shadowOffsetX = 0;

        ctx.shadowOffsetY = 4;
    },

    afterDraw(chart) {

        chart.ctx.restore();
    }
};


const geoChart =
    new Chart(
        geoCtx,
        {

            type: 'doughnut',

            data: {

                labels: [],

                datasets: [

                    {

                        data: [],

                        backgroundColor: [

                            '#2563eb',
                            '#10b981',
                            '#f59e0b',
                            '#dc2626',
                            '#8b5cf6',
                            '#64748b'
                        ],

                        borderWidth: 2,

                        borderColor: '#ffffff',

                        hoverOffset: 6

                    }

                ]

            },

            plugins: [
                shadowPlugin
            ],

            options: {

                responsive: true,

                maintainAspectRatio: false,

                cutout: '55%',

                plugins: {

                    legend: {

                        position: 'bottom',

                        labels: {

                            boxWidth: 10,

                            font: {

                                size: 10,

                                weight: '700'
                            },

                            color: '#334155'
                        }
                    }

                }
            }
        }
    );


/* =========================================================
   HTML Escape
   ========================================================= */

function escapeHtml(value) {

    return String(
        value ?? ''
    ).replace(
        /[&<>'"]/g,
        char => ({

            '&': '&amp;',
            '<': '&lt;',
            '>': '&gt;',
            "'": '&#039;',
            '"': '&quot;'

        })[char]
    );
}


/* =========================================================
   IOC 카드
   ========================================================= */

function renderIncidentCards(
    incident = {}
) {

    const container =
        document.getElementById(
            'incidentCards'
        );

    if (!container) {
        return;
    }


    const card =
        (
            active,
            level,
            title,
            detected,
            clear,
            ioc
        ) => `

            <div class="incident-card ${active ? level : ''}">

                <div class="ioc">
                    ${escapeHtml(title)}
                </div>

                <div class="state">

                    ${
                        active
                            ? detected
                            : clear
                    }

                    <br>

                    <small>
                        ${escapeHtml(ioc)}
                    </small>

                </div>

            </div>
        `;


    const c2Detected =
        incident.c2 ||
        incident.key_exfiltration;


    container.innerHTML = [

        card(
            c2Detected,
            'critical',

            'C2 / 정보 유출 IOC',

            incident.key_exfiltration
                ? '🚨 RSA 개인키 유출 탐지'
                : '🚨 C2 명령제어 통신 탐지',

            '증거 기반 C2 통신 미탐지',

            '192.168.0.86:443 · /check · /result'
        ),


        card(
            incident.malware_delivery,
            'high',

            '악성 파일 유포 IOC',

            '⚠️ V2.exe 유포지 접속 탐지',

            'V2.exe 유포 행위 미탐지',

            '192.168.0.49 · V2.exe'
        ),


        card(
            incident.ssh_movement,
            'high',

            'SSH 내부 이동 조사',

            '⚠️ 탈취 키 사용 가능성 조사',

            'SSH 내부 이동 정황 미탐지',

            '192.168.1.1 → 172.16.0.145:22'
        ),


        card(
            incident.phishing,
            'high',

            '피싱 메일 IOC',

            '⚠️ 새 백신 위장 메일 탐지',

            '피싱 메일 IOC 미탐지',

            'psc@jjcom.kr'
        )

    ].join('');
}


/* =========================================================
   검색
   ========================================================= */

function handleSearchKeyup(event) {

    clearTimeout(searchTimer);

    searchTimer =
        setTimeout(
            () => {

                /*
                 * 검색어가 바뀌어도 Elasticsearch를
                 * 다시 조회하고 기존 필터를 적용한다.
                 */

                fetchRealData();

            },
            500
        );
}


/* =========================================================
   ★ 프로토콜 체크 필터
   ========================================================= */

function getSelectedProtocols() {

    const checkboxes =
        document.querySelectorAll(
            '.protocol-checkbox'
        );

    const selected = [];

    checkboxes.forEach(
        checkbox => {

            if (checkbox.checked) {

                selected.push(
                    String(
                        checkbox.value
                    ).toUpperCase()
                );

            }

        }
    );

    return selected;
}


/* =========================================================
   ★ 프로토콜 전체 보기
   ========================================================= */

function toggleAllProtocols(
    masterCheckbox
) {

    const checked =
        Boolean(
            masterCheckbox.checked
        );


    const checkboxes =
        document.querySelectorAll(
            '.protocol-checkbox'
        );


    checkboxes.forEach(
        checkbox => {

            checkbox.checked =
                checked;

        }
    );


    updateProtocolLabelState();

    filterLogs();
}


/* =========================================================
   ★ 개별 프로토콜 변경
   ========================================================= */

function handleProtocolChange(
    changedCheckbox
) {

    const checkboxes =
        Array.from(
            document.querySelectorAll(
                '.protocol-checkbox'
            )
        );


    const allChecked =
        checkboxes.length > 0 &&
        checkboxes.every(
            checkbox =>
                checkbox.checked
        );


    const master =
        document.getElementById(
            'proto-all'
        );


    if (master) {

        master.checked =
            allChecked;

    }


    updateProtocolLabelState();

    filterLogs();
}


/* =========================================================
   ★ 프로토콜 라벨 상태
   ========================================================= */

function updateProtocolLabelState() {

    const labels =
        document.querySelectorAll(
            '.protocol-check'
        );


    labels.forEach(
        label => {

            const checkbox =
                label.querySelector(
                    'input[type="checkbox"]'
                );

            if (!checkbox) {
                return;
            }


            if (checkbox.checked) {

                label.classList.add(
                    'active'
                );

            } else {

                label.classList.remove(
                    'active'
                );

            }

        }
    );


    const selected =
        getSelectedProtocols();


    const count =
        document.getElementById(
            'protocol-filter-count'
        );


    if (!count) {
        return;
    }


    if (
        selected.length ===
        PROTOCOL_NAMES.length
    ) {

        count.innerText =
            `${selected.length}개 프로토콜 표시`;

    } else if (
        selected.length === 0
    ) {

        count.innerText =
            '프로토콜 없음';

    } else {

        count.innerText =
            `${selected.length}개 프로토콜 표시`;

    }
}


/* =========================================================
   ★ 프로토콜 이름 정규화
   ========================================================= */

function normalizeProtocol(
    value
) {

    let proto =
        String(
            value ?? ''
        )
        .trim()
        .toUpperCase();


    /*
     * Elasticsearch 데이터에 따라
     * 표기가 조금 다를 수 있으므로 정규화한다.
     */

    if (
        proto === 'DHCPV4' ||
        proto === 'DHCP4' ||
        proto === 'DHCP'
    ) {

        return 'DHCPV4';
    }


    if (
        proto === 'HTTPS' ||
        proto === 'HTTP/SSL'
    ) {

        return 'HTTPS';
    }


    if (
        proto === 'TLSV1' ||
        proto === 'TLSV1.2' ||
        proto === 'TLSV1.3'
    ) {

        return 'TLS';
    }


    return proto;
}


/* =========================================================
   로그 필터
   ========================================================= */

function filterLogs() {

    const sevElement =
        document.getElementById(
            'sev-filter'
        );

    const searchElement =
        document.getElementById(
            'sig-search'
        );


    const sevSel =
        sevElement
            ? sevElement.value
            : 'ALL';


    const keyword =
        searchElement
            ? String(
                searchElement.value || ''
            )
                .toLowerCase()
                .trim()
            : '';


    if (!Array.isArray(allLogsData)) {

        allLogsData = [];

    }


    /*
     * ★ 현재 체크된 프로토콜 목록
     */

    const selectedProtocols =
        getSelectedProtocols();


    const filtered =
        allLogsData.filter(
            log => {

                if (
                    !log ||
                    typeof log !== 'object'
                ) {

                    return false;

                }


                const sev =
                    String(
                        log.sev || ''
                    )
                    .toUpperCase();


                const src =
                    String(
                        log.src || ''
                    )
                    .toLowerCase();


                const dst =
                    String(
                        log.dst || ''
                    )
                    .toLowerCase();


                const info =
                    String(
                        log.info || ''
                    )
                    .toLowerCase();


                const attackType =
                    String(
                        log.attack_type || ''
                    )
                    .toLowerCase();


                const proto =
                    String(
                        log.proto || ''
                    )
                    .toLowerCase();


                const country =
                    String(
                        log.country || ''
                    )
                    .toLowerCase();


                const action =
                    String(
                        log.action || ''
                    )
                    .toLowerCase();


                /*
                 * =========================================
                 * 등급 필터
                 * =========================================
                 */

                const matchSev =
                    sevSel === 'ALL' ||
                    sev === sevSel;


                /*
                 * =========================================
                 * 검색 필터
                 * =========================================
                 */

                const matchKeyword =
                    keyword === '' ||

                    src.includes(keyword) ||

                    dst.includes(keyword) ||

                    info.includes(keyword) ||

                    attackType.includes(keyword) ||

                    proto.includes(keyword) ||

                    country.includes(keyword) ||

                    action.includes(keyword);


                /*
                 * =========================================
                 * ★ 프로토콜 필터
                 * =========================================
                 */

                const normalizedProto =
                    normalizeProtocol(
                        log.proto
                    );


                let matchProtocol =
                    false;


                /*
                 * 아무것도 체크되지 않았으면
                 * 화면에 데이터를 표시하지 않는다.
                 */

                if (
                    selectedProtocols.length === 0
                ) {

                    matchProtocol = false;

                } else {

                    matchProtocol =
                        selectedProtocols.includes(
                            normalizedProto
                        );

                }


                return (
                    matchSev &&
                    matchKeyword &&
                    matchProtocol
                );

            }
        );


    renderTable(filtered);

    updateProtocolLabelState();
}


/* =========================================================
   테이블 렌더링
   ========================================================= */

function renderTable(logs) {

    const tbody =
        document.getElementById(
            'log-body'
        );


    if (!tbody) {
        return;
    }


    tbody.innerHTML = '';


    if (
        !Array.isArray(logs) ||
        logs.length === 0
    ) {

        tbody.innerHTML = `

            <tr>

                <td
                    colspan="8"
                    style="
                        text-align: center;
                        padding: 30px;
                        color: var(--text-muted);
                        cursor: default;
                    "
                >
                    선택한 조건에 해당하는
                    데이터가 없습니다.
                </td>

            </tr>

        `;


        document.getElementById(
            'log-counter'
        ).innerText = '0 건';


        return;
    }


    logs.forEach(
        (log, index) => {

            const tr =
                document.createElement(
                    'tr'
                );


            if (
                log.sev ===
                'CRITICAL'
            ) {

                tr.style.backgroundColor =
                    '#fee2e2';

            } else if (
                log.sev ===
                'HIGH'
            ) {

                tr.style.backgroundColor =
                    '#fef2f2';

            }


            tr.onclick =
                () =>
                    showPacketDetail(
                        log,
                        index + 1
                    );


            let badgeColor =
                log.sev ===
                'CRITICAL'
                    ? 'var(--red)'
                    : (
                        log.sev ===
                        'HIGH'
                            ? 'var(--red)'
                            : (
                                log.sev ===
                                'MEDIUM'
                                    ? 'var(--yellow)'
                                    : 'var(--green)'
                            )
                    );


            let sevText =
                log.sev ===
                'CRITICAL'
                    ? '긴급 (CRITICAL)'
                    : (
                        log.sev ===
                        'HIGH'
                            ? '위험 (HIGH)'
                            : (
                                log.sev ===
                                'MEDIUM'
                                    ? '경고 (MEDIUM)'
                                    : '일반 (LOW)'
                            )
                    );


            let intelBadge =
                log.is_bad
                    ? `
                        <span
                            style="
                                background:#fee2e2;
                                color:#dc2626;
                                padding:2px 6px;
                                border-radius:4px;
                                font-size:0.7rem;
                                font-weight:700;
                            "
                        >
                            ⚠️ 악성 매칭
                        </span>
                    `
                    : '';


            tr.innerHTML = `

                <td
                    style="
                        color: var(--text-muted);
                        font-weight: 600;
                    "
                >
                    ${index + 1}
                </td>


                <td
                    style="
                        font-weight: 600;
                    "
                >
                    ${escapeHtml(log.time)}
                </td>


                <td
                    style="
                        font-weight: 700;
                        color: var(--blue);
                    "
                >
                    ${escapeHtml(log.src)}
                </td>


                <td
                    style="
                        font-weight: 600;
                    "
                >
                    ${escapeHtml(log.dst)}
                </td>


                <td>

                    <span
                        style="
                            background: #e2e8f0;
                            padding: 3px 8px;
                            border-radius: 4px;
                            font-size: 0.75rem;
                            font-weight: 700;
                        "
                    >
                        ${escapeHtml(log.proto)}
                    </span>

                </td>


                <td
                    style="
                        font-weight: 600;
                    "
                >
                    ${escapeHtml(log.country)}
                </td>


                <td>
                    ${escapeHtml(log.info)}
                </td>


                <td>

                    <span
                        style="
                            color: ${badgeColor};
                            font-weight: 800;
                        "
                    >
                        [${sevText}]
                    </span>

                    ${intelBadge}

                    <br>

                    <span
                        style="
                            font-size: 0.7rem;
                            color: var(--text-muted);
                            font-weight: 600;
                        "
                    >
                        조치:
                        ${escapeHtml(log.action)}
                    </span>

                </td>

            `;


            tbody.appendChild(tr);

        }
    );


    const counter =
        document.getElementById(
            'log-counter'
        );


    if (counter) {

        counter.innerText =
            `${logs.length} 건`;

    }
}


/* =========================================================
   대역폭 랭킹
   ========================================================= */

function renderBandwidthRanking(
    ranking
) {

    const container =
        document.getElementById(
            'bandwidthRankingList'
        );


    if (!container) {
        return;
    }


    if (
        !ranking ||
        ranking.length === 0
    ) {

        container.innerHTML = `

            <div
                style="
                    color: var(--text-muted);
                    text-align: center;
                    margin-top: 60px;
                    font-size: 0.8rem;
                "
            >
                트래픽 데이터 없음
            </div>

        `;

        return;
    }


    let html = '';


    ranking.forEach(
        (item, idx) => {

            let rankClass =
                idx === 0
                    ? 'rank-1'
                    : (
                        idx === 1
                            ? 'rank-2'
                            : (
                                idx === 2
                                    ? 'rank-3'
                                    : ''
                            )
                    );


            html += `

                <div class="ranking-item">

                    <div
                        style="
                            display: flex;
                            align-items: center;
                            gap: 8px;
                        "
                    >

                        <span
                            class="rank-badge ${rankClass}"
                        >
                            ${idx + 1}
                        </span>

                        <span
                            style="
                                font-weight: 700;
                                color: var(--blue);
                            "
                        >
                            ${escapeHtml(item.ip)}
                        </span>

                    </div>


                    <span
                        style="
                            font-weight: 800;
                            color: var(--green);
                        "
                    >
                        ${escapeHtml(item.mb)} MB
                    </span>

                </div>

            `;

        }
    );


    container.innerHTML = html;
}


/* =========================================================
   포렌식 상세 모달
   ========================================================= */

function showPacketDetail(
    log,
    no
) {

    const modal =
        document.getElementById(
            'packetModal'
        );


    const modalBody =
        document.getElementById(
            'modalBody'
        );


    document.getElementById(
        'modalTitle'
    ).innerText =
        `📦 Wireshark Forensic Deep Inspection [Log No. ${no}]`;


    let rawPayload =
        escapeHtml(
            log.full_payload ||
            "캡처된 페이로드 데이터가 없습니다."
        );


    let srcIpOnly =
        String(
            log.src || ''
        )
        .split(':')[0];


    let dstIpOnly =
        String(
            log.dst || ''
        )
        .split(':')[0];


    let protoName = '';

    let actionDesc = '';


    if (log.is_bad) {

        protoName =
            log.attack_type ||
            "탐지 규칙 기반 위협 통신";


        actionDesc =
            "증거 기반 IOC 또는 공격 시그니처와 일치했습니다. 아래 원시 페이로드와 권고 조치를 확인하세요.";

    }

    else if (
        log.proto === 'SMTP'
    ) {

        protoName =
            "메일 발송 (SMTP) 프로토콜";


        actionDesc =
            "메일 클라이언트를 통해 외부 메일 서버로 메일이나 첨부파일을 전송하고 있는 트래픽입니다.";

    }

    else if (
        log.proto === 'IMAP' ||
        log.proto === 'POP3'
    ) {

        protoName =
            "메일 수신 (IMAP/POP3) 프로토콜";


        actionDesc =
            "메일 서버에 접속하여 이메일을 읽어오거나 편지함을 동기화하고 있는 트래픽입니다.";

    }

    else if (
        log.proto === 'HTTP' ||
        log.proto === 'HTTPS'
    ) {

        protoName =
            "웹 브라우징 (HTTP/HTTPS)";


        actionDesc =
            "웹 브라우저를 통해 특정 웹사이트에 접속하거나 웹 서버와 API 데이터를 주고받고 있는 일반적인 인터넷 활동입니다.";

    }

    else if (
        log.proto === 'SSH'
    ) {

        protoName =
            "보안 원격 터미널 접속 (SSH)";


        actionDesc =
            "관리자나 사용자가 암호화된 터널을 통해 대상 서버에 원격으로 접속하여 명령어를 실행하려는 세션입니다.";

    }

    else if (
        log.proto === 'DNS'
    ) {

        protoName =
            "도메인 이름 질의 (DNS)";


        actionDesc =
            "사용자가 인터넷 주소를 입력하여 실제 IP 주소가 무엇인지 확인하는 DNS 질의 패킷입니다.";

    }

    else if (
        log.proto === 'TCP' ||
        log.proto === 'UDP'
    ) {

        protoName =
            `기본 전송 계층 (${log.proto})`;


        actionDesc =
            "응용 프로그램이 데이터를 전송하기 위해 기본 연결 통로를 형성하고 있거나 암호화되어 내용을 알 수 없는 트래픽입니다.";

    }

    else {

        protoName =
            `기타 통신 (${log.proto || 'UNKNOWN'})`;


        actionDesc =
            "해당 프로토콜의 표준 데이터 교환을 수행하고 있는 세션입니다.";

    }


    const isBad =
        Boolean(
            log.is_bad
        );


    const themeColor =
        isBad
            ? '#ef4444'
            : '#10b981';


    const bgLight =
        isBad
            ? 'rgba(239, 68, 68, 0.1)'
            : 'rgba(16, 185, 129, 0.1)';


    const threatIcon =
        isBad
            ? '🚨'
            : '✅';


    const threatText =
        isBad
            ? '위험 트래픽 탐지 (Threat Detected)'
            : '정상 통신 (Clean Traffic)';


    const safeSrc =
        escapeHtml(srcIpOnly);


    const safeDst =
        escapeHtml(dstIpOnly);


    const safeProtoName =
        escapeHtml(protoName);


    const safeActionDesc =
        escapeHtml(actionDesc);


    const safeTime =
        escapeHtml(log.time);


    const safeCountry =
        escapeHtml(
            log.country ||
            '사설망 (Local Network)'
        );


    const safeInfo =
        escapeHtml(log.info);


    const safeProto =
        escapeHtml(log.proto);


    const safeAction =
        escapeHtml(
            log.action ||
            '정상 허용 (Allow)'
        );


    const safeAttackType =
        escapeHtml(
            log.attack_type ||
            '알 수 없는 위협'
        );


    const packetLength =
        escapeHtml(
            log.len ?? '-'
        );


    let modalHtml = `

        <div
            style="
                font-family: var(--font-mono);
                font-size: 14.5px;
            "
        >

            <!-- 핵심 브리핑 -->

            <div
                style="
                    background-color: #1e293b;
                    border-left: 5px solid ${themeColor};
                    padding: 18px;
                    border-radius: 6px;
                    margin-bottom: 20px;
                    box-shadow:
                        0 4px 6px -1px
                        rgba(0,0,0,0.3);
                "
            >

                <h4
                    style="
                        margin: 0 0 15px 0;
                        color: ${themeColor};
                        font-size: 17px;
                        font-weight: 700;
                        display: flex;
                        align-items: center;
                        gap: 8px;
                    "
                >

                    ${threatIcon}

                    [SOC 자동 패킷 포렌식 브리핑]

                    -

                    ${threatText}

                </h4>


                <div
                    style="
                        display: flex;
                        flex-direction: column;
                        gap: 10px;
                        line-height: 1.5;
                    "
                >

                    <div>

                        <span
                            style="
                                color: #94a3b8;
                                width: 110px;
                                display: inline-block;
                            "
                        >
                            발원지 (Who)
                        </span>

                        :

                        <span
                            style="
                                color: #38bdf8;
                                font-weight: bold;
                            "
                        >
                            ${safeSrc}
                        </span>

                        단말기에서

                    </div>


                    <div>

                        <span
                            style="
                                color: #94a3b8;
                                width: 110px;
                                display: inline-block;
                            "
                        >
                            목적지 (Where)
                        </span>

                        :

                        <span
                            style="
                                color: #38bdf8;
                                font-weight: bold;
                            "
                        >
                            ${safeDst}
                        </span>

                        서버를 향해

                    </div>


                    <div>

                        <span
                            style="
                                color: #94a3b8;
                                width: 110px;
                                display: inline-block;
                            "
                        >
                            행위 (What)
                        </span>

                        :

                        <span style="color: #e2e8f0;">

                            <b>
                                ${safeProtoName}
                            </b>

                            을(를) 사용하고 있습니다.

                        </span>

                    </div>


                    <div>

                        <span
                            style="
                                color: #94a3b8;
                                width: 110px;
                                display: inline-block;
                            "
                        >
                            상황 판단
                        </span>

                        :

                        <span style="color: #e2e8f0;">

                            ${safeActionDesc}

                        </span>

                    </div>

                </div>

            </div>


            <!-- 상세 정보 -->

            <div
                style="
                    display: grid;
                    grid-template-columns:
                        1fr 1fr;
                    gap: 15px;
                    margin-bottom: 20px;
                "
            >

                <div
                    style="
                        background-color: #1e293b;
                        padding: 16px;
                        border-radius: 6px;
                    "
                >

                    <h5
                        style="
                            margin: 0 0 12px 0;
                            color: #e2e8f0;
                            font-size: 15px;
                            border-bottom:
                                1px solid #334155;
                            padding-bottom: 8px;
                        "
                    >
                        📌 네트워크 & 시간 정보
                    </h5>


                    <ul
                        style="
                            list-style: none;
                            padding: 0;
                            margin: 0;
                            font-size: 14px;
                            display: flex;
                            flex-direction: column;
                            gap: 10px;
                        "
                    >

                        <li>

                            <span
                                style="
                                    color:#94a3b8;
                                    display:inline-block;
                                    width:85px;
                                "
                            >
                                캡처 시각
                            </span>

                            <span
                                style="
                                    color:#cbd5e1;
                                "
                            >
                                ${safeTime} KST
                            </span>

                        </li>


                        <li>

                            <span
                                style="
                                    color:#94a3b8;
                                    display:inline-block;
                                    width:85px;
                                "
                            >
                                패킷 크기
                            </span>

                            <span
                                style="
                                    color:#cbd5e1;
                                "
                            >
                                ${packetLength} Bytes
                            </span>

                        </li>


                        <li>

                            <span
                                style="
                                    color:#94a3b8;
                                    display:inline-block;
                                    width:85px;
                                "
                            >
                                출발 국가
                            </span>

                            <span
                                style="
                                    color:#cbd5e1;
                                "
                            >
                                ${safeCountry}
                            </span>

                        </li>

                    </ul>

                </div>


                <div
                    style="
                        background-color: #1e293b;
                        padding: 16px;
                        border-radius: 6px;
                    "
                >

                    <h5
                        style="
                            margin: 0 0 12px 0;
                            color: #e2e8f0;
                            font-size: 15px;
                            border-bottom:
                                1px solid #334155;
                            padding-bottom: 8px;
                        "
                    >
                        🛡️ 보안 이벤트 요약
                    </h5>


                    <ul
                        style="
                            list-style: none;
                            padding: 0;
                            margin: 0;
                            font-size: 14px;
                            display: flex;
                            flex-direction: column;
                            gap: 10px;
                        "
                    >

                        <li>

                            <span
                                style="
                                    color:#94a3b8;
                                    display:inline-block;
                                    width:85px;
                                "
                            >
                                이벤트
                            </span>

                            <span
                                style="
                                    color:#cbd5e1;
                                    word-break:
                                        keep-all;
                                "
                            >
                                ${safeInfo}
                            </span>

                        </li>


                        <li>

                            <span
                                style="
                                    color:#94a3b8;
                                    display:inline-block;
                                    width:85px;
                                "
                            >
                                서비스
                            </span>

                            <span
                                style="
                                    background:#334155;
                                    padding:3px 8px;
                                    border-radius:4px;
                                    color:#60a5fa;
                                    font-weight:bold;
                                    font-size:12px;
                                "
                            >
                                ${safeProto}
                            </span>

                        </li>


                        <li>

                            <span
                                style="
                                    color:#94a3b8;
                                    display:inline-block;
                                    width:85px;
                                "
                            >
                                방화벽 조치
                            </span>

                            <span
                                style="
                                    color: ${themeColor};
                                    font-weight: bold;
                                "
                            >
                                ${safeAction}
                            </span>

                        </li>

                    </ul>

                </div>

            </div>


            <!-- Raw Payload -->

            <div
                style="
                    margin-bottom: 20px;
                "
            >

                <h5
                    style="
                        margin: 0 0 8px 0;
                        color: #e2e8f0;
                        font-size: 15px;
                    "
                >
                    ✉️ 원시 페이로드
                    (Raw Payload / Packet Data)
                </h5>


                <div
                    style="
                        background-color: #020617;
                        color: #10b981;
                        font-family:
                            'Courier New',
                            Courier,
                            monospace;
                        padding: 15px;
                        border-radius: 6px;
                        border:
                            1px solid #334155;
                        max-height: 180px;
                        overflow-y: auto;
                        font-size: 13.5px;
                        line-height: 1.4;
                        white-space: pre-wrap;
                        word-break: break-all;
                    "
                >
                    ${rawPayload}
                </div>

            </div>


            <!-- Threat Intel -->

            <div
                style="
                    background-color: ${bgLight};
                    border:
                        1px solid ${themeColor};
                    padding: 16px;
                    border-radius: 6px;
                "
            >

                <h5
                    style="
                        margin: 0 0 10px 0;
                        color: ${themeColor};
                        font-size: 15px;
                        font-weight: bold;
                    "
                >
                    📊 위협 인텔리전스 평판 조회
                    (Threat Intel)
                </h5>


                <div
                    style="
                        font-size: 14px;
                        color: #e2e8f0;
                        line-height: 1.6;
                    "
                >

                    ${
                        isBad

                            ? `

                                - ⚠️ 
                                <b>
                                    악성 행위
                                    (공격 시그니처)가
                                    탐지되었습니다.
                                </b>

                                해당 IP에 대한
                                즉각적인 차단 및
                                포렌식 조사가 필요합니다.

                                <br>

                                - <b>
                                    공격자/침해 단말:
                                  </b>

                                <span
                                    style="
                                        color:#f87171;
                                        font-weight:bold;
                                        text-decoration:underline;
                                    "
                                >
                                    ${safeSrc}
                                </span>

                                <br>

                                - <b>
                                    추정 공격 기법:
                                  </b>

                                <span
                                    style="
                                        color:#facc15;
                                    "
                                >
                                    ${safeAttackType}
                                </span>

                                <br>

                                - <b
                                    style="
                                        color:#facc15;
                                    "
                                >
                                    💡 관제 센터 권고 조치:
                                  </b>

                                즉시 인바운드
                                방화벽 규칙에 추가하여
                                해당 IP 차단 및
                                네트워크 격리 권장.

                            `

                            : `

                                - ✅ 현재 OSINT
                                평판 검사 결과
                                <b>안전한 IP</b>로
                                확인되었습니다 (Clean).

                                <br>

                                - 추가적인 공격
                                시그니처가 발견되지 않은
                                정상 트래픽입니다.

                            `
                    }

                </div>

            </div>

        </div>
    `;


    modalBody.innerHTML =
        modalHtml;


    modal.style.display =
        'flex';
}


/* =========================================================
   모달 닫기
   ========================================================= */

function closeModal() {

    const modal =
        document.getElementById(
            'packetModal'
        );


    if (modal) {

        modal.style.display =
            'none';

    }
}


/* =========================================================
   모달 바깥 클릭
   ========================================================= */

window.addEventListener(
    'click',
    function (event) {

        const modal =
            document.getElementById(
                'packetModal'
            );


        if (
            event.target === modal
        ) {

            closeModal();

        }

    }
);


/* =========================================================
   ESC 키로 모달 닫기
   ========================================================= */

window.addEventListener(
    'keydown',
    function (event) {

        if (
            event.key === 'Escape'
        ) {

            closeModal();

        }

    }
);


/* =========================================================
   Elasticsearch 데이터 조회
   ========================================================= */

async function fetchRealData() {

    if (isFetching) {
        return;
    }


    isFetching = true;


    const manualBtn =
        document.getElementById(
            'manual-btn'
        );


    if (manualBtn) {

        manualBtn.innerText =
            '포렌식 조회 중...';

    }


    const hostElement =
        document.getElementById(
            'elk-host'
        );


    const indexElement =
        document.getElementById(
            'elk-index'
        );


    const dateElement =
        document.getElementById(
            'search-date'
        );


    const hourElement =
        document.getElementById(
            'search-hour'
        );


    const searchElement =
        document.getElementById(
            'sig-search'
        );


    const hostVal =
        hostElement
            ? hostElement.value.trim()
            : '';


    const indexVal =
        indexElement
            ? indexElement.value.trim()
            : '';


    const dateVal =
        dateElement
            ? dateElement.value
            : '';


    const hourVal =
        hourElement
            ? hourElement.value
            : '';


    const searchVal =
        searchElement
            ? searchElement.value.trim()
            : '';


    try {

        const res =
            await fetch(
                `/api/dashboard-data?host=${encodeURIComponent(hostVal)}` +
                `&index=${encodeURIComponent(indexVal)}` +
                `&date=${encodeURIComponent(dateVal)}` +
                `&hour=${encodeURIComponent(hourVal)}` +
                `&search=${encodeURIComponent(searchVal)}`
            );


        if (!res.ok) {

            throw new Error(
                `HTTP ${res.status}`
            );

        }


        const data =
            await res.json();


        if (
            data.status ===
            'success'
        ) {

            const statusText =
                document.getElementById(
                    'sys-status-text'
                );


            const syncBadge =
                document.getElementById(
                    'sync-badge'
                );


            if (statusText) {

                statusText.innerText =
                    data.total_status || '';

            }


            if (
                data.has_threat
            ) {

                if (statusText) {

                    statusText.style.color =
                        'var(--red)';

                }


                if (syncBadge) {

                    syncBadge.className =
                        'badge badge-red';

                    syncBadge.innerText =
                        '⚠️ 고위험 위협 탐지됨';

                }

            }

            else {

                if (statusText) {

                    statusText.style.color =
                        'var(--green)';

                }


                if (syncBadge) {

                    syncBadge.className =
                        'badge badge-green';

                    syncBadge.innerText =
                        '시스템 정상 모니터링 중';

                }

            }


            const summary =
                data.summary || {};


            const quickMetrics =
                document.getElementById(
                    'quick-metrics'
                );


            if (quickMetrics) {

                quickMetrics.innerText =
                    `활성 IP: ${summary.unique_ips || 0}개 | ` +
                    `긴급: ${summary.critical_cnt || 0}건 | ` +
                    `위험: ${summary.high_cnt || 0}건`;

            }


            /*
             * 시간대별 차트
             */

            const now =
                new Date();


            const todayStr =
                new Date(
                    now.getTime() -
                    now.getTimezoneOffset() *
                    60000
                )
                .toISOString()
                .split('T')[0];


            const isToday =
                !dateVal ||
                dateVal === todayStr;


            const sliceHour =
                isToday
                    ? now.getHours()
                    : 23;


            const chartData =
                data.chart || {
                    labels: [],
                    data: []
                };


            freqChart.data.labels =
                Array.isArray(
                    chartData.labels
                )
                    ? chartData.labels.slice(
                        0,
                        sliceHour + 1
                    )
                    : [];


            freqChart.data.datasets[0].data =
                Array.isArray(
                    chartData.data
                )
                    ? chartData.data.slice(
                        0,
                        sliceHour + 1
                    )
                    : [];


            freqChart.update();


            /*
             * 국가별 차트
             */

            const geoData =
                data.geo_chart || {
                    labels: [],
                    data: []
                };


            geoChart.data.labels =
                Array.isArray(
                    geoData.labels
                )
                    ? geoData.labels
                    : [];


            geoChart.data.datasets[0].data =
                Array.isArray(
                    geoData.data
                )
                    ? geoData.data
                    : [];


            geoChart.update();


            /*
             * Top Talkers
             */

            renderBandwidthRanking(
                data.bandwidth_ranking || []
            );


            /*
             * IOC
             */

            renderIncidentCards(
                data.incident || {}
            );


            /*
             * 전체 로그 저장
             */

            allLogsData =
                Array.isArray(
                    data.logs
                )
                    ? data.logs
                    : [];


            console.log(
                "=== 관제 데이터 확인 ==="
            );

            console.log(
                "API 전체 건수:",
                data.debug
                    ? data.debug.total_hits
                    : "확인불가"
            );

            console.log(
                "전달받은 logs:",
                allLogsData.length
            );

            console.log(
                "첫 번째 로그:",
                allLogsData[0]
            );


            /*
             * ★ 중요
             *
             * 여기서는 무조건 전체를
             * renderTable하지 않는다.
             *
             * 등급 + 검색 + 프로토콜
             * 필터를 모두 적용한다.
             */

            filterLogs();

        }

        else {

            console.warn(
                "데이터 로드 경고:",
                data.message
            );

            allLogsData = [];

            renderTable([]);

        }

    }

    catch (e) {

        console.error(
            "Elasticsearch / API 조회 오류:",
            e
        );


        const statusText =
            document.getElementById(
                'sys-status-text'
            );


        const syncBadge =
            document.getElementById(
                'sync-badge'
            );


        if (statusText) {

            statusText.innerText =
                'ELK 연결 확인 필요';

            statusText.style.color =
                'var(--red)';

        }


        if (syncBadge) {

            syncBadge.className =
                'badge badge-red';

            syncBadge.innerText =
                '⚠️ ELK 연결 확인 필요';

        }

    }

    finally {

        if (manualBtn) {

            manualBtn.innerText =
                '실시간 포렌식 갱신';

        }


        isFetching = false;

    }

}


/* =========================================================
   갱신 주기
   ========================================================= */

function changeSyncInterval() {

    const element =
        document.getElementById(
            'sync-interval'
        );


    const intervalTime =
        element
            ? parseInt(
                element.value,
                10
            )
            : 0;


    clearInterval(
        syncInterval
    );


    syncInterval = null;


    if (
        intervalTime > 0
    ) {

        syncInterval =
            setInterval(
                fetchRealData,
                intervalTime
            );

    }

}


/* =========================================================
   초기 프로토콜 상태
   ========================================================= */

updateProtocolLabelState();


/* =========================================================
   최초 데이터 조회
   ========================================================= */

fetchRealData();


/* =========================================================
   기본 자동 갱신 5초
   ========================================================= */

syncInterval =
    setInterval(
        fetchRealData,
        5000
    );

</script>

</body>
</html>
이 노트는 로그인하지 않아도 열람할 수 있습니다. 작성·수정·삭제는 관리자 로그인 후 가능합니다.