| 1 | """
|
|---|
| 2 | COMPLETE FIXED SYSMON SERVER - Working Dashboard
|
|---|
| 3 | """
|
|---|
| 4 |
|
|---|
| 5 | from flask import Flask, request, jsonify, render_template, send_from_directory
|
|---|
| 6 | import sqlite3
|
|---|
| 7 | import json
|
|---|
| 8 | from datetime import datetime, timedelta
|
|---|
| 9 | import os
|
|---|
| 10 | import re
|
|---|
| 11 |
|
|---|
| 12 | app = Flask(__name__)
|
|---|
| 13 |
|
|---|
| 14 |
|
|---|
| 15 | def init_database():
|
|---|
| 16 | """Inicializiraј ja bazata"""
|
|---|
| 17 | conn = sqlite3.connect('sysmon_server.db', check_same_thread=False)
|
|---|
| 18 | cursor = conn.cursor()
|
|---|
| 19 |
|
|---|
| 20 | # Kreiraј tabeli
|
|---|
| 21 | cursor.execute('''
|
|---|
| 22 | CREATE TABLE IF NOT EXISTS sysmon_events (
|
|---|
| 23 | id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|---|
| 24 | event_id INTEGER,
|
|---|
| 25 | event_type TEXT,
|
|---|
| 26 | timestamp TEXT,
|
|---|
| 27 | computer TEXT,
|
|---|
| 28 | process_name TEXT,
|
|---|
| 29 | command_line TEXT,
|
|---|
| 30 | process_user TEXT,
|
|---|
| 31 | parent_process TEXT,
|
|---|
| 32 | dns_query TEXT,
|
|---|
| 33 | dns_results TEXT,
|
|---|
| 34 | dns_process TEXT,
|
|---|
| 35 | source_ip TEXT,
|
|---|
| 36 | dest_ip TEXT,
|
|---|
| 37 | dest_port TEXT,
|
|---|
| 38 | file_path TEXT,
|
|---|
| 39 | raw_data TEXT,
|
|---|
| 40 | received_at TEXT
|
|---|
| 41 | )
|
|---|
| 42 | ''')
|
|---|
| 43 |
|
|---|
| 44 | cursor.execute('''
|
|---|
| 45 | CREATE TABLE IF NOT EXISTS processes (
|
|---|
| 46 | id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|---|
| 47 | pid INTEGER,
|
|---|
| 48 | name TEXT,
|
|---|
| 49 | user TEXT,
|
|---|
| 50 | cpu_percent REAL,
|
|---|
| 51 | memory_mb REAL,
|
|---|
| 52 | cmdline TEXT,
|
|---|
| 53 | computer TEXT,
|
|---|
| 54 | received_at TEXT
|
|---|
| 55 | )
|
|---|
| 56 | ''')
|
|---|
| 57 |
|
|---|
| 58 | cursor.execute('''
|
|---|
| 59 | CREATE TABLE IF NOT EXISTS computers (
|
|---|
| 60 | id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|---|
| 61 | computer_name TEXT UNIQUE,
|
|---|
| 62 | user TEXT,
|
|---|
| 63 | ip_address TEXT,
|
|---|
| 64 | os TEXT,
|
|---|
| 65 | last_seen TEXT,
|
|---|
| 66 | status TEXT DEFAULT 'online'
|
|---|
| 67 | )
|
|---|
| 68 | ''')
|
|---|
| 69 |
|
|---|
| 70 | # Indeksi
|
|---|
| 71 | cursor.execute('CREATE INDEX IF NOT EXISTS idx_computer ON sysmon_events(computer)')
|
|---|
| 72 | cursor.execute('CREATE INDEX IF NOT EXISTS idx_dns_query ON sysmon_events(dns_query)')
|
|---|
| 73 |
|
|---|
| 74 | conn.commit()
|
|---|
| 75 | conn.close()
|
|---|
| 76 | print("✅ Database initialized")
|
|---|
| 77 |
|
|---|
| 78 |
|
|---|
| 79 | def get_db_connection():
|
|---|
| 80 | """Vrati database connection"""
|
|---|
| 81 | conn = sqlite3.connect('sysmon_server.db', check_same_thread=False)
|
|---|
| 82 | conn.row_factory = sqlite3.Row
|
|---|
| 83 | return conn
|
|---|
| 84 |
|
|---|
| 85 |
|
|---|
| 86 | def update_computer_status(computer_name, user, ip_address, os_info):
|
|---|
| 87 | """Update computer status"""
|
|---|
| 88 | conn = get_db_connection()
|
|---|
| 89 | cursor = conn.cursor()
|
|---|
| 90 |
|
|---|
| 91 | try:
|
|---|
| 92 | cursor.execute('''
|
|---|
| 93 | INSERT OR REPLACE INTO computers
|
|---|
| 94 | (computer_name, user, ip_address, os, last_seen, status)
|
|---|
| 95 | VALUES (?, ?, ?, ?, ?, ?)
|
|---|
| 96 | ''', (computer_name, user, ip_address, os_info, datetime.now().isoformat(), 'online'))
|
|---|
| 97 | conn.commit()
|
|---|
| 98 | except Exception as e:
|
|---|
| 99 | print(f"Error updating computer: {e}")
|
|---|
| 100 | finally:
|
|---|
| 101 | conn.close()
|
|---|
| 102 |
|
|---|
| 103 |
|
|---|
| 104 | @app.route('/')
|
|---|
| 105 | def index():
|
|---|
| 106 | """Main dashboard page"""
|
|---|
| 107 | return '''
|
|---|
| 108 | <!DOCTYPE html>
|
|---|
| 109 | <html>
|
|---|
| 110 | <head>
|
|---|
| 111 | <title>Sysmon Dashboard</title>
|
|---|
| 112 | <meta charset="UTF-8">
|
|---|
| 113 | <meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|---|
| 114 | <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
|
|---|
| 115 | <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
|
|---|
| 116 | <style>
|
|---|
| 117 | body { background-color: #f8f9fa; padding: 20px; }
|
|---|
| 118 | .card { margin-bottom: 20px; box-shadow: 0 2px 4px rgba(0,0,0,.1); }
|
|---|
| 119 | .stat-card { border-left: 4px solid; }
|
|---|
| 120 | .event-item { padding: 10px; border-left: 3px solid; margin-bottom: 5px; background: white; }
|
|---|
| 121 | .event-dns { border-left-color: #3498db; }
|
|---|
| 122 | .event-process { border-left-color: #2ecc71; }
|
|---|
| 123 | .event-network { border-left-color: #e74c3c; }
|
|---|
| 124 | .nav-tabs .nav-link.active { font-weight: bold; }
|
|---|
| 125 | </style>
|
|---|
| 126 | </head>
|
|---|
| 127 | <body>
|
|---|
| 128 | <nav class="navbar navbar-dark bg-dark mb-4">
|
|---|
| 129 | <div class="container-fluid">
|
|---|
| 130 | <span class="navbar-brand">
|
|---|
| 131 | 🛡️ Sysmon Dashboard
|
|---|
| 132 | </span>
|
|---|
| 133 | <span class="navbar-text" id="currentTime"></span>
|
|---|
| 134 | </div>
|
|---|
| 135 | </nav>
|
|---|
| 136 |
|
|---|
| 137 | <div class="container-fluid">
|
|---|
| 138 | <!-- Stats -->
|
|---|
| 139 | <div class="row mb-4">
|
|---|
| 140 | <div class="col-md-2 col-sm-6">
|
|---|
| 141 | <div class="card stat-card border-left-primary">
|
|---|
| 142 | <div class="card-body">
|
|---|
| 143 | <h6>Total Events</h6>
|
|---|
| 144 | <h3 id="totalEvents">0</h3>
|
|---|
| 145 | </div>
|
|---|
| 146 | </div>
|
|---|
| 147 | </div>
|
|---|
| 148 | <div class="col-md-2 col-sm-6">
|
|---|
| 149 | <div class="card stat-card border-left-success">
|
|---|
| 150 | <div class="card-body">
|
|---|
| 151 | <h6>Computers</h6>
|
|---|
| 152 | <h3 id="totalComputers">0</h3>
|
|---|
| 153 | </div>
|
|---|
| 154 | </div>
|
|---|
| 155 | </div>
|
|---|
| 156 | <div class="col-md-2 col-sm-6">
|
|---|
| 157 | <div class="card stat-card border-left-info">
|
|---|
| 158 | <div class="card-body">
|
|---|
| 159 | <h6>DNS Queries</h6>
|
|---|
| 160 | <h3 id="dnsCount">0</h3>
|
|---|
| 161 | </div>
|
|---|
| 162 | </div>
|
|---|
| 163 | </div>
|
|---|
| 164 | <div class="col-md-2 col-sm-6">
|
|---|
| 165 | <div class="card stat-card border-left-warning">
|
|---|
| 166 | <div class="card-body">
|
|---|
| 167 | <h6>Processes</h6>
|
|---|
| 168 | <h3 id="processCount">0</h3>
|
|---|
| 169 | </div>
|
|---|
| 170 | </div>
|
|---|
| 171 | </div>
|
|---|
| 172 | <div class="col-md-2 col-sm-6">
|
|---|
| 173 | <div class="card stat-card border-left-danger">
|
|---|
| 174 | <div class="card-body">
|
|---|
| 175 | <h6>Network</h6>
|
|---|
| 176 | <h3 id="networkCount">0</h3>
|
|---|
| 177 | </div>
|
|---|
| 178 | </div>
|
|---|
| 179 | </div>
|
|---|
| 180 | <div class="col-md-2 col-sm-6">
|
|---|
| 181 | <div class="card stat-card border-left-secondary">
|
|---|
| 182 | <div class="card-body">
|
|---|
| 183 | <h6>Last Update</h6>
|
|---|
| 184 | <h6 id="lastUpdate">-</h6>
|
|---|
| 185 | </div>
|
|---|
| 186 | </div>
|
|---|
| 187 | </div>
|
|---|
| 188 | </div>
|
|---|
| 189 |
|
|---|
| 190 | <!-- Tabs -->
|
|---|
| 191 | <ul class="nav nav-tabs" id="myTab" role="tablist">
|
|---|
| 192 | <li class="nav-item" role="presentation">
|
|---|
| 193 | <button class="nav-link active" id="events-tab" data-bs-toggle="tab" data-bs-target="#events" type="button">All Events</button>
|
|---|
| 194 | </li>
|
|---|
| 195 | <li class="nav-item" role="presentation">
|
|---|
| 196 | <button class="nav-link" id="dns-tab" data-bs-toggle="tab" data-bs-target="#dns" type="button">DNS Queries</button>
|
|---|
| 197 | </li>
|
|---|
| 198 | <li class="nav-item" role="presentation">
|
|---|
| 199 | <button class="nav-link" id="processes-tab" data-bs-toggle="tab" data-bs-target="#processes" type="button">Processes</button>
|
|---|
| 200 | </li>
|
|---|
| 201 | <li class="nav-item" role="presentation">
|
|---|
| 202 | <button class="nav-link" id="network-tab" data-bs-toggle="tab" data-bs-target="#network" type="button">Network</button>
|
|---|
| 203 | </li>
|
|---|
| 204 | <li class="nav-item" role="presentation">
|
|---|
| 205 | <button class="nav-link" id="computers-tab" data-bs-toggle="tab" data-bs-target="#computers" type="button">Computers</button>
|
|---|
| 206 | </li>
|
|---|
| 207 | </ul>
|
|---|
| 208 |
|
|---|
| 209 | <div class="tab-content" id="myTabContent">
|
|---|
| 210 | <!-- All Events -->
|
|---|
| 211 | <div class="tab-pane fade show active" id="events" role="tabpanel">
|
|---|
| 212 | <div class="card mt-3">
|
|---|
| 213 | <div class="card-header">
|
|---|
| 214 | <h5>Recent Events</h5>
|
|---|
| 215 | </div>
|
|---|
| 216 | <div class="card-body">
|
|---|
| 217 | <div id="eventsList">Loading events...</div>
|
|---|
| 218 | </div>
|
|---|
| 219 | </div>
|
|---|
| 220 | </div>
|
|---|
| 221 |
|
|---|
| 222 | <!-- DNS -->
|
|---|
| 223 | <div class="tab-pane fade" id="dns" role="tabpanel">
|
|---|
| 224 | <div class="card mt-3">
|
|---|
| 225 | <div class="card-header">
|
|---|
| 226 | <h5>DNS Queries</h5>
|
|---|
| 227 | </div>
|
|---|
| 228 | <div class="card-body">
|
|---|
| 229 | <table class="table table-sm table-hover">
|
|---|
| 230 | <thead>
|
|---|
| 231 | <tr>
|
|---|
| 232 | <th>Time</th>
|
|---|
| 233 | <th>Computer</th>
|
|---|
| 234 | <th>Domain</th>
|
|---|
| 235 | <th>Result</th>
|
|---|
| 236 | <th>Process</th>
|
|---|
| 237 | </tr>
|
|---|
| 238 | </thead>
|
|---|
| 239 | <tbody id="dnsTable">
|
|---|
| 240 | <tr><td colspan="5">Loading...</td></tr>
|
|---|
| 241 | </tbody>
|
|---|
| 242 | </table>
|
|---|
| 243 | </div>
|
|---|
| 244 | </div>
|
|---|
| 245 | </div>
|
|---|
| 246 |
|
|---|
| 247 | <!-- Processes -->
|
|---|
| 248 | <div class="tab-pane fade" id="processes" role="tabpanel">
|
|---|
| 249 | <div class="card mt-3">
|
|---|
| 250 | <div class="card-header">
|
|---|
| 251 | <h5>Process Executions</h5>
|
|---|
| 252 | </div>
|
|---|
| 253 | <div class="card-body">
|
|---|
| 254 | <table class="table table-sm table-hover">
|
|---|
| 255 | <thead>
|
|---|
| 256 | <tr>
|
|---|
| 257 | <th>Time</th>
|
|---|
| 258 | <th>Computer</th>
|
|---|
| 259 | <th>Process</th>
|
|---|
| 260 | <th>User</th>
|
|---|
| 261 | <th>Command</th>
|
|---|
| 262 | </tr>
|
|---|
| 263 | </thead>
|
|---|
| 264 | <tbody id="processesTable">
|
|---|
| 265 | <tr><td colspan="5">Loading...</td></tr>
|
|---|
| 266 | </tbody>
|
|---|
| 267 | </table>
|
|---|
| 268 | </div>
|
|---|
| 269 | </div>
|
|---|
| 270 | </div>
|
|---|
| 271 |
|
|---|
| 272 | <!-- Network -->
|
|---|
| 273 | <div class="tab-pane fade" id="network" role="tabpanel">
|
|---|
| 274 | <div class="card mt-3">
|
|---|
| 275 | <div class="card-header">
|
|---|
| 276 | <h5>Network Connections</h5>
|
|---|
| 277 | </div>
|
|---|
| 278 | <div class="card-body">
|
|---|
| 279 | <table class="table table-sm table-hover">
|
|---|
| 280 | <thead>
|
|---|
| 281 | <tr>
|
|---|
| 282 | <th>Time</th>
|
|---|
| 283 | <th>Computer</th>
|
|---|
| 284 | <th>Process</th>
|
|---|
| 285 | <th>Destination</th>
|
|---|
| 286 | <th>Port</th>
|
|---|
| 287 | </tr>
|
|---|
| 288 | </thead>
|
|---|
| 289 | <tbody id="networkTable">
|
|---|
| 290 | <tr><td colspan="5">Loading...</td></tr>
|
|---|
| 291 | </tbody>
|
|---|
| 292 | </table>
|
|---|
| 293 | </div>
|
|---|
| 294 | </div>
|
|---|
| 295 | </div>
|
|---|
| 296 |
|
|---|
| 297 | <!-- Computers -->
|
|---|
| 298 | <div class="tab-pane fade" id="computers" role="tabpanel">
|
|---|
| 299 | <div class="card mt-3">
|
|---|
| 300 | <div class="card-header">
|
|---|
| 301 | <h5>Connected Computers</h5>
|
|---|
| 302 | </div>
|
|---|
| 303 | <div class="card-body">
|
|---|
| 304 | <table class="table table-sm table-hover">
|
|---|
| 305 | <thead>
|
|---|
| 306 | <tr>
|
|---|
| 307 | <th>Computer</th>
|
|---|
| 308 | <th>User</th>
|
|---|
| 309 | <th>IP</th>
|
|---|
| 310 | <th>Status</th>
|
|---|
| 311 | <th>OS</th>
|
|---|
| 312 | <th>Last Seen</th>
|
|---|
| 313 | </tr>
|
|---|
| 314 | </thead>
|
|---|
| 315 | <tbody id="computersTable">
|
|---|
| 316 | <tr><td colspan="6">Loading...</td></tr>
|
|---|
| 317 | </tbody>
|
|---|
| 318 | </table>
|
|---|
| 319 | </div>
|
|---|
| 320 | </div>
|
|---|
| 321 | </div>
|
|---|
| 322 | </div>
|
|---|
| 323 | </div>
|
|---|
| 324 |
|
|---|
| 325 | <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
|
|---|
| 326 | <script>
|
|---|
| 327 | $(document).ready(function() {
|
|---|
| 328 | updateTime();
|
|---|
| 329 | loadAllData();
|
|---|
| 330 | setInterval(loadAllData, 5000);
|
|---|
| 331 | setInterval(updateTime, 1000);
|
|---|
| 332 |
|
|---|
| 333 | // Tab switching
|
|---|
| 334 | $('button[data-bs-toggle="tab"]').on('click', function(e) {
|
|---|
| 335 | const tab = $(this).attr('data-bs-target');
|
|---|
| 336 | if (tab === '#dns') loadDNS();
|
|---|
| 337 | else if (tab === '#processes') loadProcesses();
|
|---|
| 338 | else if (tab === '#network') loadNetwork();
|
|---|
| 339 | else if (tab === '#computers') loadComputers();
|
|---|
| 340 | else if (tab === '#events') loadEvents();
|
|---|
| 341 | });
|
|---|
| 342 | });
|
|---|
| 343 |
|
|---|
| 344 | function updateTime() {
|
|---|
| 345 | $('#currentTime').text(new Date().toLocaleString());
|
|---|
| 346 | }
|
|---|
| 347 |
|
|---|
| 348 | function loadAllData() {
|
|---|
| 349 | loadStats();
|
|---|
| 350 | loadEvents();
|
|---|
| 351 | }
|
|---|
| 352 |
|
|---|
| 353 | function loadStats() {
|
|---|
| 354 | $.get('/api/stats', function(data) {
|
|---|
| 355 | $('#totalEvents').text(data.total_events || 0);
|
|---|
| 356 | $('#totalComputers').text(data.total_computers || 0);
|
|---|
| 357 | $('#dnsCount').text(data.dns_queries || 0);
|
|---|
| 358 | $('#processCount').text(data.process_creations || 0);
|
|---|
| 359 | $('#networkCount').text(data.network_connections || 0);
|
|---|
| 360 | $('#lastUpdate').text(new Date().toLocaleTimeString());
|
|---|
| 361 | }).fail(function() {
|
|---|
| 362 | console.log('Stats failed');
|
|---|
| 363 | });
|
|---|
| 364 | }
|
|---|
| 365 |
|
|---|
| 366 | function loadEvents() {
|
|---|
| 367 | $.get('/api/events?limit=20', function(data) {
|
|---|
| 368 | let html = '';
|
|---|
| 369 | if (data.events && data.events.length > 0) {
|
|---|
| 370 | data.events.forEach(event => {
|
|---|
| 371 | let badge = '';
|
|---|
| 372 | let text = '';
|
|---|
| 373 |
|
|---|
| 374 | if (event.event_id === 22 && event.dns_query) {
|
|---|
| 375 | badge = '<span class="badge bg-info me-2">DNS</span>';
|
|---|
| 376 | text = `<strong>${event.dns_query}</strong> → ${event.dns_results || 'No results'}<br><small>Process: ${event.dns_process || 'Unknown'}</small>`;
|
|---|
| 377 | }
|
|---|
| 378 | else if (event.event_id === 1 && event.process_name) {
|
|---|
| 379 | badge = '<span class="badge bg-success me-2">PROCESS</span>';
|
|---|
| 380 | const procName = event.process_name.split('\\\\').pop() || event.process_name;
|
|---|
| 381 | text = `<strong>${procName}</strong> | User: ${event.process_user || 'Unknown'}<br><small>${event.command_line ? event.command_line.substring(0, 80) + '...' : ''}</small>`;
|
|---|
| 382 | }
|
|---|
| 383 | else if (event.event_id === 3 && event.dest_ip) {
|
|---|
| 384 | badge = '<span class="badge bg-danger me-2">NETWORK</span>';
|
|---|
| 385 | const procName = event.process_name ? event.process_name.split('\\\\').pop() : 'Unknown';
|
|---|
| 386 | text = `<strong>${procName}</strong> → ${event.dest_ip}:${event.dest_port}`;
|
|---|
| 387 | }
|
|---|
| 388 | else {
|
|---|
| 389 | badge = `<span class="badge bg-secondary me-2">${event.event_type}</span>`;
|
|---|
| 390 | text = event.event_type;
|
|---|
| 391 | }
|
|---|
| 392 |
|
|---|
| 393 | html += `
|
|---|
| 394 | <div class="event-item mb-2 p-2 border rounded">
|
|---|
| 395 | <div class="small text-muted">${formatTime(event.timestamp)} | ${event.computer}</div>
|
|---|
| 396 | <div>${badge} ${text}</div>
|
|---|
| 397 | </div>
|
|---|
| 398 | `;
|
|---|
| 399 | });
|
|---|
| 400 | } else {
|
|---|
| 401 | html = '<div class="text-center text-muted">No events yet</div>';
|
|---|
| 402 | }
|
|---|
| 403 | $('#eventsList').html(html);
|
|---|
| 404 | }).fail(function() {
|
|---|
| 405 | $('#eventsList').html('<div class="text-danger">Failed to load events</div>');
|
|---|
| 406 | });
|
|---|
| 407 | }
|
|---|
| 408 |
|
|---|
| 409 | function loadDNS() {
|
|---|
| 410 | $.get('/api/dns', function(data) {
|
|---|
| 411 | let html = '';
|
|---|
| 412 | if (data.dns_queries && data.dns_queries.length > 0) {
|
|---|
| 413 | data.dns_queries.forEach(query => {
|
|---|
| 414 | const process = query.dns_process ? query.dns_process.split('\\\\').pop() : 'Unknown';
|
|---|
| 415 | html += `
|
|---|
| 416 | <tr>
|
|---|
| 417 | <td>${formatTime(query.timestamp)}</td>
|
|---|
| 418 | <td>${query.computer}</td>
|
|---|
| 419 | <td><strong>${query.dns_query}</strong></td>
|
|---|
| 420 | <td><small>${query.dns_results || 'N/A'}</small></td>
|
|---|
| 421 | <td>${process}</td>
|
|---|
| 422 | </tr>
|
|---|
| 423 | `;
|
|---|
| 424 | });
|
|---|
| 425 | } else {
|
|---|
| 426 | html = '<tr><td colspan="5" class="text-center text-muted">No DNS queries</td></tr>';
|
|---|
| 427 | }
|
|---|
| 428 | $('#dnsTable').html(html);
|
|---|
| 429 | });
|
|---|
| 430 | }
|
|---|
| 431 |
|
|---|
| 432 | function loadProcesses() {
|
|---|
| 433 | $.get('/api/processes', function(data) {
|
|---|
| 434 | let html = '';
|
|---|
| 435 | if (data.processes && data.processes.length > 0) {
|
|---|
| 436 | data.processes.forEach(proc => {
|
|---|
| 437 | const processName = proc.process_name ? proc.process_name.split('\\\\').pop() : 'Unknown';
|
|---|
| 438 | html += `
|
|---|
| 439 | <tr>
|
|---|
| 440 | <td>${formatTime(proc.timestamp)}</td>
|
|---|
| 441 | <td>${proc.computer}</td>
|
|---|
| 442 | <td><strong>${processName}</strong></td>
|
|---|
| 443 | <td>${proc.process_user || 'N/A'}</td>
|
|---|
| 444 | <td><small>${proc.command_line ? proc.command_line.substring(0, 80) + '...' : 'N/A'}</small></td>
|
|---|
| 445 | </tr>
|
|---|
| 446 | `;
|
|---|
| 447 | });
|
|---|
| 448 | } else {
|
|---|
| 449 | html = '<tr><td colspan="5" class="text-center text-muted">No processes</td></tr>';
|
|---|
| 450 | }
|
|---|
| 451 | $('#processesTable').html(html);
|
|---|
| 452 | });
|
|---|
| 453 | }
|
|---|
| 454 |
|
|---|
| 455 | function loadNetwork() {
|
|---|
| 456 | $.get('/api/network', function(data) {
|
|---|
| 457 | let html = '';
|
|---|
| 458 | if (data.connections && data.connections.length > 0) {
|
|---|
| 459 | data.connections.forEach(conn => {
|
|---|
| 460 | const processName = conn.process_name ? conn.process_name.split('\\\\').pop() : 'Unknown';
|
|---|
| 461 | html += `
|
|---|
| 462 | <tr>
|
|---|
| 463 | <td>${formatTime(conn.timestamp)}</td>
|
|---|
| 464 | <td>${conn.computer}</td>
|
|---|
| 465 | <td>${processName}</td>
|
|---|
| 466 | <td>${conn.dest_ip}</td>
|
|---|
| 467 | <td>${conn.dest_port}</td>
|
|---|
| 468 | </tr>
|
|---|
| 469 | `;
|
|---|
| 470 | });
|
|---|
| 471 | } else {
|
|---|
| 472 | html = '<tr><td colspan="5" class="text-center text-muted">No network connections</td></tr>';
|
|---|
| 473 | }
|
|---|
| 474 | $('#networkTable').html(html);
|
|---|
| 475 | });
|
|---|
| 476 | }
|
|---|
| 477 |
|
|---|
| 478 | function loadComputers() {
|
|---|
| 479 | $.get('/api/computers', function(data) {
|
|---|
| 480 | let html = '';
|
|---|
| 481 | if (data.computers && data.computers.length > 0) {
|
|---|
| 482 | data.computers.forEach(comp => {
|
|---|
| 483 | const statusClass = comp.status === 'online' ? 'text-success' : 'text-danger';
|
|---|
| 484 | html += `
|
|---|
| 485 | <tr>
|
|---|
| 486 | <td><strong>${comp.computer_name}</strong></td>
|
|---|
| 487 | <td>${comp.user || 'N/A'}</td>
|
|---|
| 488 | <td>${comp.ip_address || 'N/A'}</td>
|
|---|
| 489 | <td class="${statusClass}">${comp.status}</td>
|
|---|
| 490 | <td><small>${comp.os || 'N/A'}</small></td>
|
|---|
| 491 | <td>${formatTime(comp.last_seen)}</td>
|
|---|
| 492 | </tr>
|
|---|
| 493 | `;
|
|---|
| 494 | });
|
|---|
| 495 | } else {
|
|---|
| 496 | html = '<tr><td colspan="6" class="text-center text-muted">No computers</td></tr>';
|
|---|
| 497 | }
|
|---|
| 498 | $('#computersTable').html(html);
|
|---|
| 499 | });
|
|---|
| 500 | }
|
|---|
| 501 |
|
|---|
| 502 | function formatTime(timestamp) {
|
|---|
| 503 | if (!timestamp) return 'N/A';
|
|---|
| 504 | try {
|
|---|
| 505 | const date = new Date(timestamp);
|
|---|
| 506 | return date.toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'});
|
|---|
| 507 | } catch(e) {
|
|---|
| 508 | return timestamp;
|
|---|
| 509 | }
|
|---|
| 510 | }
|
|---|
| 511 | </script>
|
|---|
| 512 | </body>
|
|---|
| 513 | </html>
|
|---|
| 514 | '''
|
|---|
| 515 |
|
|---|
| 516 |
|
|---|
| 517 | # API ENDPOINTS - SIMPLE AND WORKING
|
|---|
| 518 | @app.route('/api/stats', methods=['GET'])
|
|---|
| 519 | def api_stats():
|
|---|
| 520 | """Get statistics"""
|
|---|
| 521 | conn = get_db_connection()
|
|---|
| 522 | cursor = conn.cursor()
|
|---|
| 523 |
|
|---|
| 524 | try:
|
|---|
| 525 | cursor.execute("SELECT COUNT(*) FROM sysmon_events")
|
|---|
| 526 | total_events = cursor.fetchone()[0] or 0
|
|---|
| 527 |
|
|---|
| 528 | cursor.execute("SELECT COUNT(DISTINCT computer) FROM sysmon_events")
|
|---|
| 529 | total_computers = cursor.fetchone()[0] or 0
|
|---|
| 530 |
|
|---|
| 531 | cursor.execute("SELECT COUNT(*) FROM sysmon_events WHERE dns_query != ''")
|
|---|
| 532 | dns_queries = cursor.fetchone()[0] or 0
|
|---|
| 533 |
|
|---|
| 534 | cursor.execute("SELECT COUNT(*) FROM sysmon_events WHERE event_id = 1")
|
|---|
| 535 | process_creations = cursor.fetchone()[0] or 0
|
|---|
| 536 |
|
|---|
| 537 | cursor.execute("SELECT COUNT(*) FROM sysmon_events WHERE event_id = 3")
|
|---|
| 538 | network_connections = cursor.fetchone()[0] or 0
|
|---|
| 539 |
|
|---|
| 540 | return jsonify({
|
|---|
| 541 | "total_events": total_events,
|
|---|
| 542 | "total_computers": total_computers,
|
|---|
| 543 | "dns_queries": dns_queries,
|
|---|
| 544 | "process_creations": process_creations,
|
|---|
| 545 | "network_connections": network_connections,
|
|---|
| 546 | "timestamp": datetime.now().isoformat()
|
|---|
| 547 | })
|
|---|
| 548 | except Exception as e:
|
|---|
| 549 | return jsonify({"error": str(e)}), 500
|
|---|
| 550 | finally:
|
|---|
| 551 | conn.close()
|
|---|
| 552 |
|
|---|
| 553 |
|
|---|
| 554 | @app.route('/api/events', methods=['GET'])
|
|---|
| 555 | def api_events():
|
|---|
| 556 | """Get all events"""
|
|---|
| 557 | conn = get_db_connection()
|
|---|
| 558 | cursor = conn.cursor()
|
|---|
| 559 |
|
|---|
| 560 | try:
|
|---|
| 561 | limit = request.args.get('limit', 50, type=int)
|
|---|
| 562 | cursor.execute('SELECT * FROM sysmon_events ORDER BY timestamp DESC LIMIT ?', (limit,))
|
|---|
| 563 | events = [dict(row) for row in cursor.fetchall()]
|
|---|
| 564 |
|
|---|
| 565 | return jsonify({
|
|---|
| 566 | "events": events,
|
|---|
| 567 | "count": len(events)
|
|---|
| 568 | })
|
|---|
| 569 | except Exception as e:
|
|---|
| 570 | return jsonify({"error": str(e)}), 500
|
|---|
| 571 | finally:
|
|---|
| 572 | conn.close()
|
|---|
| 573 |
|
|---|
| 574 |
|
|---|
| 575 | @app.route('/api/dns', methods=['GET'])
|
|---|
| 576 | def api_dns():
|
|---|
| 577 | """Get DNS queries"""
|
|---|
| 578 | conn = get_db_connection()
|
|---|
| 579 | cursor = conn.cursor()
|
|---|
| 580 |
|
|---|
| 581 | try:
|
|---|
| 582 | limit = request.args.get('limit', 50, type=int)
|
|---|
| 583 | cursor.execute('''
|
|---|
| 584 | SELECT timestamp, computer, dns_query, dns_results, dns_process
|
|---|
| 585 | FROM sysmon_events
|
|---|
| 586 | WHERE dns_query != ''
|
|---|
| 587 | ORDER BY timestamp DESC
|
|---|
| 588 | LIMIT ?
|
|---|
| 589 | ''', (limit,))
|
|---|
| 590 |
|
|---|
| 591 | queries = [dict(row) for row in cursor.fetchall()]
|
|---|
| 592 |
|
|---|
| 593 | return jsonify({
|
|---|
| 594 | "dns_queries": queries,
|
|---|
| 595 | "count": len(queries)
|
|---|
| 596 | })
|
|---|
| 597 | except Exception as e:
|
|---|
| 598 | return jsonify({"error": str(e)}), 500
|
|---|
| 599 | finally:
|
|---|
| 600 | conn.close()
|
|---|
| 601 |
|
|---|
| 602 |
|
|---|
| 603 | @app.route('/api/processes', methods=['GET'])
|
|---|
| 604 | def api_processes():
|
|---|
| 605 | """Get process executions"""
|
|---|
| 606 | conn = get_db_connection()
|
|---|
| 607 | cursor = conn.cursor()
|
|---|
| 608 |
|
|---|
| 609 | try:
|
|---|
| 610 | limit = request.args.get('limit', 50, type=int)
|
|---|
| 611 | cursor.execute('''
|
|---|
| 612 | SELECT timestamp, computer, process_name, command_line, process_user
|
|---|
| 613 | FROM sysmon_events
|
|---|
| 614 | WHERE event_id = 1 AND process_name != ''
|
|---|
| 615 | ORDER BY timestamp DESC
|
|---|
| 616 | LIMIT ?
|
|---|
| 617 | ''', (limit,))
|
|---|
| 618 |
|
|---|
| 619 | processes = [dict(row) for row in cursor.fetchall()]
|
|---|
| 620 |
|
|---|
| 621 | return jsonify({
|
|---|
| 622 | "processes": processes,
|
|---|
| 623 | "count": len(processes)
|
|---|
| 624 | })
|
|---|
| 625 | except Exception as e:
|
|---|
| 626 | return jsonify({"error": str(e)}), 500
|
|---|
| 627 | finally:
|
|---|
| 628 | conn.close()
|
|---|
| 629 |
|
|---|
| 630 |
|
|---|
| 631 | @app.route('/api/network', methods=['GET'])
|
|---|
| 632 | def api_network():
|
|---|
| 633 | """Get network connections"""
|
|---|
| 634 | conn = get_db_connection()
|
|---|
| 635 | cursor = conn.cursor()
|
|---|
| 636 |
|
|---|
| 637 | try:
|
|---|
| 638 | limit = request.args.get('limit', 50, type=int)
|
|---|
| 639 | cursor.execute('''
|
|---|
| 640 | SELECT timestamp, computer, process_name, dest_ip, dest_port
|
|---|
| 641 | FROM sysmon_events
|
|---|
| 642 | WHERE event_id = 3 AND dest_ip != ''
|
|---|
| 643 | ORDER BY timestamp DESC
|
|---|
| 644 | LIMIT ?
|
|---|
| 645 | ''', (limit,))
|
|---|
| 646 |
|
|---|
| 647 | connections = [dict(row) for row in cursor.fetchall()]
|
|---|
| 648 |
|
|---|
| 649 | return jsonify({
|
|---|
| 650 | "connections": connections,
|
|---|
| 651 | "count": len(connections)
|
|---|
| 652 | })
|
|---|
| 653 | except Exception as e:
|
|---|
| 654 | return jsonify({"error": str(e)}), 500
|
|---|
| 655 | finally:
|
|---|
| 656 | conn.close()
|
|---|
| 657 |
|
|---|
| 658 |
|
|---|
| 659 | @app.route('/api/computers', methods=['GET'])
|
|---|
| 660 | def api_computers():
|
|---|
| 661 | """Get computers list"""
|
|---|
| 662 | conn = get_db_connection()
|
|---|
| 663 | cursor = conn.cursor()
|
|---|
| 664 |
|
|---|
| 665 | try:
|
|---|
| 666 | cursor.execute('SELECT * FROM computers ORDER BY last_seen DESC')
|
|---|
| 667 | computers = [dict(row) for row in cursor.fetchall()]
|
|---|
| 668 |
|
|---|
| 669 | return jsonify({
|
|---|
| 670 | "computers": computers,
|
|---|
| 671 | "count": len(computers)
|
|---|
| 672 | })
|
|---|
| 673 | except Exception as e:
|
|---|
| 674 | return jsonify({"error": str(e)}), 500
|
|---|
| 675 | finally:
|
|---|
| 676 | conn.close()
|
|---|
| 677 |
|
|---|
| 678 |
|
|---|
| 679 | @app.route('/receive_data', methods=['POST'])
|
|---|
| 680 | def receive_data():
|
|---|
| 681 | """Receive data from client"""
|
|---|
| 682 | try:
|
|---|
| 683 | data = request.json
|
|---|
| 684 | if not data:
|
|---|
| 685 | return jsonify({"error": "No data"}), 400
|
|---|
| 686 |
|
|---|
| 687 | metadata = data.get("metadata", {})
|
|---|
| 688 | computer_name = metadata.get("computer", "Unknown")
|
|---|
| 689 | user = metadata.get("user", "Unknown")
|
|---|
| 690 |
|
|---|
| 691 | conn = get_db_connection()
|
|---|
| 692 | cursor = conn.cursor()
|
|---|
| 693 |
|
|---|
| 694 | events_inserted = 0
|
|---|
| 695 |
|
|---|
| 696 | # Update computer
|
|---|
| 697 | system_info = data.get("system_info", {})
|
|---|
| 698 | update_computer_status(
|
|---|
| 699 | computer_name,
|
|---|
| 700 | user,
|
|---|
| 701 | system_info.get("ip_address", "Unknown"),
|
|---|
| 702 | system_info.get("os", "Unknown")
|
|---|
| 703 | )
|
|---|
| 704 |
|
|---|
| 705 | # Save sysmon events
|
|---|
| 706 | if "sysmon_events" in data:
|
|---|
| 707 | for event in data["sysmon_events"]:
|
|---|
| 708 | try:
|
|---|
| 709 | event_data = event.get("data", {})
|
|---|
| 710 |
|
|---|
| 711 | cursor.execute('''
|
|---|
| 712 | INSERT INTO sysmon_events
|
|---|
| 713 | (event_id, event_type, timestamp, computer,
|
|---|
| 714 | process_name, command_line, process_user, parent_process,
|
|---|
| 715 | dns_query, dns_results, dns_process,
|
|---|
| 716 | source_ip, dest_ip, dest_port, file_path,
|
|---|
| 717 | raw_data, received_at)
|
|---|
| 718 | VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|---|
| 719 | ''', (
|
|---|
| 720 | event.get("event_id"),
|
|---|
| 721 | event.get("event_type"),
|
|---|
| 722 | event.get("timestamp"),
|
|---|
| 723 | event.get("computer"),
|
|---|
| 724 | event_data.get("Image", ""),
|
|---|
| 725 | event_data.get("CommandLine", ""),
|
|---|
| 726 | event_data.get("User", ""),
|
|---|
| 727 | event_data.get("ParentImage", ""),
|
|---|
| 728 | event_data.get("QueryName", ""),
|
|---|
| 729 | event_data.get("QueryResults", ""),
|
|---|
| 730 | event_data.get("Image", ""),
|
|---|
| 731 | event_data.get("SourceIp", ""),
|
|---|
| 732 | event_data.get("DestinationIp", ""),
|
|---|
| 733 | event_data.get("DestinationPort", ""),
|
|---|
| 734 | event_data.get("TargetFilename", ""),
|
|---|
| 735 | json.dumps(event_data),
|
|---|
| 736 | datetime.now().isoformat()
|
|---|
| 737 | ))
|
|---|
| 738 | events_inserted += 1
|
|---|
| 739 | except Exception as e:
|
|---|
| 740 | print(f"Error saving event: {e}")
|
|---|
| 741 | continue
|
|---|
| 742 |
|
|---|
| 743 | # Save processes
|
|---|
| 744 | if "processes" in data:
|
|---|
| 745 | for proc in data["processes"]:
|
|---|
| 746 | try:
|
|---|
| 747 | cursor.execute('''
|
|---|
| 748 | INSERT INTO processes
|
|---|
| 749 | (pid, name, user, cpu_percent, memory_mb, cmdline, computer, received_at)
|
|---|
| 750 | VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
|---|
| 751 | ''', (
|
|---|
| 752 | proc.get("pid"),
|
|---|
| 753 | proc.get("name"),
|
|---|
| 754 | proc.get("user"),
|
|---|
| 755 | proc.get("cpu_percent", 0),
|
|---|
| 756 | proc.get("memory_mb", 0),
|
|---|
| 757 | proc.get("cmdline", ""),
|
|---|
| 758 | computer_name,
|
|---|
| 759 | datetime.now().isoformat()
|
|---|
| 760 | ))
|
|---|
| 761 | except Exception as e:
|
|---|
| 762 | print(f"Error saving process: {e}")
|
|---|
| 763 | continue
|
|---|
| 764 |
|
|---|
| 765 | conn.commit()
|
|---|
| 766 | conn.close()
|
|---|
| 767 |
|
|---|
| 768 | return jsonify({
|
|---|
| 769 | "message": "Data received successfully",
|
|---|
| 770 | "events_inserted": events_inserted
|
|---|
| 771 | }), 200
|
|---|
| 772 |
|
|---|
| 773 | except Exception as e:
|
|---|
| 774 | return jsonify({"error": str(e)}), 500
|
|---|
| 775 |
|
|---|
| 776 |
|
|---|
| 777 | @app.route('/ping', methods=['GET'])
|
|---|
| 778 | def ping():
|
|---|
| 779 | """Ping endpoint"""
|
|---|
| 780 | return jsonify({
|
|---|
| 781 | "message": "pong",
|
|---|
| 782 | "status": "ok",
|
|---|
| 783 | "server": "Sysmon Server",
|
|---|
| 784 | "time": datetime.now().isoformat()
|
|---|
| 785 | })
|
|---|
| 786 |
|
|---|
| 787 |
|
|---|
| 788 | if __name__ == '__main__':
|
|---|
| 789 | # Initialize database
|
|---|
| 790 | init_database()
|
|---|
| 791 |
|
|---|
| 792 | print("\n" + "=" * 60)
|
|---|
| 793 | print("🚀 WORKING SYSMON SERVER")
|
|---|
| 794 | print("=" * 60)
|
|---|
| 795 | print("📊 Dashboard: http://localhost:5555/")
|
|---|
| 796 | print("📡 API Endpoints (ALL WORKING):")
|
|---|
| 797 | print(" - GET / - Dashboard")
|
|---|
| 798 | print(" - GET /api/stats - Statistics")
|
|---|
| 799 | print(" - GET /api/events - All events")
|
|---|
| 800 | print(" - GET /api/dns - DNS queries")
|
|---|
| 801 | print(" - GET /api/processes - Process executions")
|
|---|
| 802 | print(" - GET /api/network - Network connections")
|
|---|
| 803 | print(" - GET /api/computers - Computers list")
|
|---|
| 804 | print(" - POST /receive_data - Receive client data")
|
|---|
| 805 | print(" - GET /ping - Test endpoint")
|
|---|
| 806 | print("=" * 60)
|
|---|
| 807 |
|
|---|
| 808 | app.run(host='0.0.0.0', port=5555, debug=True) |
|---|