-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.ts
More file actions
484 lines (455 loc) · 14.5 KB
/
server.ts
File metadata and controls
484 lines (455 loc) · 14.5 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
import express from "express";
import path from "path";
import dotenv from "dotenv";
import { createServer as createViteServer } from "vite";
import { GoogleGenAI } from "@google/genai";
dotenv.config();
const app = express();
app.use(express.json());
const PORT = 3000;
// Initialize Gemini Client
let ai: GoogleGenAI | null = null;
if (process.env.GEMINI_API_KEY) {
ai = new GoogleGenAI({
apiKey: process.env.GEMINI_API_KEY,
httpOptions: {
headers: {
'User-Agent': 'aistudio-build',
},
},
});
}
// In-memory Database of Alerts
interface Alert {
id: string;
timestamp: string;
source: "ebpf" | "rules" | "stats";
type: "CryptoMining" | "DataExfiltration" | "ModelTheft" | "ReverseShell" | "PrivilegeEscalation" | "Anomaly";
severity: "Low" | "Medium" | "High" | "Critical";
pid: number;
comm: string;
containerId: string;
podName: string;
namespace: string;
description: string;
details: Record<string, any>;
status: "active" | "mitigated" | "acknowledged";
score: number;
}
// Generate some historical alerts distributed over the last 24 hours
const initialAlerts: Alert[] = [
{
id: "alert-101",
timestamp: new Date(Date.now() - 22 * 60 * 60 * 1000).toISOString(), // 22h ago
source: "rules",
type: "ModelTheft",
severity: "Critical",
pid: 18451,
comm: "python3",
containerId: "cgroup-ml-training-t01",
podName: "pytorch-dist-trainer-0",
namespace: "ml-training",
description: "Unauthorized UID reader (10099) attempted to read compiled PyTorch weights file: /opt/ml/models/llama3_70b.safetensors",
details: {
call: "do_sys_openat2",
path: "/opt/ml/models/llama3_70b.safetensors",
uid: 10099,
gid: 10099,
flags: "O_RDONLY",
verdict: "BlockAccess"
},
status: "mitigated",
score: 96
},
{
id: "alert-102",
timestamp: new Date(Date.now() - 18 * 60 * 1000 * 60).toISOString(), // 18h ago
source: "ebpf",
type: "CryptoMining",
severity: "Critical",
pid: 19202,
comm: "xmrig-cuda",
containerId: "cgroup-ml-infer-i02",
podName: "llama-serve-7b-689b",
namespace: "ml-inference",
description: "Cryptomining core detected on NVIDIA device ioctl write queues executing context manipulation hashes",
details: {
pci_bus: "0000:03:00.0",
ioctl_code: "0x2412",
kernel_address: "0xffffffff81a9bc0",
nvidia_sub_cmd: 99,
verdict: "KillProcess"
},
status: "active",
score: 98
},
{
id: "alert-103",
timestamp: new Date(Date.now() - 14 * 60 * 1000 * 60).toISOString(), // 14h ago
source: "ebpf",
type: "DataExfiltration",
severity: "High",
pid: 21102,
comm: "curl",
containerId: "cgroup-kubeflow-k01",
podName: "jupyter-notebook-user1",
namespace: "kubeflow",
description: "Model weights egress exfiltration suspected. High outbound network payload (580MB) matching illegal external subnet IP destinations",
details: {
destination: "185.22.14.99:443",
payload_mb: 580,
protocol: "TCP",
allowed: false,
verdict: "AlertAndLog"
},
status: "active",
score: 87
},
{
id: "alert-104",
timestamp: new Date(Date.now() - 9 * 60 * 1000 * 60).toISOString(), // 9h ago
source: "ebpf",
type: "ReverseShell",
severity: "Critical",
pid: 30211,
comm: "bash",
containerId: "cgroup-ops-o03",
podName: "gpu-operator-f762",
namespace: "gpu-operators",
description: "Interactive shell process spawned under container, redirecting standard input/output descriptors directly over remote SSH network connect socket",
details: {
terminal_path: "/bin/bash",
target_host: "45.10.12.3:8080",
socket_fd: 4,
verdict: "IsolateContainer"
},
status: "active",
score: 99
},
{
id: "alert-105",
timestamp: new Date(Date.now() - 4 * 60 * 1000 * 60).toISOString(), // 4h ago
source: "stats",
type: "Anomaly",
severity: "Medium",
pid: 8820,
comm: "python3",
containerId: "cgroup-default-d01",
podName: "tensorboard-logs",
namespace: "default",
description: "Abnormal memory consumption spike alongside unexpected file system file listing operations mapped under root workspace files",
details: {
memory_peak_mb: 1450,
fs_ops_per_sec: 1480,
confidence: 0.82,
verdict: "AlertAndLog"
},
status: "acknowledged",
score: 72
},
{
id: "alert-106",
timestamp: new Date(Date.now() - 2 * 60 * 1000 * 60).toISOString(), // 2h ago
source: "rules",
type: "PrivilegeEscalation",
severity: "Critical",
pid: 31050,
comm: "sudo",
containerId: "cgroup-ml-training-t01",
podName: "pytorch-dist-trainer-0",
namespace: "ml-training",
description: "Container privilege escalation detected: Local process attempted namespaces escape and write access to host node credential system state",
details: {
target_file: "/etc/shadow",
original_uid: 10001,
attempted_uid: 0,
verdict: "BlockAndQuarantine"
},
status: "active",
score: 95
}
];
let alertsDb: Alert[] = [...initialAlerts];
// Alerts API
app.get("/api/alerts", (req, res) => {
res.json(alertsDb);
});
// Simulate API
app.post("/api/alerts/simulate", (req, res) => {
const { category } = req.body;
const id = `sim-${Date.now()}`;
let newAlert: Alert;
switch (category) {
case "ModelTheft":
newAlert = {
id,
timestamp: new Date().toISOString(),
source: "rules",
type: "ModelTheft",
severity: "Critical",
pid: Math.floor(10000 + Math.random() * 20000),
comm: "python3",
containerId: `cgroup-ml-training-t${Math.floor(10 + Math.random() * 80)}`,
podName: `ray-worker-node-${Math.floor(1000 + Math.random() * 8999)}`,
namespace: "ml-training",
description: "Unauthorized process detected targeting Ray cluster storage nodes. Core Model weights exfiltration pattern detected.",
details: {
call: "do_sys_openat2",
path: "/opt/ml/models/model.safetensors",
uid: 10005,
flags: "O_RDONLY",
verdict: "BlockAccess"
},
status: "active",
score: 94
};
break;
case "CryptoMining":
newAlert = {
id,
timestamp: new Date().toISOString(),
source: "ebpf",
type: "CryptoMining",
severity: "Critical",
pid: Math.floor(10000 + Math.random() * 20000),
comm: "nicehash",
containerId: `cgroup-gpu-operator-${Math.floor(10 + Math.random() * 80)}`,
podName: `nv-gpu-telemetry-f55a`,
namespace: "gpu-operators",
description: "Intruder cryptomining binary spawned. Traced raw NVIDIA physical register ioctl operations matching hardware hijack profiles.",
details: {
ioctl_code: "0x2412",
device: "/dev/nvidiactl",
gpu_util_spike: "99.8%",
verdict: "KillProcess"
},
status: "active",
score: 98
};
break;
case "DataExfiltration":
newAlert = {
id,
timestamp: new Date().toISOString(),
source: "ebpf",
type: "DataExfiltration",
severity: "High",
pid: Math.floor(10000 + Math.random() * 20000),
comm: "rsync",
containerId: `cgroup-ml-inference-i${Math.floor(10 + Math.random() * 80)}`,
podName: `vllm-llama-node-8899`,
namespace: "ml-inference",
description: "Egress threat detection fired based on outbound socket tracing. Massive dataset exfiltration pattern matched.",
details: {
exfil_rate_mbps: 240,
target_dest: "45.10.88.204:22",
payload_mb: 850,
verdict: "AlertAndLog"
},
status: "active",
score: 89
};
break;
case "ReverseShell":
newAlert = {
id,
timestamp: new Date().toISOString(),
source: "ebpf",
type: "ReverseShell",
severity: "Critical",
pid: Math.floor(10000 + Math.random() * 20000),
comm: "sh",
containerId: `cgroup-kubeflow-k${Math.floor(10 + Math.random() * 80)}`,
podName: `kubeflow-dashboard-76e2`,
namespace: "kubeflow",
description: "Reverse interactive shell execution detected. Outgoing bash descriptors attached directly to a remote network socket.",
details: {
shell: "/bin/sh",
remote_host: "185.44.11.23:4444",
socket_id: 12,
verdict: "IsolateContainer"
},
status: "active",
score: 99
};
break;
case "PrivilegeEscalation":
newAlert = {
id,
timestamp: new Date().toISOString(),
source: "rules",
type: "PrivilegeEscalation",
severity: "Critical",
pid: Math.floor(10000 + Math.random() * 20000),
comm: "chroot",
containerId: `cgroup-default-d${Math.floor(10 + Math.random() * 80)}`,
podName: `nginx-ingress-controller`,
namespace: "default",
description: "Container breakout and privilege escalation detected. Local process triggered namespace mapping overrides.",
details: {
sys_call: "sys_setns",
original_gid: 10002,
attempted_uid: 0,
verdict: "BlockAndQuarantine"
},
status: "active",
score: 97
};
break;
default:
newAlert = {
id,
timestamp: new Date().toISOString(),
source: "stats",
type: "Anomaly",
severity: "Medium",
pid: Math.floor(10000 + Math.random() * 20000),
comm: "python3",
containerId: `cgroup-default-d${Math.floor(10 + Math.random() * 80)}`,
podName: `workspace-jupyter-85`,
namespace: "default",
description: "Telemetry anomaly scored above risk threshold: rapid file locks and memory overhead index spikes.",
details: {
anomaly_factors: ["memory_spike", "file_reads"],
deviation: "3.7 sigma",
verdict: "AlertAndLog"
},
status: "active",
score: 75
};
}
alertsDb.unshift(newAlert);
res.json(newAlert);
});
// Mitigate API
app.post("/api/alerts/:id/mitigate", (req, res) => {
const { id } = req.params;
const alert = alertsDb.find(a => a.id === id);
if (alert) {
alert.status = "mitigated";
res.json(alert);
} else {
res.status(404).json({ error: "Alert not found" });
}
});
// Clear API
app.post("/api/alerts/clear", (req, res) => {
alertsDb = [];
res.json({ message: "Alerts cleared successfully" });
});
// System Status API
app.get("/api/system/status", (req, res) => {
res.json({
ebpfProbesLoaded: true,
daemonStatus: "active",
kernelTelemetryQueueLen: Math.floor(Math.random() * 5),
eventsSkipped: 0,
cpuOverheadPercent: 0.12,
memoryUsageMb: 42.5,
totalNodesMonitored: 36,
activePodsMonitored: 820,
gpuMonitoredCount: 64,
probes: [
{ name: "sys_enter_execve", type: "tracepoint", state: "attached", events_count: 145020 },
{ name: "do_sys_openat2", type: "kprobe", state: "attached", events_count: 679011 },
{ name: "sys_enter_connect", type: "tracepoint", state: "attached", events_count: 11210 },
{ name: "nvidia_ioctl", type: "kprobe", state: "attached", events_count: 85220 }
],
telemetry: {
timestamp: new Date().toISOString(),
events_per_sec: Math.floor(1150 + Math.random() * 200),
cpu_usage: 0.12,
gpu_util_avg: 74.5,
gpu_leak_score: 1.2,
memory_pressure: 24,
network_mbps: 125,
fs_ops_per_sec: 8400
}
});
});
// Gemini Copilot Analyzer API
app.post("/api/copilot/analyze", async (req, res) => {
const { alertId } = req.body;
const alert = alertsDb.find(a => a.id === alertId);
if (!alert) {
return res.status(404).json({ error: "Alert not found" });
}
if (!ai) {
return res.json({
analysis: `### [MOCK CONTAINMENT REPORT]
Detected threat **${alert.type}** inside namespace **${alert.namespace}**.
#### EXECUTIVE ANALYTICS:
- **Alert ID**: \`${alert.id}\`
- **Component**: \`${alert.podName}\` (PID: ${alert.pid})
- **Severity**: **${alert.severity}**
- **Trigger**: System call manipulation patterns matching known malicious intent.
#### AUTOMATED RECOVERY PLAN:
1. **Host-Level Process Signal**: Emitted \`SIGKILL (9)\` to executing binary PID ${alert.pid} (\`${alert.comm}\`).
2. **Container Boundary Locking**: Isolated network sockets associated with sub-interface container identifier \`${alert.containerId}\`.
3. **Draft Network Isolation Policy**:
\`\`\`yaml
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: dynamic-isolate-${alert.podName}
namespace: ${alert.namespace}
spec:
podSelector:
matchLabels:
app.kubernetes.io/name: ${alert.comm}
policyTypes:
- Ingress
- Egress
\`\`\`
*Audit Log logged safely in SentinelML kernelring space.*`
});
}
try {
const prompt = `You are a Kubernetes Runtime Security Architect and Staff Linux Kernel Specialist.
Analyze this runtime security alert and output a markdown formatted containment report:
ALERT DATA:
- ID: ${alert.id}
- Timestamp: ${alert.timestamp}
- Type: ${alert.type}
- Severity: ${alert.severity}
- Executable name: ${alert.comm}
- PID: ${alert.pid}
- Container ID: ${alert.containerId}
- Pod Name: ${alert.podName}
- Namespace: ${alert.namespace}
- Threat Trigger: ${alert.description}
- Raw Kernel Context: ${JSON.stringify(alert.details)}
- Threat Risk Score: ${alert.score}%
Please format the response with:
1. Threat Diagnostics (brief and highly technical systems breakdown)
2. Containment Plan (target process termination, container quarantine)
3. Kubernetes NetworkPolicy YAML block to isolate the Pod "${alert.podName}" inside Namespace "${alert.namespace}".`;
const response = await ai.models.generateContent({
model: "gemini-3.5-flash",
contents: prompt,
});
res.json({ analysis: response.text });
} catch (error: any) {
res.status(500).json({ error: error.message });
}
});
// Start Server Loop
async function startServer() {
if (process.env.NODE_ENV !== "production") {
const vite = await createViteServer({
server: { middlewareMode: true },
appType: "spa",
});
app.use(vite.middlewares);
} else {
const distPath = path.join(process.cwd(), 'dist');
app.use(express.static(distPath));
app.get('*', (req, res) => {
res.sendFile(path.join(distPath, 'index.html'));
});
}
app.listen(PORT, "0.0.0.0", () => {
console.log(`Server running on http://localhost:${PORT}`);
});
}
startServer();