-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdashboard.html
More file actions
1408 lines (1186 loc) · 47.6 KB
/
dashboard.html
File metadata and controls
1408 lines (1186 loc) · 47.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!--
Copyright (c) 2025 Sentrilite, Inc. All rights reserved.
This software is the confidential and proprietary information of
Sentrilite ("Confidential Information"). You shall not
disclose such Confidential Information and shall use it only
in accordance with the terms of the license agreement you entered
into with Sentrilite.
-->
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>System Security Dashboard</title>
<script src="jspdf.umd.min.js"></script>
<script>
// Initialize jsPDF after the library loads
function initJsPDF() {
if (typeof window.jspdf !== 'undefined') {
window.jsPDF = window.jspdf.jsPDF;
console.log("✅ jsPDF initialized");
} else {
console.warn("⚠️ jsPDF library not found yet");
}
}
// Try immediately
initJsPDF();
// Also try when DOM is ready
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', initJsPDF);
} else {
initJsPDF();
}
</script>
<style>
body { font-family: 'Segoe UI', sans-serif; background: linear-gradient(#0f0f0f, #1a1a1a); color: #eee; margin: 0; display: flex; height: 100vh; overflow: hidden; }
.sidebar { width: 260px; background: #111; padding: 1em; border-right: 2px solid #333; display: flex; flex-direction: column; }
.sidebar button { margin-top: 0.5em; padding: 0.6em; border: none; background: #222; color: #ccc; cursor: pointer; border-radius: 8px; transition: background 0.2s, transform 0.2s; }
.sidebar button:hover { background: #444; transform: scale(1.02); }
.main-content { flex: 1; padding: 1em; display: flex; flex-direction: column; overflow: hidden; }
.topbar { display: flex; justify-content: space-between; align-items: center; margin-bottom: 1em; gap: 10px; }
.topbar button { padding: 0.5em 0.8em; border: none; border-radius: 6px; cursor: pointer; font-weight: 500; font-size: 0.9rem; }
.topbar .pdf-download-btn {
background: #00cc7a; /* Fallback for browsers that don't support gradient */
background: linear-gradient(90deg, #00cc7a, #0099cc);
color: #ffffff !important;
box-shadow: 0 2px 8px rgba(0, 255, 153, 0.15);
display: inline-block;
visibility: visible;
opacity: 1;
}
.topbar .pdf-download-btn:hover {
opacity: 0.9;
}
h1, h2, h3 { color: #fff; margin-top: 0; }
.counters { display: flex; gap: 0.7em; margin-bottom: 1em; }
.counters button { padding: 0.6em 1.2em; border-radius: 8px; font-weight: bold; font-size: 0.9em; border: none; cursor: pointer; transition: background 0.2s; }
.risk-high { background: #e74c3c; color: white; }
.risk-medium { background: #3378b8; color: white; } /* Medium risk is slightly darker blue for live streaming */
.risk-low { background: #2ecc71; color: black; }
.filters { display: flex; gap: 0.7em; margin-bottom: 1em; flex-wrap: wrap; }
.filters input { padding: 0.5em; font-size: 0.85em; border-radius: 6px; border: none; width: 140px; }
.alerts { margin-bottom: 1em; padding: 1em; background-color: #330000; border: 1px solid #ff4c4c; color: #ff4c4c; font-weight: bold; border-radius: 8px; transition: opacity 0.5s ease; }
.event-log { flex: 1; overflow-y: auto; background: #000; border-radius: 8px; padding: 1em; font-family: 'Courier New', Courier, monospace; white-space: pre-wrap; box-shadow: inset 0 0 5px #333; font-size: 13px; }
.hidden { display: none; }
.tag { font-size: 0.75em; background: yellow; color: black; padding: 3px 7px; border-radius: 6px; margin-left: 5px; }
input, button { font-family: inherit; }
.status { font-size: 0.85em; margin-left: 10px; }
#history-modal, #xdr-modal { background: #222; padding: 20px; border-radius: 8px; color: white; position: fixed; top: 20%; left: 50%; transform: translateX(-50%); box-shadow: 0 0 10px black; max-width: 500px; width: 90%; z-index: 999; }
</style>
</head>
<body>
<div class="sidebar">
<h3>⛨ EDR Manager</h3>
<button onclick="toggleRuleForm()">➕ Add New Rule</button>
<button onclick="refreshRuleList()">✏️ View Rules</button>
<button onclick="deleteAllRules()">🗑️ Delete All Rules</button>
<button onclick="clearEvents()">🧹 Clear Events</button>
<h3 style="margin-top: 2em;">🛡️ XDR Manager</h3>
<button onclick="toggleXdrForm()">➕ Add New Rule</button>
<button onclick="viewXdrRules()">👁️ View Rules</button>
<button onclick="deleteAllXdrRules()">🗑️ Delete All Rules</button>
<div id="rule-form" class="hidden" style="margin-top: 1em;">
<input id="match-key" placeholder="match key (e.g. cmd)"><br>
<input id="match-values" placeholder="match values (comma separated)"><br>
<input id="tags" placeholder="tags (comma separated)"><br>
<input id="risk-level" type="number" min="1" max="3" placeholder="risk level (1-3)"><br>
<button onclick="addRule()">Save Rule</button>
</div>
<div id="xdr-form" class="hidden" style="margin-top: 1em;">
<label><input type="radio" name="xdr-action" value="block" checked> Block</label>
<label><input type="radio" name="xdr-action" value="allow"> Allow</label><br><br>
<input id="xdr-ip" placeholder="IP Address (optional)"><br><br>
<input id="xdr-port" placeholder="Port or Port Range (e.g. 80 or 1000-2000)"><br><br>
<button onclick="addXdrRule()">Save Rule</button>
</div>
</div>
<div class="main-content">
<div class="topbar">
<h1>Sentrilite Live System Events Dashboard</h1>
<div>
<button id="pdf-download-btn" class="pdf-download-btn" onclick="downloadPDFReport()">📄 Download PDF Report</button>
<button id="pause-btn" onclick="togglePause()">⏸️ Pause</button>
<button id="alert-btn" onclick="toggleAlerts()">🔔 Alerts On</button>
<button onclick="showAlertHistory()">📜 Alert History</button>
<span id="status" class="status">🟢 Connected</span>
</div>
</div>
<div class="counters">
<button id="count-red" class="risk-high" onclick="setFilterByRisk(1)">High Risk: 0</button>
<button id="count-orange" class="risk-medium" onclick="setFilterByRisk(2)">Medium: 0</button>
<button id="count-green" class="risk-low" onclick="setFilterByRisk(3)">Low: 0</button>
</div>
<div class="filters">
<input type="text" id="filter-uid" placeholder="Filter UID/username" oninput="renderEvents()">
<input type="text" id="filter-ip" placeholder="Filter IP" oninput="renderEvents()">
<input type="text" id="filter-cmd" placeholder="Filter CMD" oninput="renderEvents()">
<input type="text" id="filter-tag" placeholder="Filter TAG" oninput="renderEvents()">
</div>
<div id="alerts" class="alerts hidden"></div>
<h2>Live Events</h2>
<div id="event-log" class="event-log"></div>
<!-- Modal for past alerts -->
<div id="history-modal" class="hidden">
<h3>📜 Past Alerts</h3>
<div id="history-content" style="max-height: 300px; overflow-y: auto; margin-top: 10px;"></div>
<button onclick="clearAlertHistory()">🗑️ Clear History</button>
<button onclick="downloadAlertHistory()">⬇️ Download JSON</button>
<button onclick="hideAlertHistory()">❌ Close</button>
</div>
<!-- Modal for XDR Rules -->
<div id="xdr-modal" class="hidden">
<h3>🛡️ XDR Rules</h3>
<div id="xdr-content" style="max-height: 300px; overflow-y: auto; margin-top: 10px;"></div>
<button onclick="hideXdrRules()">❌ Close</button>
</div>
</div>
<script>
let paused = false;
let alertsEnabled = true;
let events = [];
let alertHistory = [];
let allAlertsFromFile = []; // All alerts loaded from alerts.json
let currentRiskFilter = null;
let ws;
function getWebSocketHost() {
// When dashboard.html is opened via file://, hostname is empty → fallback to localhost
if (window.location.hostname && window.location.hostname.length > 0) {
return window.location.hostname;
}
return "localhost";
}
function connectWebSocket() {
const host = getWebSocketHost();
const url = `ws://${host}:8765`;
console.log("Connecting to WebSocket:", url);
ws = new WebSocket(url);
ws.onopen = () => {
console.log("✅ WebSocket connected");
document.getElementById("status").textContent = "🟢 Connected";
document.getElementById("status").style.color = "#2ecc71";
};
ws.onmessage = event => {
if (paused) return;
const data = JSON.parse(event.data);
if (data.type === "rule_list") { updateRuleList(data.rules); return; }
if (data.type === "xdr_rule_list") {
updateXdrRuleList(data.rules);
return;
}
// ⛔️ Skip any non-event messages
if (data.type && ["clear_alerts", "clear_alerts_ack", "rule_list", "xdr_rule_list", "health"].includes(data.type)) return;
events.push(data);
renderEvents();
maybeShowAlert(data);
};
ws.onclose = () => {
document.getElementById("status").textContent = "🔴 Disconnected";
document.getElementById("status").style.color = "#e74c3c";
setTimeout(connectWebSocket, 3000);
};
ws.onerror = (e) => {
console.error("WebSocket error:", e);
ws.close();
}
}
connectWebSocket();
// Load alerts from alerts.json on page load to update counters
async function loadAlertsOnPageLoad() {
const alertsFromFile = await loadAlertsFromJSON();
// Convert alerts.json format to our alert format
alertsFromFile.forEach(alert => {
let riskLevel = alert.risk_level || alert.riskLevel || alert.severity || 0;
if (typeof riskLevel === 'string') {
riskLevel = parseInt(riskLevel, 10) || 0;
}
allAlertsFromFile.push({
risk_level: riskLevel,
time: alert.time || alert.timestamp || new Date().toISOString(),
message: alert.message || alert.Message || alert.cmd || alert.comm || "Alert"
});
});
// Update counters with all alerts
updateCounters();
console.log(`✅ Loaded ${allAlertsFromFile.length} alerts from alerts.json on page load`);
}
// Load alerts when page loads
loadAlertsOnPageLoad();
function togglePause() {
paused = !paused;
document.getElementById("pause-btn").textContent = paused ? "▶️ Resume" : "⏸️ Pause";
}
function toggleAlerts() {
alertsEnabled = !alertsEnabled;
document.getElementById("alert-btn").textContent = alertsEnabled ? "🔔 Alerts On" : "🔕 Alerts Off";
}
function updateCounters() {
// Count from all alerts in alerts.json
let red = 0, orange = 0, green = 0;
allAlertsFromFile.forEach(alert => {
const risk = normalizeRiskLevel(alert);
if (risk === 1) red++;
else if (risk === 2) orange++;
else if (risk === 3) green++;
});
// Also count from streamed events
events.forEach(data => {
if (data.risk_level === 1) red++;
else if (data.risk_level === 2) orange++;
else if (data.risk_level === 3) green++;
});
document.getElementById("count-red").textContent = `High Risk: ${red}`;
document.getElementById("count-orange").textContent = `Medium: ${orange}`;
document.getElementById("count-green").textContent = `Low: ${green}`;
}
// Format timestamps for live log display: yyyy-mm-dd hh:mm:ss (local time)
function formatLogTime(ms) {
const date = new Date(ms);
const yyyy = date.getFullYear();
const MM = String(date.getMonth() + 1).padStart(2, "0");
const dd = String(date.getDate()).padStart(2, "0");
const hh = String(date.getHours()).padStart(2, "0");
const mm = String(date.getMinutes()).padStart(2, "0");
const ss = String(date.getSeconds()).padStart(2, "0");
return `${yyyy}-${MM}-${dd} ${hh}:${mm}:${ss}`;
}
function renderEvents() {
const log = document.getElementById("event-log");
log.innerHTML = "";
let red = 0, orange = 0, green = 0;
for (const data of events) {
if (!shouldDisplay(data)) continue;
// Use event timestamp when present; otherwise fall back to current time.
let tsMs;
if (data.timestamp) {
const t = data.timestamp;
// Support seconds or milliseconds
tsMs = t < 946684800000 ? t * 1000 : t;
} else {
tsMs = Date.now();
}
const ts = formatLogTime(tsMs);
const tags = (data.tags || []).join(", ");
const tagsDisplay = tags ? ` [${tags}]` : "";
const portPart = data.port ? ` PORT=${data.port}` : "";
// NEW: read K8s enrichment keys from payload (underscore JSON keys)
const ns = data.k8s_namespace || "";
const pod = data.k8s_pod || "";
const ctr = data.k8s_container || "";
const uid = data.k8s_pod_uid || "";
const k8sPart = (ns || pod || ctr || uid)
? ` [k8s ns=${ns || "-"} pod=${pod || "-"} ctr=${ctr || "-"} uid=${uid ? uid.slice(0,12) + "…" : "-"}]`
: "";
let cmd = data.display_cmd || data.cmd || "";
let arg = data.arg1 || "";
// Insert k8sPart right after COMM for easy scanning
let line = `[${ts}] PID=${data.pid} UID=${data.uid} USER=${data.user || ""} COMM=${data.comm}${k8sPart}`;
if (cmd) line += ` CMD=${cmd}`;
if (arg) line += ` ARG=${arg}`;
line += ` IP=${data.ip || "localhost"} TYPE=${data.msg_type_str}${portPart}${tagsDisplay}`;
if (data._ && data._ !== "ok") {
line += ` Reason: ${data._}`; // show the real error reason
}
const div = document.createElement("div");
div.textContent = line;
div.className = data.risk_level === 1 ? "risk-high"
: (data.risk_level === 2 ? "risk-medium" : "risk-low");
log.appendChild(div);
if (data.risk_level === 1) red++;
else if (data.risk_level === 2) orange++;
else green++;
}
// Update counters (includes alerts from file)
updateCounters();
log.scrollTop = log.scrollHeight;
}
function maybeShowAlert(data) {
if (!alertsEnabled) return;
const alerts = document.getElementById("alerts");
let message = "";
const ipPart = data.ip ? `, IP=${data.ip}` : "";
const portPart = data.port !== undefined ? `, PORT=${data.port}` : "";
const cmdPart = data.cmd ? `, CMD=${data.cmd}` : "";
const pidPart = data.pid !== undefined ? `PID=${data.pid}` : "";
if (data.tags?.includes("intruder") && data.msg_type_str === "ACCEPT") {
message = `🚨 ALERT: Intruder connected${ipPart}${portPart}`;
} else if (data.tags?.includes("intruder") && data.tags?.includes("info-disclosure")) {
message = `🚨 ALERT: Intruder accessed sensitive file! ${pidPart}${cmdPart}${ipPart}${portPart}`;
} else if (data.tags?.includes("exfiltration")) {
message = `🚨 ALERT: Possible data exfiltration! ${pidPart}${cmdPart}${ipPart}${portPart}`;
} else if (data.tags?.includes("unexpected-service")) {
message = `🚨 ALERT: Unexpected service opened! ${pidPart}${cmdPart}${ipPart}${portPart}`;
}
if (message) {
alerts.textContent = message;
alerts.classList.remove("hidden");
alertHistory.push({ time: new Date().toISOString(), message });
setTimeout(() => { alerts.classList.add("hidden"); }, 3000);
}
}
async function showAlertHistory() {
const modal = document.getElementById("history-modal");
const content = document.getElementById("history-content");
content.innerHTML = "Loading alerts...";
modal.classList.remove("hidden");
// Load all alerts from alerts.json
const alertsFromFile = await loadAlertsFromJSON();
// Convert to alert format and filter high risk
const allAlerts = [];
alertsFromFile.forEach(alert => {
let riskLevel = alert.risk_level || alert.riskLevel || alert.severity || 0;
if (typeof riskLevel === 'string') {
riskLevel = parseInt(riskLevel, 10) || 0;
}
// Only include high risk (risk level 1)
if (riskLevel === 1) {
const time = alert.time || alert.timestamp || new Date().toISOString();
const message = alert.message || alert.Message || alert.cmd || alert.comm || "Alert";
allAlerts.push({ time, message, risk_level: riskLevel });
}
});
// Sort by time (most recent first) and take top 50
allAlerts.sort((a, b) => {
const timeA = new Date(a.time).getTime();
const timeB = new Date(b.time).getTime();
return timeB - timeA; // Descending order
});
const top50 = allAlerts.slice(0, 50);
if (top50.length === 0) {
content.innerHTML = "No high-risk alerts found.";
} else {
content.innerHTML = `<h4 style="margin-top: 0; margin-bottom: 10px; color: #fff;">Top 50 High Risk Alerts</h4>` +
top50.map(a => `[${a.time}] ${a.message}`).join("<br>");
}
}
function hideAlertHistory() {
document.getElementById("history-modal").classList.add("hidden");
}
function clearAlertHistory() {
alertHistory = [];
document.getElementById("history-content").innerHTML = "";
// Send request to server to clear alerts.json
ws.send(JSON.stringify({ type: "clear_alerts" }));
}
function downloadAlertHistory() {
const blob = new Blob([JSON.stringify(alertHistory, null, 2)], { type: "application/json" });
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = "alert_history.json";
a.click();
URL.revokeObjectURL(url);
}
function shouldDisplay(data) {
if (currentRiskFilter && data.risk_level !== currentRiskFilter) return false;
const uidInput = document.getElementById("filter-uid").value.trim();
if (uidInput && !(data.uid?.toString().includes(uidInput) || (data.user || "").includes(uidInput))) return false;
if (filter("ip", data.ip)) return false;
if (filter("cmd", data.cmd)) return false;
if (filter("tag", data.tags)) return false;
return true;
}
function filter(type, value) {
const input = document.getElementById(`filter-${type}`).value;
if (!input) return false;
if (type === "tag") return !(value || []).includes(input);
return !(value || "").toString().includes(input);
}
function setFilterByRisk(level) {
currentRiskFilter = currentRiskFilter === level ? null : level;
renderEvents();
}
function toggleRuleForm() { document.getElementById("rule-form").classList.toggle("hidden"); }
function toggleXdrForm() { document.getElementById("xdr-form").classList.toggle("hidden"); }
function clearEvents() { events = []; renderEvents(); }
function updateRuleList(rules) {
if (!rules.length) return alert("ℹ️ No rules defined.");
const list = rules.map((r, i) => `${i+1}. Match ${r.match_key} IN [${r.match_values.join(", ")}], Tags: [${r.tags.join(", ")}], Risk: ${r.risk_level}`).join("\n");
alert("📜 Current Rules:\n\n" + list);
}
function refreshRuleList() { ws.send(JSON.stringify({ type: "get_rules" })); }
function addRule() {
const matchKey = document.getElementById("match-key").value.trim();
const matchValues = document.getElementById("match-values").value.split(",").map(v => v.trim()).filter(v => v);
const tags = document.getElementById("tags").value.split(",").map(v => v.trim()).filter(v => v);
const riskLevel = parseInt(document.getElementById("risk-level").value);
// Validation
if (!matchKey) {
alert("❌ Match key cannot be empty. Example: cmd, comm, arg1, ip");
return;
}
if (!matchValues.length) {
alert("❌ You must provide at least one match value.");
return;
}
if (![1, 2, 3].includes(riskLevel)) {
alert("❌ Risk level must be 1, 2, or 3.");
return;
}
const rule = {
type: "add_rule",
match_key: matchKey,
match_values: matchValues,
tags: tags,
risk_level: riskLevel
};
ws.send(JSON.stringify(rule));
alert("✅ Rule saved!");
refreshRuleList();
toggleRuleForm();
}
function deleteAllRules() { ws.send(JSON.stringify({ type: "delete_all_rules" })); refreshRuleList(); }
function addXdrRule() {
const action = document.querySelector('input[name="xdr-action"]:checked').value; // "block" or "allow"
const ip = document.getElementById("xdr-ip").value.trim();
const port = document.getElementById("xdr-port").value.trim();
if (!ip && !port) {
alert("❌ Please specify at least an IP or a Port.");
return;
}
const value = { ip, port };
const newRule = {
type: "add_xdr_rule",
rule_type: action, // <-- just "block" or "allow"
value: value
};
ws.send(JSON.stringify(newRule));
alert("✅ XDR Rule saved successfully!");
document.getElementById("xdr-form").classList.add("hidden");
}
function deleteAllXdrRules() {
if (!confirm("⚠️ Are you sure you want to delete all XDR rules?")) return;
ws.send(JSON.stringify({ type: "clear_xdr_rules" }));
alert("✅ All XDR rules cleared!");
}
function viewXdrRules() {
ws.send(JSON.stringify({ type: "get_xdr_rules" }));
}
function updateXdrRuleList(rules) {
if (!rules.length) {
alert("ℹ️ No XDR rules defined.");
return;
}
const list = rules.map((r, i) => {
const action = r.type === "block" ? "Block" : (r.type === "allow" ? "Allow" : "Unknown");
const ip = r.value?.ip || "Any IP";
const port = r.value?.port || "Any Port";
return `${i + 1}. [${action}] IP: ${ip}, Port: ${port}`;
}).join("\n");
alert("🛡️ Current XDR Rules:\n\n" + list);
}
// PDF Report Generation Functions
function normalizeRiskLevel(alert) {
let v = alert.risk_level ?? alert.RiskLevel ?? alert.severity;
if (typeof v === "number") return v;
if (typeof v === "string") {
const n = parseInt(v, 10);
if (!isNaN(n)) return n;
const s = v.toLowerCase();
if (s === "critical" || s === "high") return 1;
if (s === "medium") return 2;
if (s === "low") return 3;
}
return 0;
}
function getRiskRGB(level) {
const r = normalizeRiskLevel({ risk_level: level });
if (r === 1) return [231, 76, 60]; // 🔴 High - Red
if (r === 2) return [59, 143, 207]; // 🔵 Medium - slightly darker Blue
if (r === 3) return [0, 128, 0]; // 🟢 Low - Dark Green (more visible in Firefox)
return [80, 80, 80]; // ⚫ Other/unknown - Gray
}
function computeAlertMetrics(alerts) {
const riskCounts = { 1: 0, 2: 0, 3: 0, other: 0 };
const ipCounts = {};
const procCounts = {};
const tagCounts = {};
alerts.forEach(a => {
const risk = normalizeRiskLevel(a);
if (risk === 1 || risk === 2 || risk === 3) {
riskCounts[risk]++;
} else {
riskCounts.other++;
}
const ip = a.ip || a.IP || "";
if (ip && ip !== "127.0.0.1" && ip !== "localhost") {
ipCounts[ip] = (ipCounts[ip] || 0) + 1;
}
const cmd = a.cmd || a.Comm || a.comm || a.message || a.msg || "";
if (cmd) {
const key = cmd.length > 80 ? cmd.slice(0, 77) + "..." : cmd;
procCounts[key] = (procCounts[key] || 0) + 1;
}
const tags = Array.isArray(a.tags) ? a.tags : [];
tags.forEach(t => {
if (!t || typeof t !== "string") return;
const tag = t.trim();
if (!tag || tag.toLowerCase() === "linux") return;
if (tag.startsWith("host:")) return;
if (tag.startsWith("count:")) return;
tagCounts[tag] = (tagCounts[tag] || 0) + 1;
});
});
const topTags = Object.entries(tagCounts)
.filter(([k, c]) => k && c >= 1)
.sort((a, b) => b[1] - a[1])
.slice(0, 10);
const topProcesses = Object.entries(procCounts)
.filter(([k, c]) => k && c >= 5)
.sort((a, b) => b[1] - a[1])
.slice(0, 5);
const topIPs = Object.entries(ipCounts)
.filter(([k, c]) => k && c >= 5)
.sort((a, b) => b[1] - a[1])
.slice(0, 5);
return {
riskCounts,
ipCounts,
procCounts,
tagCounts,
topTags,
topProcesses,
topIPs
};
}
function createPieChartDataURL(riskCounts) {
const total = (riskCounts[1] || 0) + (riskCounts[2] || 0) + (riskCounts[3] || 0);
if (total === 0) return null;
const canvas = document.createElement("canvas");
canvas.width = 200;
canvas.height = 200;
const ctx = canvas.getContext("2d");
const cx = 100;
const cy = 100;
const r = 80;
const segments = [
{ value: riskCounts[1] || 0, color: "#e74c3c" }, // High - red
{ value: riskCounts[2] || 0, color: "#3b8fcf" }, // Medium - slightly darker blue
{ value: riskCounts[3] || 0, color: "#27ae60" } // Low - green
];
let startAngle = -Math.PI / 2;
segments.forEach(seg => {
if (seg.value <= 0) return;
const angle = (seg.value / total) * Math.PI * 2;
const endAngle = startAngle + angle;
ctx.beginPath();
ctx.moveTo(cx, cy);
ctx.arc(cx, cy, r, startAngle, endAngle);
ctx.closePath();
ctx.fillStyle = seg.color;
ctx.fill();
startAngle = endAngle;
});
ctx.beginPath();
ctx.arc(cx, cy, r, 0, Math.PI * 2);
ctx.strokeStyle = "#ffffff";
ctx.lineWidth = 2;
ctx.stroke();
return canvas.toDataURL("image/png");
}
function createTimeseriesHistogramDataURL(alerts) {
if (!alerts || alerts.length === 0) return null;
// Parse timestamps and extract valid events with timestamps
const events = [];
alerts.forEach(alert => {
let timestamp;
if (alert.timestamp) {
timestamp = typeof alert.timestamp === 'number'
? (alert.timestamp < 946684800000 ? alert.timestamp * 1000 : alert.timestamp)
: new Date(alert.timestamp).getTime();
} else if (alert.time) {
timestamp = new Date(alert.time).getTime();
} else {
return; // Skip alerts without timestamp
}
if (isNaN(timestamp)) return;
const risk = normalizeRiskLevel(alert);
events.push({ timestamp, risk });
});
if (events.length === 0) return null;
// Sort events by timestamp
events.sort((a, b) => a.timestamp - b.timestamp);
// Determine time window: use full range from first to last event
const latestTime = events[events.length - 1].timestamp;
const earliestTime = events[0].timestamp;
const timeRange = latestTime - earliestTime;
// Use full range
const windowStart = earliestTime;
const windowEnd = latestTime;
// Create 1-hour time buckets
const oneHour = 60 * 60 * 1000; // 1 hour in milliseconds
const buckets = {};
events.forEach(event => {
// Round down to nearest hour
const bucketTime = Math.floor(event.timestamp / oneHour) * oneHour;
const bucketKey = bucketTime.toString();
if (!buckets[bucketKey]) {
buckets[bucketKey] = { time: bucketTime, risk1: 0, risk2: 0, risk3: 0 };
}
// Count events by risk level in this 1-hour window
if (event.risk === 1) buckets[bucketKey].risk1++;
else if (event.risk === 2) buckets[bucketKey].risk2++;
else if (event.risk === 3) buckets[bucketKey].risk3++;
});
const sortedBuckets = Object.values(buckets).sort((a, b) => a.time - b.time);
if (sortedBuckets.length === 0) return null;
// Find max count for scaling (across all risk levels)
let maxCount = 0;
sortedBuckets.forEach(b => {
const maxInBucket = Math.max(b.risk1, b.risk2, b.risk3);
if (maxInBucket > maxCount) maxCount = maxInBucket;
});
if (maxCount === 0) return null;
// Create canvas with more space
const canvas = document.createElement("canvas");
canvas.width = 250;
canvas.height = 200;
const ctx = canvas.getContext("2d");
const padding = 35;
const chartWidth = canvas.width - padding * 2;
const chartHeight = canvas.height - padding * 2;
const chartBottom = canvas.height - padding;
const chartTop = padding;
const barSpacing = chartWidth / sortedBuckets.length;
const maxBarWidth = 7; // Maximum 0.1 inch in pixels
const barWidth = Math.min(maxBarWidth, barSpacing * 0.6); // Use smaller of max width or 60% spacing
// Draw axes
ctx.strokeStyle = "#333";
ctx.lineWidth = 1;
ctx.beginPath();
ctx.moveTo(padding, chartTop);
ctx.lineTo(padding, chartBottom);
ctx.lineTo(canvas.width - padding, chartBottom);
ctx.stroke();
// Draw separate bars for each risk level in each 1-hour time bucket
// Each bar's height represents the count of events in that 1-hour window
sortedBuckets.forEach((bucket, index) => {
const baseX = padding + (index * barSpacing) + (barSpacing / 2);
const singleBarWidth = barWidth / 3; // Divide width among 3 risk levels
const barGap = 0.5; // Small gap between bars
// Draw risk 1 (high) bar - left position, height = count
if (bucket.risk1 > 0) {
const height = (bucket.risk1 / maxCount) * chartHeight;
const x = baseX - singleBarWidth - barGap;
ctx.fillStyle = "#e74c3c";
ctx.fillRect(x, chartBottom - height, singleBarWidth, height);
}
// Draw risk 2 (medium) bar - center position, height = count
if (bucket.risk2 > 0) {
const height = (bucket.risk2 / maxCount) * chartHeight;
const x = baseX - (singleBarWidth / 2);
ctx.fillStyle = "#3b8fcf"; // Medium - slightly darker blue
ctx.fillRect(x, chartBottom - height, singleBarWidth, height);
}
// Draw risk 3 (low) bar - right position, height = count
if (bucket.risk3 > 0) {
const height = (bucket.risk3 / maxCount) * chartHeight;
const x = baseX + barGap;
ctx.fillStyle = "#27ae60";
ctx.fillRect(x, chartBottom - height, singleBarWidth, height);
}
});
// Format timestamps for display with date and time
const formatTime = (timestamp) => {
const date = new Date(timestamp);
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
const year = String(date.getFullYear()).slice(-2);
const hours = String(date.getHours()).padStart(2, '0');
const minutes = String(date.getMinutes()).padStart(2, '0');
return `${month}-${day}-${year} ${hours}:${minutes}`;
};
// Draw x-axis label "Time" just below the X-axis for clarity (avoid overlap)
ctx.fillStyle = "#333";
ctx.font = "10px Arial";
ctx.textAlign = "center";
ctx.fillText("Time", Math.round(canvas.width / 2), chartBottom + 20);
// Draw start and end time labels with date, slightly below the X-axis
ctx.font = "8px Arial";
ctx.textAlign = "left";
ctx.fillText(formatTime(windowStart), padding, chartBottom + 12);
ctx.textAlign = "right";
ctx.fillText(formatTime(windowEnd), canvas.width - padding, chartBottom + 12);
// Y-axis label "Alerts" – move slightly left of axis and increase size to reduce blur
ctx.save();
ctx.translate(padding - 22, Math.round((chartTop + chartBottom) / 2));
ctx.rotate(-Math.PI / 2);
ctx.textAlign = "center";
ctx.font = "bold 10px Arial";
ctx.fillText("Alerts", 0, 0);
ctx.restore();
return canvas.toDataURL("image/png");
}
function buildSummaryPage(doc, alerts, metrics, generatedAt) {
const totalAlerts = alerts.length;
const { riskCounts, topTags, topProcesses, topIPs } = metrics;
doc.setFontSize(18);
doc.setFont(undefined, "bold");
doc.setTextColor(0, 0, 0);
doc.text("Sentrilite Alert Report", 20, 20);
// Get machine FQDN/IP address
const hostname = window.location.hostname || "localhost";
const hostInfo = hostname === "localhost" || hostname === "" ? "localhost" : hostname;
doc.setFontSize(11);
doc.setFont(undefined, "bold");
doc.setTextColor(60, 60, 60);
doc.text(`Machine: ${hostInfo}`, 20, 26);
doc.setFontSize(10);
doc.setFont(undefined, "bold");
doc.setTextColor(60, 60, 60);
doc.text(`Generated at: ${generatedAt}`, 20, 30);
doc.line(20, 32, 190, 32);
// Charts row: Pie chart on left, Timeseries histogram on right
doc.setFontSize(12);
doc.setFont(undefined, "bold");
doc.setTextColor(20, 20, 20);
doc.text("Alerts Risk Distribution", 20, 40);
// Event Timeline with dates
const timeseriesDataURL = createTimeseriesHistogramDataURL(alerts);
let timelineTitle = "Event Timeline";
if (timeseriesDataURL && alerts.length > 0) {
const events = [];
alerts.forEach(alert => {
let timestamp;
if (alert.timestamp) {
timestamp = typeof alert.timestamp === 'number'
? (alert.timestamp < 946684800000 ? alert.timestamp * 1000 : alert.timestamp)
: new Date(alert.timestamp).getTime();
} else if (alert.time) {
timestamp = new Date(alert.time).getTime();
}
if (timestamp && !isNaN(timestamp)) events.push(timestamp);
});
if (events.length > 0) {
events.sort((a, b) => a - b);
const startDate = new Date(events[0]);
const endDate = new Date(events[events.length - 1]);
const formatDate = (d) => {
const month = String(d.getMonth() + 1).padStart(2, '0');
const day = String(d.getDate()).padStart(2, '0');
const year = String(d.getFullYear()).slice(-2);
return `${month}-${day}-${year}`;
};
timelineTitle = `Event Timeline (${formatDate(startDate)} to ${formatDate(endDate)})`;
}
}
// Render timeline title in bold for emphasis
doc.setFont(undefined, "bold");
doc.text(timelineTitle, 100, 40);
// Timeseries histogram position (X-axis at y=110)
const timeseriesY = 45; // Start below title
const timeseriesHeight = 70;
const timeseriesXAxisY = timeseriesY + timeseriesHeight; // X-axis position
if (timeseriesDataURL) {
// Use more space for timeseries: start earlier and make wider
doc.addImage(timeseriesDataURL, "PNG", 85, timeseriesY, 105, timeseriesHeight);
}
// Pie chart: align base with X-axis of timeseries (X-axis is at timeseriesXAxisY)
const pieDataURL = createPieChartDataURL(riskCounts);
if (pieDataURL) {
// Make pie chart slightly bigger: increase from 56 to 65
const pieHeight = 65;
// Starting from previous position (0.1 inch up, 0.2 inch left),
// move 0.1 inch right and 0.1 inch down (~7.2 points each).
const pieY = timeseriesXAxisY - pieHeight; // back to align with X-axis
const pieX = 20 - 14.4 + 7.2; // net 0.1 inch left from original
doc.addImage(pieDataURL, "PNG", pieX, pieY, 65, pieHeight);
}
// Legend and Breakdown row: Below pie chart, moved 0.5 inch (14.17 points) down
const legendX = 20;
let legendY = 115 + 14.17; // 0.5 inch = 14.17 points
doc.setFontSize(11.4); // ~10% bigger than 10.35
doc.setTextColor(20, 20, 20);
doc.setFont(undefined, "bold");
doc.text("Risk Color Legend", legendX, legendY);
legendY += 8;
doc.setFillColor(231, 76, 60);
doc.rect(legendX, legendY - 4, 4, 4, "F");
doc.setTextColor(40, 40, 40);
doc.setFont("Courier New", "normal");
doc.text("Critical / High risk", legendX + 6, legendY);
legendY += 5;
doc.setFillColor(59, 143, 207);
doc.rect(legendX, legendY - 4, 4, 4, "F");
doc.setFont("Courier New", "normal");
doc.text("Medium risk", legendX + 6, legendY);
legendY += 8;
// Alert Breakdown further to the right, moved 0.5 inch down
const breakdownX = 120;
let breakdownY = 115 + 14.17; // 0.5 inch = 14.17 points
const highCount = riskCounts[1] || 0;
const mediumCount = riskCounts[2] || 0;
const lowCount = riskCounts[3] || 0;
const otherCount = riskCounts.other || 0;
const totalCount = highCount + mediumCount + lowCount + otherCount;
doc.setFontSize(12.65); // ~10% bigger than 11.5
doc.setTextColor(20, 20, 20);
doc.setFont(undefined, "bold");
doc.text("Alert Breakdown", breakdownX, breakdownY);
breakdownY += 6;
doc.setFontSize(9);
doc.setTextColor(40, 40, 40);
doc.setFont("Courier New", "normal");
doc.text(`High Risk: ${highCount}`, breakdownX, breakdownY); breakdownY += 5;
doc.setFont("Courier New", "normal");
doc.text(`Medium Risk: ${mediumCount}`, breakdownX, breakdownY); breakdownY += 5;
doc.setFont("Courier New", "normal");
doc.text(`Low Risk: ${lowCount}`, breakdownX, breakdownY); breakdownY += 5;
if (otherCount > 0) {
doc.setFont("Courier New", "normal");
doc.text(`Other: ${otherCount}`, breakdownX, breakdownY);
breakdownY += 5;
}
doc.setFont("Courier New", "normal");
doc.text(`Total: ${totalCount}`, breakdownX, breakdownY);
// Tags Summary and Top Processes below Alert Breakdown (with proper spacing)
// breakdownY already points to the end of Alert Breakdown (after "Total" line)
// Move this block DOWN by 0.25 inch (~18 points) relative to the current position
let tagsY = breakdownY + 8 + 18;
// Cap at reasonable position to stay on page 1 (A4 page height is ~280 points)
if (tagsY > 200) {
tagsY = 200; // Cap at safe position to stay on page 1
}
// Store the starting Y for Top Processes (same as Tags Summary start)
let procsX = 100;
let procsY = tagsY; // Start at same Y as Tags Summary
doc.setFontSize(12.1); // ~10% bigger than 11
doc.setTextColor(20, 20, 20);
doc.setFont(undefined, "bold");
doc.text("Tags Summary (top 10):", 20, tagsY);
tagsY += 6;